blob: 6d1c9fc1fbaa94cd7882e38b072a183be47dad19 [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>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080047#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070049#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080051#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080052#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080053#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070054#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070055#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070056#include <ui/ColorSpace.h>
57#include <ui/DebugUtils.h>
58#include <ui/DisplayInfo.h>
59#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070060#include <ui/GraphicBufferAllocator.h>
61#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070062#include <ui/UiConfig.h>
Ady Abraham8164d482019-01-11 14:47:59 -080063#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070065#include <utils/String16.h>
66#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070067#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080068#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070069#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080070
Mathias Agopian921e6ac2012-07-23 23:11:29 -070071#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070072#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073
Robert Carr578038f2018-03-09 12:25:24 -080074#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070075#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070076#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020077#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020079#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080080#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080081#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070083#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080084#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070085#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070086#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080087#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070088#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089
Steven Thomasb02664d2017-07-26 18:48:28 -070090#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070091#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070092#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070093#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070094#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070095#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070096#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070097#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070098#include "Scheduler/EventControlThread.h"
99#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700100#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700101#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700102#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800103#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700104
Mathias Agopianff2ed702013-09-01 21:36:12 -0700105#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700106
David Sodman7e4ae112018-02-09 15:02:28 -0800107#include "android-base/stringprintf.h"
108
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900109#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800110#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700111#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800112#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900113#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900114
chaviw1d044282017-09-27 12:19:28 -0700115#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900116#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700117
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800118namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700119
Jaesoo Lee43518572017-01-23 19:03:16 +0900120using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900121using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900122using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800123
Yiwei Zhang5434a782018-12-05 18:06:32 -0800124using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700125using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700126using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800127using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700128using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700129using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900130
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800131using RefreshRateType = scheduler::RefreshRateConfigs::RefreshRateType;
132
Steven Thomasb02664d2017-07-26 18:48:28 -0700133namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700134
135#pragma clang diagnostic push
136#pragma clang diagnostic error "-Wswitch-enum"
137
138bool isWideColorMode(const ColorMode colorMode) {
139 switch (colorMode) {
140 case ColorMode::DISPLAY_P3:
141 case ColorMode::ADOBE_RGB:
142 case ColorMode::DCI_P3:
143 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700144 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700145 case ColorMode::BT2100_PQ:
146 case ColorMode::BT2100_HLG:
147 return true;
148 case ColorMode::NATIVE:
149 case ColorMode::STANDARD_BT601_625:
150 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
151 case ColorMode::STANDARD_BT601_525:
152 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
153 case ColorMode::STANDARD_BT709:
154 case ColorMode::SRGB:
155 return false;
156 }
157 return false;
158}
159
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700160ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
161 switch (rotation) {
162 case ISurfaceComposer::eRotateNone:
163 return ui::Transform::ROT_0;
164 case ISurfaceComposer::eRotate90:
165 return ui::Transform::ROT_90;
166 case ISurfaceComposer::eRotate180:
167 return ui::Transform::ROT_180;
168 case ISurfaceComposer::eRotate270:
169 return ui::Transform::ROT_270;
170 }
171 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
172 return ui::Transform::ROT_0;
173}
174
Peiyong Linfca547f2018-07-09 13:03:33 -0700175#pragma clang diagnostic pop
176
Steven Thomasb02664d2017-07-26 18:48:28 -0700177class ConditionalLock {
178public:
179 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
180 if (lock) {
181 mMutex.lock();
182 }
183 }
184 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
185private:
186 Mutex& mMutex;
187 bool mLocked;
188};
Peiyong Linfca547f2018-07-09 13:03:33 -0700189
Peiyong Lin9d846a52018-11-05 13:18:20 -0800190// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
191bool validateCompositionDataspace(Dataspace dataspace) {
192 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
193}
194
Steven Thomasb02664d2017-07-26 18:48:28 -0700195} // namespace anonymous
196
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800197// ---------------------------------------------------------------------------
198
Mathias Agopian99b49842011-06-27 16:05:52 -0700199const String16 sHardwareTest("android.permission.HARDWARE_TEST");
200const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
201const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
202const String16 sDump("android.permission.DUMP");
203
Daniel Solomon42d04562019-01-20 21:03:19 -0800204constexpr float kSrgbRedX = 0.4123f;
205constexpr float kSrgbRedY = 0.2126f;
206constexpr float kSrgbRedZ = 0.0193f;
207constexpr float kSrgbGreenX = 0.3576f;
208constexpr float kSrgbGreenY = 0.7152f;
209constexpr float kSrgbGreenZ = 0.1192f;
210constexpr float kSrgbBlueX = 0.1805f;
211constexpr float kSrgbBlueY = 0.0722f;
212constexpr float kSrgbBlueZ = 0.9506f;
213constexpr float kSrgbWhiteX = 0.9505f;
214constexpr float kSrgbWhiteY = 1.0000f;
215constexpr float kSrgbWhiteZ = 1.0891f;
216
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800217constexpr float kDefaultRefreshRate = 60.f;
218constexpr float kPerformanceRefreshRate = 90.f;
219
Mathias Agopian99b49842011-06-27 16:05:52 -0700220// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700221int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700222bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800223uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800224bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800225bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800226int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600227bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700228int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700229bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700230bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700231Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
232ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
233Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
234ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700235
Kalle Raitaa099a242017-01-11 11:17:29 -0800236std::string getHwcServiceName() {
237 char value[PROPERTY_VALUE_MAX] = {};
238 property_get("debug.sf.hwc_service_name", value, "default");
239 ALOGI("Using HWComposer service: '%s'", value);
240 return std::string(value);
241}
242
243bool useTrebleTestingOverride() {
244 char value[PROPERTY_VALUE_MAX] = {};
245 property_get("debug.sf.treble_testing_override", value, "false");
246 ALOGI("Treble testing override: '%s'", value);
247 return std::string(value) == "true";
248}
249
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800250std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
251 switch(displayColorSetting) {
252 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700253 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800254 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700255 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800256 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700257 return std::string("Enhanced");
258 default:
259 return std::string("Unknown ") +
260 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800261 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800262}
263
David Sodmanbc815282017-11-05 18:57:52 -0800264SurfaceFlingerBE::SurfaceFlingerBE()
265 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800266 mFrameBuckets(),
267 mTotalTime(0),
268 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800269 mComposerSequenceId(0) {
270}
271
Lloyd Pique90c115d2018-09-18 21:39:42 -0700272SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
273 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800274 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700275 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700276 mTransactionPending(false),
277 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700278 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700279 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800280 mBootTime(systemTime()),
Ana Krulec757f63a2019-01-25 10:46:18 -0800281 mPhaseOffsets{getFactory().createPhaseOffsets()},
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800282 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800283 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800284 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800285 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800286 mDebugRegion(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700287 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700288 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700289 mDebugInTransaction(0),
290 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700291 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800292 mTimeStats(factory.createTimeStats()),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700293 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700294 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800295 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800296 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800297 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700298 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700299 mMainThreadId(std::this_thread::get_id()),
300 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800301
Lloyd Pique90c115d2018-09-18 21:39:42 -0700302SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
303 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800304 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800305
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900306 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800307
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700309
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900310 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700311
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900312 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800313
Steven Thomas050b2c82017-03-06 11:45:16 -0800314 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900315 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800316
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900317 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800318
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900319 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700320
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900321 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600322
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900323 mDefaultCompositionDataspace =
324 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
325 mWideColorGamutCompositionDataspace =
326 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
327 defaultCompositionDataspace = mDefaultCompositionDataspace;
328 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
329 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
330 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
331 wideColorGamutCompositionPixelFormat =
332 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700333
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900334 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800335
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900336 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
337 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
338 switch (tmpPrimaryDisplayOrientation) {
339 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700340 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800341 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900342 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700343 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800344 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900345 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700346 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800347 break;
348 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700349 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800350 break;
351 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700352 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800353
Daniel Solomon42d04562019-01-20 21:03:19 -0800354 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
355 if (surfaceFlingerConfigsServiceV1_2) {
356 surfaceFlingerConfigsServiceV1_2->getDisplayNativePrimaries(
357 [&](auto tmpPrimaries) {
358 memcpy(&mInternalDisplayPrimaries, &tmpPrimaries, sizeof(ui::DisplayPrimaries));
359 });
360 } else {
361 initDefaultDisplayNativePrimaries();
362 }
363
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800364 // debugging stuff...
365 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700366
Mathias Agopianb4b17302013-03-20 18:36:41 -0700367 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700368 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700369
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800370 property_get("debug.sf.showupdates", value, "0");
371 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700372
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700373 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000374
375 // DDMS debugging deprecated (b/120782499)
376 property_get("debug.sf.ddms", value, "0");
377 int debugDdms = atoi(value);
378 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700379
380 property_get("debug.sf.disable_backpressure", value, "0");
381 mPropagateBackpressure = !atoi(value);
382 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700383
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800384 property_get("debug.sf.enable_hwc_vds", value, "0");
385 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800386 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800387
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800388 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800389 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800390 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700391
Yiwei Zhang243b3782018-05-15 17:40:04 -0700392 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700393 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
394 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
395
Ana Krulec98b5b242018-08-10 15:03:23 -0700396 property_get("debug.sf.use_scheduler", value, "0");
397 mUseScheduler = atoi(value);
398
Ady Abrahamc3e21312019-02-07 14:30:23 -0800399 if (!mUseScheduler) {
400 mPrimaryDispSync =
401 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
402 SurfaceFlinger::dispSyncPresentTimeOffset);
403 }
404
Ana Krulec757f63a2019-01-25 10:46:18 -0800405 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
406 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700407
Romain Guy11d63f42017-07-20 12:47:14 -0700408 // We should be reading 'persist.sys.sf.color_saturation' here
409 // but since /data may be encrypted, we need to wait until after vold
410 // comes online to attempt to read the property. The property is
411 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800412
413 if (useTrebleTestingOverride()) {
414 // Without the override SurfaceFlinger cannot connect to HIDL
415 // services that are not listed in the manifests. Considered
416 // deriving the setting from the set service name, but it
417 // would be brittle if the name that's not 'default' is used
418 // for production purposes later on.
419 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
420 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800421}
422
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800423void SurfaceFlinger::onFirstRef()
424{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800425 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800426}
427
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800428SurfaceFlinger::~SurfaceFlinger()
429{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800430}
431
Dan Stozac7014012014-02-14 15:03:43 -0800432void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800433{
434 // the window manager died on us. prepare its eulogy.
435
Andy McFadden13a082e2012-08-24 10:16:42 -0700436 // restore initial conditions (default device unblank, etc)
437 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800438
439 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700440 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800441}
442
Robert Carr1db73f62016-12-21 12:58:51 -0800443static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700444 status_t err = client->initCheck();
445 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800446 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800447 }
Robert Carr1db73f62016-12-21 12:58:51 -0800448 return nullptr;
449}
450
451sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
452 return initClient(new Client(this));
453}
454
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700455sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
456 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700457{
458 class DisplayToken : public BBinder {
459 sp<SurfaceFlinger> flinger;
460 virtual ~DisplayToken() {
461 // no more references, this display must be terminated
462 Mutex::Autolock _l(flinger->mStateLock);
463 flinger->mCurrentState.displays.removeItem(this);
464 flinger->setTransactionFlags(eDisplayTransactionNeeded);
465 }
466 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700467 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700468 : flinger(flinger) {
469 }
470 };
471
472 sp<BBinder> token = new DisplayToken(this);
473
474 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700475 // Display ID is assigned when virtual display is allocated by HWC.
476 DisplayDeviceState state;
477 state.isSecure = secure;
478 state.displayName = displayName;
479 mCurrentState.displays.add(token, state);
480 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700481 return token;
482}
483
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700484void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700485 Mutex::Autolock _l(mStateLock);
486
Dominik Laskowski075d3172018-05-24 15:50:06 -0700487 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
488 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700489 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700490 return;
491 }
492
Dominik Laskowski075d3172018-05-24 15:50:06 -0700493 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
494 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700495 ALOGE("destroyDisplay called for non-virtual display");
496 return;
497 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700498 mInterceptor->saveDisplayDeletion(state.sequenceId);
499 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700500 setTransactionFlags(eDisplayTransactionNeeded);
501}
502
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800503std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
504 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700505
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800506 const auto internalDisplayId = getInternalDisplayIdLocked();
507 if (!internalDisplayId) {
508 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700509 }
510
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800511 std::vector<PhysicalDisplayId> displayIds;
512 displayIds.reserve(mPhysicalDisplayTokens.size());
513 displayIds.push_back(internalDisplayId->value);
514
515 for (const auto& [id, token] : mPhysicalDisplayTokens) {
516 if (id != *internalDisplayId) {
517 displayIds.push_back(id.value);
518 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700519 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700520
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800521 return displayIds;
522}
523
524sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
525 Mutex::Autolock lock(mStateLock);
526 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700527}
528
Ady Abraham37965d42018-11-01 13:43:32 -0700529status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
530 if (!outGetColorManagement) {
531 return BAD_VALUE;
532 }
533 *outGetColorManagement = useColorManagement;
534 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700535}
536
Lloyd Pique441d5042018-10-18 16:49:51 -0700537HWComposer& SurfaceFlinger::getHwComposer() const {
538 return mCompositionEngine->getHwComposer();
539}
540
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700541renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
542 return mCompositionEngine->getRenderEngine();
543}
544
Lloyd Pique70d91362018-10-18 16:02:55 -0700545compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
546 return *mCompositionEngine.get();
547}
548
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800549void SurfaceFlinger::bootFinished()
550{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700551 if (mStartPropertySetThread->join() != NO_ERROR) {
552 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800553 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800554 const nsecs_t now = systemTime();
555 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000556 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700557
558 // wait patiently for the window manager death
559 const String16 name("window");
560 sp<IBinder> window(defaultServiceManager()->getService(name));
561 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700562 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700563 }
Robert Carr720e5062018-07-30 17:45:14 -0700564 sp<IBinder> input(defaultServiceManager()->getService(
565 String16("inputflinger")));
566 if (input == nullptr) {
567 ALOGE("Failed to link to input service");
568 } else {
569 mInputFlinger = interface_cast<IInputFlinger>(input);
570 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700571
Steven Thomas050b2c82017-03-06 11:45:16 -0800572 if (mVrFlinger) {
573 mVrFlinger->OnBootFinished();
574 }
575
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700576 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700577 // formerly we would just kill the process, but we now ask it to exit so it
578 // can choose where to stop the animation.
579 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700580
581 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
582 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
583 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700584
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800585 postMessageAsync(new LambdaMessage([this] {
586 readPersistentProperties();
587 mBootStage = BootStage::FINISHED;
588 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800589}
590
Dan Stoza436ccf32018-06-21 12:10:12 -0700591uint32_t SurfaceFlinger::getNewTexture() {
592 {
593 std::lock_guard lock(mTexturePoolMutex);
594 if (!mTexturePool.empty()) {
595 uint32_t name = mTexturePool.back();
596 mTexturePool.pop_back();
597 ATRACE_INT("TexturePoolSize", mTexturePool.size());
598 return name;
599 }
600
601 // The pool was too small, so increase it for the future
602 ++mTexturePoolSize;
603 }
604
605 // The pool was empty, so we need to get a new texture name directly using a
606 // blocking call to the main thread
607 uint32_t name = 0;
608 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
609 return name;
610}
611
Mathias Agopian3f844832013-08-07 21:24:32 -0700612void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700613 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700614}
615
Wei Wangf9b05ee2017-07-19 20:59:39 -0700616// Do not call property_set on main thread which will be blocked by init
617// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700618void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700619 ALOGI( "SurfaceFlinger's main thread ready to run. "
620 "Initializing graphics H/W...");
621
Ana Krulec757f63a2019-01-25 10:46:18 -0800622 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900623
Steven Thomasb02664d2017-07-26 18:48:28 -0700624 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800625
Dominik Laskowski83b88212018-12-11 13:34:06 -0800626 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -0800627
Steven Thomasb02664d2017-07-26 18:48:28 -0700628 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700629 if (mUseScheduler) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800630 mScheduler = getFactory().createScheduler(
631 [this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
632
Ana Krulec757f63a2019-01-25 10:46:18 -0800633 // TODO(b/113612090): Currently we assume that if scheduler is turned on, then the refresh
634 // rate is 90. Once b/122905403 is completed, this should be updated accordingly.
635 mPhaseOffsets->setRefreshRateType(
636 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700637
Ana Krulec98b5b242018-08-10 15:03:23 -0700638 mAppConnectionHandle =
Ady Abraham3aff9172019-02-07 19:10:26 -0800639 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
Ady Abrahama1a49af2019-02-07 14:36:55 -0800640 resyncCallback,
Ana Krulec98b5b242018-08-10 15:03:23 -0700641 impl::EventThread::InterceptVSyncsCallback());
642 mSfConnectionHandle =
Ady Abraham3aff9172019-02-07 19:10:26 -0800643 mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
Ady Abrahama1a49af2019-02-07 14:36:55 -0800644 resyncCallback, [this](nsecs_t timestamp) {
Ana Krulec98b5b242018-08-10 15:03:23 -0700645 mInterceptor->saveVSyncEvent(timestamp);
646 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800647
Ana Krulec98b5b242018-08-10 15:03:23 -0700648 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700649 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
650 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700651 } else {
652 mEventThreadSource =
653 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800654 mPhaseOffsets->getCurrentAppOffset(), true, "app");
Ana Krulec98b5b242018-08-10 15:03:23 -0700655 mEventThread =
656 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700657 impl::EventThread::InterceptVSyncsCallback(),
658 "appEventThread");
659 mSfEventThreadSource =
660 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800661 mPhaseOffsets->getCurrentSfOffset(), true, "sf");
Ana Krulec98b5b242018-08-10 15:03:23 -0700662
663 mSFEventThread =
664 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700665 [this](nsecs_t timestamp) {
666 mInterceptor->saveVSyncEvent(timestamp);
667 },
668 "sfEventThread");
Dominik Laskowskif654d572018-12-20 11:03:06 -0800669 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Ana Krulec98b5b242018-08-10 15:03:23 -0700670 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
671 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800672
Steven Thomasb02664d2017-07-26 18:48:28 -0700673 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700674 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700675 renderEngineFeature |= (useColorManagement ?
676 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700677 renderEngineFeature |= (useContextPriority ?
678 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700679
680 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700681 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700682 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700683 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700684
685 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
686 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700687 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
688 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800689 // Process any initial hotplug and resulting display changes.
690 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700691 const auto display = getDefaultDisplayDeviceLocked();
692 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700693 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700694 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800695
Steven Thomas050b2c82017-03-06 11:45:16 -0800696 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700697 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700698 // This callback is called from the vr flinger dispatch thread. We
699 // need to call signalTransaction(), which requires holding
700 // mStateLock when we're not on the main thread. Acquiring
701 // mStateLock from the vr flinger dispatch thread might trigger a
702 // deadlock in surface flinger (see b/66916578), so post a message
703 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700704 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700705 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
706 mVrFlingerRequestsDisplay = requestDisplay;
707 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700708 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800709 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700710 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
711 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700712 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700713 .value_or(0),
714 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800715 if (!mVrFlinger) {
716 ALOGE("Failed to start vrflinger");
717 }
718 }
719
Ady Abrahamc3e21312019-02-07 14:30:23 -0800720 if (!mUseScheduler) {
721 mEventControlThread = getFactory().createEventControlThread(
722 [this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
723 }
Jamie Gennisd1700752013-10-14 12:22:52 -0700724
Mathias Agopian92a979a2012-08-02 18:32:23 -0700725 // initialize our drawing state
726 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700727
Andy McFadden13a082e2012-08-24 10:16:42 -0700728 // set initial conditions (e.g. unblank default device)
729 initializeDisplays();
730
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700731 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700732
Wei Wangf9b05ee2017-07-19 20:59:39 -0700733 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700734
735 const bool presentFenceReliable =
736 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
737 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700738
739 if (mStartPropertySetThread->Start() != NO_ERROR) {
740 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800741 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800742
Ana Krulec7d1d6832018-12-27 11:10:09 -0800743 if (mUseScheduler) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800744 mScheduler->setExpiredIdleTimerCallback([this] {
745 Mutex::Autolock lock(mStateLock);
746 setRefreshRateTo(RefreshRateType::DEFAULT);
Ana Krulec757f63a2019-01-25 10:46:18 -0800747 });
Ady Abrahama1a49af2019-02-07 14:36:55 -0800748 mScheduler->setResetIdleTimerCallback([this] {
749 Mutex::Autolock lock(mStateLock);
750 setRefreshRateTo(RefreshRateType::PERFORMANCE);
751 });
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800752
Alec Mourifb571ea2019-01-24 18:42:10 -0800753 mRefreshRateStats =
754 std::make_unique<scheduler::RefreshRateStats>(getHwComposer().getConfigs(
755 *display->getId()),
756 mTimeStats);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800757 }
758
Dan Stoza9e56aa02015-11-02 13:00:03 -0800759 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700760}
761
Romain Guy11d63f42017-07-20 12:47:14 -0700762void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700763 Mutex::Autolock _l(mStateLock);
764
Romain Guy11d63f42017-07-20 12:47:14 -0700765 char value[PROPERTY_VALUE_MAX];
766
767 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800768 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700769 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800770 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100771
772 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700773 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800774
775 property_get("persist.sys.sf.color_mode", value, "0");
776 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700777}
778
Mathias Agopiana67e4182012-06-19 17:26:12 -0700779void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800780 // Start boot animation service by setting a property mailbox
781 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700782 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800783 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700784 if (mStartPropertySetThread->join() != NO_ERROR) {
785 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800786 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700787}
788
Mathias Agopian875d8e12013-06-07 15:35:48 -0700789size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700790 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700791}
792
Mathias Agopian875d8e12013-06-07 15:35:48 -0700793size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700794 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700795}
796
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800797// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800798
Jamie Gennis582270d2011-08-17 18:19:00 -0700799bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800800 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800801 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800802 return authenticateSurfaceTextureLocked(bufferProducer);
803}
804
805bool SurfaceFlinger::authenticateSurfaceTextureLocked(
806 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800807 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800808 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800809}
810
Brian Anderson6b376712017-04-04 10:51:39 -0700811status_t SurfaceFlinger::getSupportedFrameTimestamps(
812 std::vector<FrameEvent>* outSupported) const {
813 *outSupported = {
814 FrameEvent::REQUESTED_PRESENT,
815 FrameEvent::ACQUIRE,
816 FrameEvent::LATCH,
817 FrameEvent::FIRST_REFRESH_START,
818 FrameEvent::LAST_REFRESH_START,
819 FrameEvent::GPU_COMPOSITION_DONE,
820 FrameEvent::DEQUEUE_READY,
821 FrameEvent::RELEASE,
822 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700823 ConditionalLock _l(mStateLock,
824 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700825 if (!getHwComposer().hasCapability(
826 HWC2::Capability::PresentFenceIsNotReliable)) {
827 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
828 }
829 return NO_ERROR;
830}
831
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800832status_t SurfaceFlinger::getDisplayConfigsLocked(const sp<IBinder>& displayToken,
833 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700834 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700835 return BAD_VALUE;
836 }
837
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800838 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700839 if (!displayId) {
840 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700841 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700842
Mathias Agopian8b736f12012-08-13 17:54:26 -0700843 // TODO: Not sure if display density should handled by SF any longer
844 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700845 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700846 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700847 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800848 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700849 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700850 }
851 return density;
852 }
853 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700854 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700855 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700856 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700857 return getDensityFromProperty("ro.sf.lcd_density"); }
858 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700859
Dan Stoza7f7da322014-05-02 15:26:25 -0700860 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700861
Dominik Laskowski075d3172018-05-24 15:50:06 -0700862 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700863 DisplayInfo info = DisplayInfo();
864
Dan Stoza9e56aa02015-11-02 13:00:03 -0800865 float xdpi = hwConfig->getDpiX();
866 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700867
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700868 info.w = hwConfig->getWidth();
869 info.h = hwConfig->getHeight();
870 // Default display viewport to display width and height
871 info.viewportW = info.w;
872 info.viewportH = info.h;
873
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800874 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700875 // The density of the device is provided by a build property
876 float density = Density::getBuildDensity() / 160.0f;
877 if (density == 0) {
878 // the build doesn't provide a density -- this is wrong!
879 // use xdpi instead
880 ALOGE("ro.sf.lcd_density must be defined as a build property");
881 density = xdpi / 160.0f;
882 }
883 if (Density::getEmuDensity()) {
884 // if "qemu.sf.lcd_density" is specified, it overrides everything
885 xdpi = ydpi = density = Density::getEmuDensity();
886 density /= 160.0f;
887 }
888 info.density = density;
889
890 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700891 const auto display = getDefaultDisplayDeviceLocked();
892 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700893
894 // This is for screenrecord
895 const Rect viewport = display->getViewport();
896 if (viewport.isValid()) {
897 info.viewportW = uint32_t(viewport.getWidth());
898 info.viewportH = uint32_t(viewport.getHeight());
899 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700900 } else {
901 // TODO: where should this value come from?
902 static const int TV_DENSITY = 213;
903 info.density = TV_DENSITY / 160.0f;
904 info.orientation = 0;
905 }
906
Dan Stoza7f7da322014-05-02 15:26:25 -0700907 info.xdpi = xdpi;
908 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800909 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800910 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800911
Andy McFadden91b2ca82014-06-13 14:04:23 -0700912 // This is how far in advance a buffer must be queued for
913 // presentation at a given time. If you want a buffer to appear
914 // on the screen at time N, you must submit the buffer before
915 // (N - presentationDeadline).
916 //
917 // Normally it's one full refresh period (to give SF a chance to
918 // latch the buffer), but this can be reduced by configuring a
919 // DispSync offset. Any additional delays introduced by the hardware
920 // composer or panel must be accounted for here.
921 //
922 // We add an additional 1ms to allow for processing time and
923 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800924 info.presentationDeadline =
925 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700926
927 // All non-virtual displays are currently considered secure.
928 info.secure = true;
929
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800930 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700931 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800932 std::swap(info.w, info.h);
933 }
934
Michael Wright28f24d02016-07-12 13:30:53 -0700935 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700936 }
937
Dan Stoza7f7da322014-05-02 15:26:25 -0700938 return NO_ERROR;
939}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700940
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700941status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
942 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700943 return BAD_VALUE;
944 }
945
Ana Krulece588e312018-09-18 12:32:24 -0700946 if (mUseScheduler) {
947 mScheduler->getDisplayStatInfo(stats);
948 } else {
949 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
950 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
951 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700952 return NO_ERROR;
953}
954
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700955int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
956 const auto display = getDisplayDevice(displayToken);
957 if (!display) {
958 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800959 return BAD_VALUE;
960 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700961
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700962 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700963}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700964
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800965void SurfaceFlinger::setDesiredActiveConfig(const sp<IBinder>& displayToken, int mode) {
966 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800967
Ana Krulec7d1d6832018-12-27 11:10:09 -0800968 Vector<DisplayInfo> configs;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800969 // Lock is acquired by setRefreshRateTo.
970 getDisplayConfigsLocked(displayToken, &configs);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800971 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
972 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
973 return;
974 }
975
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800976 // Lock is acquired by setRefreshRateTo.
977 const auto display = getDisplayDeviceLocked(displayToken);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800978 if (!display) {
979 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
980 displayToken.get());
981 return;
982 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700983 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800984 ALOGW("Attempt to set active config %d for virtual display", mode);
985 return;
986 }
987 int currentDisplayPowerMode = display->getPowerMode();
988 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
989 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700990 return;
991 }
992
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800993 // Don't check against the current mode yet. Worst case we set the desired
994 // config twice.
995 {
996 std::lock_guard<std::mutex> lock(mActiveConfigLock);
997 mDesiredActiveConfig = ActiveConfigInfo{mode, displayToken};
998 }
999 // This will trigger HWC refresh without resetting the idle timer.
1000 repaintEverythingForHWC();
1001}
1002
1003status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
1004 ATRACE_CALL();
1005 postMessageSync(new LambdaMessage(
1006 [&]() NO_THREAD_SAFETY_ANALYSIS { setDesiredActiveConfig(displayToken, mode); }));
1007 return NO_ERROR;
1008}
1009
1010void SurfaceFlinger::setActiveConfigInHWC() {
1011 ATRACE_CALL();
1012
1013 const auto display = getDisplayDevice(mUpcomingActiveConfig.displayToken);
1014 if (!display) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001015 return;
1016 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001017 const auto displayId = display->getId();
1018 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001019
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001020 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1021 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1022 mSetActiveConfigState = SetActiveConfigState::NOTIFIED_HWC;
1023 ATRACE_INT("SetActiveConfigState", mSetActiveConfigState);
1024}
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001025
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001026void SurfaceFlinger::setActiveConfigInternal() {
1027 ATRACE_CALL();
1028
1029 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1030 if (mUseScheduler) {
1031 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
1032 }
1033
1034 const auto display = getDisplayDeviceLocked(mUpcomingActiveConfig.displayToken);
1035 display->setActiveConfig(mUpcomingActiveConfig.configId);
1036
1037 mSetActiveConfigState = SetActiveConfigState::NONE;
1038 ATRACE_INT("SetActiveConfigState", mSetActiveConfigState);
1039
Dominik Laskowski83b88212018-12-11 13:34:06 -08001040 resyncToHardwareVsync(true, getVsyncPeriod());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001041 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
1042}
1043
1044bool SurfaceFlinger::updateSetActiveConfigStateMachine() NO_THREAD_SAFETY_ANALYSIS {
1045 // Store the local variable to release the lock.
1046 ActiveConfigInfo desiredActiveConfig;
1047 {
1048 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1049 desiredActiveConfig = mDesiredActiveConfig;
1050 }
1051
1052 const auto display = getDisplayDevice(desiredActiveConfig.displayToken);
1053 if (display) {
1054 if (mSetActiveConfigState == SetActiveConfigState::NONE &&
1055 display->getActiveConfig() != desiredActiveConfig.configId) {
1056 // Step 1) Desired active config was set, it is different than the
1057 // config currently in use. Notify HWC.
1058 mUpcomingActiveConfig = desiredActiveConfig;
1059 setActiveConfigInHWC();
1060 } else if (mSetActiveConfigState == SetActiveConfigState::NOTIFIED_HWC) {
1061 // Step 2) HWC was notified and we received refresh from it.
1062 mSetActiveConfigState = SetActiveConfigState::REFRESH_RECEIVED;
1063 ATRACE_INT("SetActiveConfigState", mSetActiveConfigState);
1064 repaintEverythingForHWC();
1065 // We do not want to give another frame to HWC while we are transitioning.
1066 return false;
1067 } else if (mSetActiveConfigState == SetActiveConfigState::REFRESH_RECEIVED &&
1068 !(mPreviousPresentFence != Fence::NO_FENCE &&
1069 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled))) {
1070 // Step 3) We received the present fence from the HWC, so we assume it
1071 // successfully updated the config, hence we update SF.
1072 setActiveConfigInternal();
1073 // If the config changed again while we were transitioning, restart the
1074 // process.
1075 if (desiredActiveConfig != mUpcomingActiveConfig) {
1076 mUpcomingActiveConfig = desiredActiveConfig;
1077 setActiveConfigInHWC(); // sets the state to NOTIFY_HWC
1078 }
1079 }
1080 }
1081 return true;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001082}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001083
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001084status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1085 Vector<ColorMode>* outColorModes) {
1086 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001087 return BAD_VALUE;
1088 }
1089
Peiyong Lina52f0292018-03-14 17:26:31 -07001090 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001091 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001092 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1093
1094 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1095 if (!displayId) {
1096 return NAME_NOT_FOUND;
1097 }
1098
Dominik Laskowski075d3172018-05-24 15:50:06 -07001099 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001100 }
Michael Wright28f24d02016-07-12 13:30:53 -07001101 outColorModes->clear();
1102 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1103
1104 return NO_ERROR;
1105}
1106
Daniel Solomon42d04562019-01-20 21:03:19 -08001107status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1108 ui::DisplayPrimaries &primaries) {
1109 if (!displayToken) {
1110 return BAD_VALUE;
1111 }
1112
1113 // Currently we only support this API for a single internal display.
1114 if (getInternalDisplayToken() != displayToken) {
1115 return BAD_VALUE;
1116 }
1117
1118 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1119 return NO_ERROR;
1120}
1121
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001122ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1123 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001124 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001125 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001126 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001127}
1128
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001129status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001130 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001131 Vector<ColorMode> modes;
1132 getDisplayColorModes(displayToken, &modes);
1133 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1134 if (mode < ColorMode::NATIVE || !exists) {
1135 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1136 decodeColorMode(mode).c_str(), mode, displayToken.get());
1137 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001138 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001139 const auto display = getDisplayDevice(displayToken);
1140 if (!display) {
1141 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1142 decodeColorMode(mode).c_str(), mode, displayToken.get());
1143 } else if (display->isVirtual()) {
1144 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1145 decodeColorMode(mode).c_str(), mode);
1146 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001147 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1148 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001149 }
1150 }));
1151
Michael Wright28f24d02016-07-12 13:30:53 -07001152 return NO_ERROR;
1153}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001154
Svetoslavd85084b2014-03-20 10:28:31 -07001155status_t SurfaceFlinger::clearAnimationFrameStats() {
1156 Mutex::Autolock _l(mStateLock);
1157 mAnimFrameTracker.clearStats();
1158 return NO_ERROR;
1159}
1160
1161status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1162 Mutex::Autolock _l(mStateLock);
1163 mAnimFrameTracker.getStats(outStats);
1164 return NO_ERROR;
1165}
1166
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001167status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1168 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001169 Mutex::Autolock _l(mStateLock);
1170
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001171 const auto display = getDisplayDeviceLocked(displayToken);
1172 if (!display) {
1173 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001174 return BAD_VALUE;
1175 }
1176
Peiyong Linfb069302018-04-25 14:34:31 -07001177 // At this point the DisplayDeivce should already be set up,
1178 // meaning the luminance information is already queried from
1179 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001180 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001181 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1182 capabilities.getDesiredMaxLuminance(),
1183 capabilities.getDesiredMaxAverageLuminance(),
1184 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001185
1186 return NO_ERROR;
1187}
1188
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001189status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1190 ui::PixelFormat* outFormat,
1191 ui::Dataspace* outDataspace,
1192 uint8_t* outComponentMask) const {
1193 if (!outFormat || !outDataspace || !outComponentMask) {
1194 return BAD_VALUE;
1195 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001196 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001197 if (!display || !display->getId()) {
1198 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1199 return BAD_VALUE;
1200 }
1201 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1202 outDataspace, outComponentMask);
1203}
1204
Kevin DuBois74e53772018-11-19 10:52:38 -08001205status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1206 bool enable, uint8_t componentMask,
1207 uint64_t maxFrames) const {
1208 const auto display = getDisplayDevice(displayToken);
1209 if (!display || !display->getId()) {
1210 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1211 return BAD_VALUE;
1212 }
1213
1214 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1215 componentMask, maxFrames);
1216}
1217
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001218status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1219 uint64_t maxFrames, uint64_t timestamp,
1220 DisplayedFrameStats* outStats) const {
1221 const auto display = getDisplayDevice(displayToken);
1222 if (!display || !display->getId()) {
1223 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1224 return BAD_VALUE;
1225 }
1226
1227 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1228 outStats);
1229}
1230
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001231status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1232 if (!outSupported) {
1233 return BAD_VALUE;
1234 }
1235 *outSupported = getRenderEngine().supportsProtectedContent();
1236 return NO_ERROR;
1237}
1238
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001239status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1240 bool* outIsWideColorDisplay) const {
1241 if (!displayToken || !outIsWideColorDisplay) {
1242 return BAD_VALUE;
1243 }
1244 Mutex::Autolock _l(mStateLock);
1245 const auto display = getDisplayDeviceLocked(displayToken);
1246 if (!display) {
1247 return BAD_VALUE;
1248 }
1249 *outIsWideColorDisplay = display->hasWideColorGamut();
1250 return NO_ERROR;
1251}
1252
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001253status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001254 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001255 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001256
Chia-I Wu90f669f2017-10-05 14:24:41 -07001257 if (mInjectVSyncs == enable) {
1258 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001259 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001260
Dominik Laskowski83b88212018-12-11 13:34:06 -08001261 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001262
Ana Krulec98b5b242018-08-10 15:03:23 -07001263 // TODO(akrulec): Part of the Injector should be refactored, so that it
1264 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001265 if (enable) {
1266 ALOGV("VSync Injections enabled");
1267 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001268 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001269 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001270 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001271 impl::EventThread::InterceptVSyncsCallback(),
1272 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001273 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001274 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001275 } else {
1276 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001277 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001278 }
1279
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001280 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001281 }));
1282
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001283 return NO_ERROR;
1284}
1285
1286status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001287 Mutex::Autolock _l(mStateLock);
1288
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001289 if (!mInjectVSyncs) {
1290 ALOGE("VSync Injections not enabled");
1291 return BAD_VALUE;
1292 }
1293 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1294 ALOGV("Injecting VSync inside SurfaceFlinger");
1295 mVSyncInjector->onInjectSyncEvent(when);
1296 }
1297 return NO_ERROR;
1298}
1299
Lloyd Pique755e3192018-01-31 16:46:15 -08001300status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1301 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001302 // Try to acquire a lock for 1s, fail gracefully
1303 const status_t err = mStateLock.timedLock(s2ns(1));
1304 const bool locked = (err == NO_ERROR);
1305 if (!locked) {
1306 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1307 return TIMED_OUT;
1308 }
1309
1310 outLayers->clear();
1311 mCurrentState.traverseInZOrder([&](Layer* layer) {
1312 outLayers->push_back(layer->getLayerDebugInfo());
1313 });
1314
1315 mStateLock.unlock();
1316 return NO_ERROR;
1317}
1318
Peiyong Linc6780972018-10-28 15:24:08 -07001319status_t SurfaceFlinger::getCompositionPreference(
1320 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1321 Dataspace* outWideColorGamutDataspace,
1322 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001323 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001324 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001325 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001326 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001327 return NO_ERROR;
1328}
1329
Dan Stoza84ab9372018-12-17 15:27:57 -08001330status_t SurfaceFlinger::addRegionSamplingListener(
1331 const Rect& /*samplingArea*/, const sp<IBinder>& /*stopLayerHandle*/,
1332 const sp<IRegionSamplingListener>& /*listener*/) {
1333 return NO_ERROR;
1334}
1335
1336status_t SurfaceFlinger::removeRegionSamplingListener(
1337 const sp<IRegionSamplingListener>& /*listener*/) {
1338 return NO_ERROR;
1339}
1340
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001341// ----------------------------------------------------------------------------
1342
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001343sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1344 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001345 auto resyncCallback = makeResyncCallback([this] {
1346 Mutex::Autolock lock(mStateLock);
1347 return getVsyncPeriod();
1348 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001349
Ana Krulec98b5b242018-08-10 15:03:23 -07001350 if (mUseScheduler) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001351 const auto& handle = vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle
1352 : mAppConnectionHandle;
1353
Ady Abrahama1a49af2019-02-07 14:36:55 -08001354 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001355 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001356 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001357 return mSFEventThread->createEventConnection(resyncCallback, ResetIdleTimerCallback());
Ana Krulec98b5b242018-08-10 15:03:23 -07001358 } else {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001359 return mEventThread->createEventConnection(resyncCallback, ResetIdleTimerCallback());
Ana Krulec98b5b242018-08-10 15:03:23 -07001360 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001361 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001362}
1363
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001364// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001365
1366void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001367 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001368}
1369
1370void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001371 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001372}
1373
1374void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001375 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001376}
1377
1378void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001379 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001380 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001381}
1382
1383status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001384 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001385 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001386}
1387
1388status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001389 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001390 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001391 if (res == NO_ERROR) {
1392 msg->wait();
1393 }
1394 return res;
1395}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001396
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001397void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001398 do {
1399 waitForEvent();
1400 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001401}
1402
Dominik Laskowski83b88212018-12-11 13:34:06 -08001403nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001404 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001405 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1406 return 0;
1407 }
1408
1409 const auto config = getHwComposer().getActiveConfig(*displayId);
1410 return config ? config->getVsyncPeriod() : 0;
1411}
1412
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001413void SurfaceFlinger::enableHardwareVsync() {
Ady Abrahamc3e21312019-02-07 14:30:23 -08001414 assert(!mUseScheduler);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001415 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001416 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001417 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001418 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001419 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001420 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001421}
1422
Dominik Laskowski83b88212018-12-11 13:34:06 -08001423void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001424 Mutex::Autolock _l(mHWVsyncLock);
Ady Abraham3aff9172019-02-07 19:10:26 -08001425 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1426 if (mUseScheduler) {
1427 if (makeAvailable) {
Ana Krulec7ab56032018-11-02 20:51:06 +01001428 mScheduler->makeHWSyncAvailable(true);
Ady Abraham3aff9172019-02-07 19:10:26 -08001429 } else if (!mScheduler->getHWSyncAvailable()) {
1430 // Hardware vsync is not currently available, so abort the resync
1431 // attempt for now
1432 return;
Ana Krulec7ab56032018-11-02 20:51:06 +01001433 }
Ady Abraham3aff9172019-02-07 19:10:26 -08001434 } else {
1435 if (makeAvailable) {
1436 mHWVsyncAvailable = true;
1437 } else if (!mHWVsyncAvailable) {
1438 // Hardware vsync is not currently available, so abort the resync
1439 // attempt for now
1440 return;
1441 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001442 }
1443
Dominik Laskowski83b88212018-12-11 13:34:06 -08001444 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001445 return;
1446 }
1447
Ana Krulece588e312018-09-18 12:32:24 -07001448 if (mUseScheduler) {
1449 mScheduler->setVsyncPeriod(period);
1450 } else {
1451 mPrimaryDispSync->reset();
1452 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001453
Ana Krulece588e312018-09-18 12:32:24 -07001454 if (!mPrimaryHWVsyncEnabled) {
1455 mPrimaryDispSync->beginResync();
1456 mEventControlThread->setVsyncEnabled(true);
1457 mPrimaryHWVsyncEnabled = true;
1458 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001459 }
1460}
1461
Jesse Hall948fe0c2013-10-14 12:56:09 -07001462void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Ady Abrahamc3e21312019-02-07 14:30:23 -08001463 assert(!mUseScheduler);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001464 Mutex::Autolock _l(mHWVsyncLock);
1465 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001466 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001467 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001468 mPrimaryHWVsyncEnabled = false;
1469 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001470 if (makeUnavailable) {
1471 mHWVsyncAvailable = false;
1472 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001473}
1474
Dominik Laskowski83b88212018-12-11 13:34:06 -08001475void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001476 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001477
Dan Stoza57164302017-05-08 14:03:54 -07001478 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001479 const nsecs_t last = lastResyncTime.exchange(now);
1480
1481 if (now - last > kIgnoreDelay) {
1482 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001483 }
1484}
1485
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001486void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1487 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001488 ATRACE_NAME("SF onVsync");
1489
Steven Thomas3cfac282017-02-06 12:29:30 -08001490 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001491 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001492 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001493 return;
1494 }
1495
Dominik Laskowski075d3172018-05-24 15:50:06 -07001496 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001497 return;
1498 }
1499
Dominik Laskowski075d3172018-05-24 15:50:06 -07001500 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001501 // For now, we don't do anything with external display vsyncs.
1502 return;
1503 }
1504
Ana Krulece588e312018-09-18 12:32:24 -07001505 if (mUseScheduler) {
1506 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001507 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001508 bool needsHwVsync = false;
1509 { // Scope for the lock
1510 Mutex::Autolock _l(mHWVsyncLock);
1511 if (mPrimaryHWVsyncEnabled) {
1512 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1513 }
1514 }
1515
1516 if (needsHwVsync) {
1517 enableHardwareVsync();
1518 } else {
1519 disableHardwareVsync(false);
1520 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001521 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001522}
1523
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001524void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001525 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1526 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001527}
1528
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001529void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate) {
1530 mPhaseOffsets->setRefreshRateType(refreshRate);
1531
1532 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1533 mVsyncModulator.setPhaseOffsets(early, gl, late);
1534
1535 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001536 return;
1537 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001538
Ana Krulec7d1d6832018-12-27 11:10:09 -08001539 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1540 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1541 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1542 // refresh cycle.
1543
1544 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001545 const nsecs_t currentVsyncPeriod = getVsyncPeriod();
Ana Krulec7d1d6832018-12-27 11:10:09 -08001546 if (currentVsyncPeriod == 0) {
1547 return;
1548 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001549
Ana Krulec7d1d6832018-12-27 11:10:09 -08001550 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1551 // floating numbers.
1552 const float currentFps = 1e9 / currentVsyncPeriod;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001553 const float newFps = refreshRate == RefreshRateType::PERFORMANCE ? kPerformanceRefreshRate
1554 : kDefaultRefreshRate;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001555 if (std::abs(currentFps - newFps) <= 1) {
1556 return;
1557 }
1558
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001559 const auto displayId = getInternalDisplayIdLocked();
1560 LOG_ALWAYS_FATAL_IF(!displayId);
1561
1562 auto configs = getHwComposer().getConfigs(*displayId);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001563 for (int i = 0; i < configs.size(); i++) {
1564 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1565 if (vsyncPeriod == 0) {
1566 continue;
1567 }
1568 const float fps = 1e9 / vsyncPeriod;
1569 // TODO(b/113612090): There should be a better way at determining which config
1570 // has the right refresh rate.
1571 if (std::abs(fps - newFps) <= 1) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001572 setDesiredActiveConfig(getInternalDisplayTokenLocked(), i);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001573 }
1574 }
1575}
1576
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001577void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001578 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001579 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001580 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001581
Lloyd Piqueba04e622017-12-14 17:11:26 -08001582 // Ignore events that do not have the right sequenceId.
1583 if (sequenceId != getBE().mComposerSequenceId) {
1584 return;
1585 }
1586
Steven Thomasb02664d2017-07-26 18:48:28 -07001587 // Only lock if we're not on the main thread. This function is normally
1588 // called on a hwbinder thread, but for the primary display it's called on
1589 // the main thread with the state lock already held, so don't attempt to
1590 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001591 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001592
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001593 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001594
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001595 if (std::this_thread::get_id() == mMainThreadId) {
1596 // Process all pending hot plug events immediately if we are on the main thread.
1597 processDisplayHotplugEventsLocked();
1598 }
1599
Lloyd Piqueba04e622017-12-14 17:11:26 -08001600 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001601}
1602
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001603void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001604 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001605 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001606 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001607 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001608 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001609}
1610
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001611void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001612 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001613 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001614 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001615 getHwComposer().setVsyncEnabled(*displayId,
1616 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1617 }
Mathias Agopian86303202012-07-24 22:46:10 -07001618}
1619
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001620// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001621void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001622 if (mUseScheduler) {
1623 mScheduler->disableHardwareVsync(true);
1624 } else {
1625 disableHardwareVsync(true);
1626 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001627 // Clear the drawing state so that the logic inside of
1628 // handleTransactionLocked will fire. It will determine the delta between
1629 // mCurrentState and mDrawingState and re-apply all changes when we make the
1630 // transition.
1631 mDrawingState.displays.clear();
1632 mDisplays.clear();
1633}
1634
Steven Thomas050b2c82017-03-06 11:45:16 -08001635void SurfaceFlinger::updateVrFlinger() {
1636 if (!mVrFlinger)
1637 return;
1638 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001639 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001640 return;
1641 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001642
Lloyd Pique441d5042018-10-18 16:49:51 -07001643 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001644 ALOGE("Vr flinger is only supported for remote hardware composer"
1645 " service connections. Ignoring request to transition to vr"
1646 " flinger.");
1647 mVrFlingerRequestsDisplay = false;
1648 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001649 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001650
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001651 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001652
Steven Thomas0123ac62018-07-12 11:32:34 -07001653 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001654 LOG_ALWAYS_FATAL_IF(!display);
1655 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001656 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1657 // called below. Clear the reference now so we don't accidentally use it
1658 // later.
1659 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001660
Steven Thomasb02664d2017-07-26 18:48:28 -07001661 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001662 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001663 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001664
Steven Thomasb02664d2017-07-26 18:48:28 -07001665 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001666 // Delete the current instance before creating the new one
1667 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1668 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1669 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1670 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001671
Lloyd Pique441d5042018-10-18 16:49:51 -07001672 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001673 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001674
1675 if (vrFlingerRequestsDisplay) {
1676 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001677 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001678
1679 mVisibleRegionsDirty = true;
1680 invalidateHwcGeometry();
1681
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001682 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001683 display = getDefaultDisplayDeviceLocked();
1684 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001685 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001686
Steven Thomasb02664d2017-07-26 18:48:28 -07001687 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001688 const nsecs_t vsyncPeriod = getVsyncPeriod();
1689 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001690
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001691 // The present fences returned from vr_hwc are not an accurate
1692 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001693 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001694 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1695 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001696 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001697 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001698 !hasSyncFramework);
1699 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001700
Steven Thomasb02664d2017-07-26 18:48:28 -07001701 // Use phase of 0 since phase is not known.
1702 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001703 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001704 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001705
Dominik Laskowski83b88212018-12-11 13:34:06 -08001706 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001707
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001708 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001709 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001710}
1711
Mathias Agopian4fec8732012-06-29 14:12:52 -07001712void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001713 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001714 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001715 case MessageQueue::INVALIDATE: {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001716 if (!updateSetActiveConfigStateMachine()) {
1717 break;
1718 }
1719
Ana Krulec3084c052018-11-21 20:27:17 +01001720 if (mUseScheduler) {
1721 // This call is made each time SF wakes up and creates a new frame.
1722 mScheduler->incrementFrameCounter();
1723 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001724 bool frameMissed = !mHadClientComposition && mPreviousPresentFence != Fence::NO_FENCE &&
1725 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001726 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001727 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001728 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001729 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001730 if (mPropagateBackpressure) {
1731 signalLayerUpdate();
1732 break;
1733 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001734 }
Dan Stoza50182882016-07-08 12:02:20 -07001735
Steven Thomas050b2c82017-03-06 11:45:16 -08001736 // Now that we're going to make it to the handleMessageTransaction()
1737 // call below it's safe to call updateVrFlinger(), which will
1738 // potentially trigger a display handoff.
1739 updateVrFlinger();
1740
Dan Stoza6b9454d2014-11-07 16:00:59 -08001741 bool refreshNeeded = handleMessageTransaction();
1742 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001743
1744 updateCursorAsync();
1745 updateInputFlinger();
1746
Dan Stoza58784442014-12-02 16:58:17 -08001747 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001748 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001749 // Signal a refresh if a transaction modified the window state,
1750 // a new buffer was latched, or if HWC has requested a full
1751 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001752 signalRefresh();
1753 }
1754 break;
1755 }
1756 case MessageQueue::REFRESH: {
1757 handleMessageRefresh();
1758 break;
1759 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001760 }
1761}
1762
Dan Stoza6b9454d2014-11-07 16:00:59 -08001763bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001764 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001765
1766 // Apply any ready transactions in the queues if there are still transactions that have not been
1767 // applied, wake up during the next vsync period and check again
1768 bool transactionNeeded = false;
1769 if (!flushTransactionQueues()) {
1770 transactionNeeded = true;
1771 }
1772
Mathias Agopian4fec8732012-06-29 14:12:52 -07001773 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001774 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001775 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001776
1777 if (transactionNeeded) {
1778 setTransactionFlags(eTransactionNeeded);
1779 }
1780
1781 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001782}
1783
Mathias Agopian4fec8732012-06-29 14:12:52 -07001784void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001785 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001786
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001787 mRefreshPending = false;
1788
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001789 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001790 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001791 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001792 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001793 for (const auto& [token, display] : mDisplays) {
1794 beginFrame(display);
1795 prepareFrame(display);
1796 doDebugFlashRegions(display, repaintEverything);
1797 doComposition(display, repaintEverything);
1798 }
1799
Adrian Roos1e1a1282017-11-01 19:05:31 +01001800 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001801 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001802
1803 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001804 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001805
Dan Stozabfbffeb2016-07-21 14:49:33 -07001806 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001807 for (const auto& [token, displayDevice] : mDisplays) {
1808 auto display = displayDevice->getCompositionDisplay();
1809 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001810 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001811 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001812 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001813
Alec Mouri86770e52018-09-24 22:40:58 +00001814 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001815 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001816 if (mHadClientComposition) {
1817 base::unique_fd flushFence(getRenderEngine().flush());
1818 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1819 getBE().flushFence = new Fence(std::move(flushFence));
1820 } else {
1821 // Cleanup for hygiene.
1822 getBE().flushFence = Fence::NO_FENCE;
1823 }
1824 }
1825
Jorim Jaggi90535212018-05-23 23:44:06 +02001826 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001827
David Sodman7e4ae112018-02-09 15:02:28 -08001828 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001829 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001830 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001831 compositionInfo.hwc.hwcLayer = nullptr;
1832 }
David Sodmanba340492018-08-05 21:51:33 -07001833 }
David Sodman7e4ae112018-02-09 15:02:28 -08001834
1835 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001836}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001837
David Sodmanfa9b2af2017-12-24 13:28:59 -08001838
1839bool SurfaceFlinger::handleMessageInvalidate() {
1840 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001841 bool refreshNeeded = handlePageFlip();
1842
Vishnu Nair4351ad52019-02-11 14:13:02 -08001843 if (mVisibleRegionsDirty) {
1844 computeLayerBounds();
1845 }
1846
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001847 for (auto& layer : mLayersPendingRefresh) {
1848 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001849 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001850 invalidateLayerStack(layer, visibleReg);
1851 }
1852 mLayersPendingRefresh.clear();
1853 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001854}
1855
David Sodman79bba0e2018-08-05 18:07:49 -07001856void SurfaceFlinger::calculateWorkingSet() {
1857 ATRACE_CALL();
1858 ALOGV(__FUNCTION__);
1859
David Sodman79bba0e2018-08-05 18:07:49 -07001860 // build the h/w work list
1861 if (CC_UNLIKELY(mGeometryInvalid)) {
1862 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001863 for (const auto& [token, displayDevice] : mDisplays) {
1864 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001865 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001866 if (!displayId) {
1867 continue;
1868 }
David Sodman79bba0e2018-08-05 18:07:49 -07001869
Lloyd Pique32cbe282018-10-19 13:09:22 -07001870 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001871 for (size_t i = 0; i < currentLayers.size(); i++) {
1872 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001873
Dominik Laskowski075d3172018-05-24 15:50:06 -07001874 if (!layer->hasHwcLayer(*displayId)) {
1875 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1876 layer->forceClientComposition(*displayId);
1877 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001878 }
1879 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001880
Lloyd Pique32cbe282018-10-19 13:09:22 -07001881 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001882 if (mDebugDisableHWC || mDebugRegion) {
1883 layer->forceClientComposition(*displayId);
1884 }
David Sodman79bba0e2018-08-05 18:07:49 -07001885 }
1886 }
1887 }
1888
1889 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001890 for (const auto& [token, displayDevice] : mDisplays) {
1891 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001892 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001893 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001894 continue;
1895 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001896 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001897
1898 if (mDrawingState.colorMatrixChanged) {
1899 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001900 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001901 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001902 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001903 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001904 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1905 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001906 !profile->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001907 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001908 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1909 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001910 !profile->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001911 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001912 }
1913
Peiyong Lind3788632018-09-18 16:01:31 -07001914 // TODO(b/111562338) remove when composer 2.3 is shipped.
1915 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001916 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001917 }
1918
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001919 if (layer->getRoundedCornerState().radius > 0.0f) {
1920 layer->forceClientComposition(*displayId);
1921 }
1922
Dominik Laskowski075d3172018-05-24 15:50:06 -07001923 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001924 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001925 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001926 continue;
1927 }
1928
Lloyd Pique32cbe282018-10-19 13:09:22 -07001929 const auto& displayState = display->getState();
1930 layer->setPerFrameData(*displayId, displayState.transform, displayState.viewport,
1931 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001932 }
1933
Peiyong Lin13effd12018-07-24 17:01:47 -07001934 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001935 ColorMode colorMode;
1936 Dataspace dataSpace;
1937 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001938 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001939 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001940 }
1941 }
1942
1943 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001944
1945 for (const auto& [token, display] : mDisplays) {
1946 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001947 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001948 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001949
1950 if (displayId) {
1951 if (!layer->setHwcLayer(*displayId)) {
1952 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1953 }
1954 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001955 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001956
Dominik Laskowski05275f12018-11-01 15:03:24 -07001957 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001958 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1959 }
1960 }
David Sodman79bba0e2018-08-05 18:07:49 -07001961}
1962
Lloyd Pique32cbe282018-10-19 13:09:22 -07001963void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1964 bool repaintEverything) {
1965 auto display = displayDevice->getCompositionDisplay();
1966 const auto& displayState = display->getState();
1967
Mathias Agopiancd60f992012-08-16 16:28:27 -07001968 // is debugging enabled
1969 if (CC_LIKELY(!mDebugRegion))
1970 return;
1971
Lloyd Pique32cbe282018-10-19 13:09:22 -07001972 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001973 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001974 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001975 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001976 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001977 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001978 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001979
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001980 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001981 }
1982 }
1983
Lloyd Pique32cbe282018-10-19 13:09:22 -07001984 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001985
1986 if (mDebugRegion > 1) {
1987 usleep(mDebugRegion * 1000);
1988 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001989
Lloyd Pique32cbe282018-10-19 13:09:22 -07001990 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001991}
1992
Adrian Roos1e1a1282017-11-01 19:05:31 +01001993void SurfaceFlinger::doTracing(const char* where) {
1994 ATRACE_CALL();
1995 ATRACE_NAME(where);
1996 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001997 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001998 }
1999}
2000
Yiwei Zhang7124ad32018-02-21 13:02:45 -08002001void SurfaceFlinger::logLayerStats() {
2002 ATRACE_CALL();
2003 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002004 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002005 if (display->isPrimary()) {
2006 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07002007 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08002008 }
2009 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07002010
2011 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08002012 }
2013}
2014
David Sodman2b406362017-12-15 13:33:47 -08002015void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002016{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002017 ATRACE_CALL();
2018 ALOGV("preComposition");
2019
David Sodman2b406362017-12-15 13:33:47 -08002020 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
2021
Mathias Agopiancd60f992012-08-16 16:28:27 -07002022 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08002023 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08002024 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002025 needExtraInvalidate = true;
2026 }
Robert Carr2047fae2016-11-28 14:09:09 -08002027 });
2028
Mathias Agopiancd60f992012-08-16 16:28:27 -07002029 if (needExtraInvalidate) {
2030 signalLayerUpdate();
2031 }
2032}
2033
Ana Krulece588e312018-09-18 12:32:24 -07002034void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2035 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002036 // Update queue of past composite+present times and determine the
2037 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002038 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002039 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002040 while (!getBE().mCompositePresentTimes.empty()) {
2041 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002042 // Cached values should have been updated before calling this method,
2043 // which helps avoid duplicate syscalls.
2044 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2045 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2046 break;
2047 }
2048 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002049 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002050 }
2051
2052 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002053 while (getBE().mCompositePresentTimes.size() > 16) {
2054 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002055 }
2056
Ana Krulece588e312018-09-18 12:32:24 -07002057 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002058}
2059
Ana Krulece588e312018-09-18 12:32:24 -07002060void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2061 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002062 // Integer division and modulo round toward 0 not -inf, so we need to
2063 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08002064 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
2065 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
2066 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002067
Ana Krulec757f63a2019-01-25 10:46:18 -08002068 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002069 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002070 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002071 }
2072
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002073 // Snap the latency to a value that removes scheduling jitter from the
2074 // composition and present times, which often have >1ms of jitter.
2075 // Reducing jitter is important if an app attempts to extrapolate
2076 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08002077 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002078 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002079 nsecs_t bias = stats.vsyncPeriod / 2;
2080 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2081 nsecs_t snappedCompositeToPresentLatency =
2082 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002083
David Sodman99974d22017-11-28 12:04:33 -08002084 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002085 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2086 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002087 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002088}
2089
Ady Abraham8164d482019-01-11 14:47:59 -08002090// debug patch for b/119477596 - add stack guards to catch stack
2091// corruptions and disable clang optimizations.
2092// The code below is temporary and planned to be removed once stack
2093// corruptions are found.
2094#pragma clang optimize off
2095class StackGuard {
2096public:
2097 StackGuard(const char* name, const char* func, int line) {
2098 guarders.reserve(MIN_CAPACITY);
2099 guarders.push_back({this, name, func, line});
2100 validate();
2101 }
2102 ~StackGuard() {
2103 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
2104 if (i->guard == this) {
2105 guarders.erase(i);
2106 break;
2107 }
2108 }
2109 }
2110
2111 static void validate() {
2112 for (const auto& guard : guarders) {
2113 if (guard.guard->cookie != COOKIE_VALUE) {
2114 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
2115 CallStack stack(LOG_TAG);
2116 abort();
2117 }
2118 }
2119 }
2120
2121private:
2122 uint64_t cookie = COOKIE_VALUE;
2123 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
2124 static constexpr size_t MIN_CAPACITY = 16;
2125
2126 struct GuarderElement {
2127 StackGuard* guard;
2128 const char* name;
2129 const char* func;
2130 int line;
2131 };
2132
2133 static std::vector<GuarderElement> guarders;
2134};
2135std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2136
2137#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2138
2139#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002140void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002141{
Ady Abraham8164d482019-01-11 14:47:59 -08002142 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002143 ATRACE_CALL();
2144 ALOGV("postComposition");
2145
Brian Anderson3546a3f2016-07-14 11:51:14 -07002146 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002147 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002148 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002149 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002150 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002151 }
Ady Abraham8164d482019-01-11 14:47:59 -08002152 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002153
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002154 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002155 const auto displayDevice = getDefaultDisplayDeviceLocked();
2156 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002157
David Sodman73beded2017-11-15 11:56:06 -08002158 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002159 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002160 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2161
Lloyd Pique32cbe282018-10-19 13:09:22 -07002162 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002163 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002164 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2165 ->getRenderSurface()
2166 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002167 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002168 } else {
2169 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2170 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002171
Ady Abraham8164d482019-01-11 14:47:59 -08002172 ASSERT_ON_STACK_GUARD();
2173
David Sodman73beded2017-11-15 11:56:06 -08002174 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002175 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2176 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002177 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002178 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002179 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002180
Ana Krulece588e312018-09-18 12:32:24 -07002181 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002182 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002183 if (mUseScheduler) {
2184 mScheduler->getDisplayStatInfo(&stats);
2185 } else {
2186 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2187 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2188 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002189
Ady Abraham8164d482019-01-11 14:47:59 -08002190 ASSERT_ON_STACK_GUARD();
2191
David Sodman2b406362017-12-15 13:33:47 -08002192 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002193 // when we started doing work for this frame, but that should be okay
2194 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002195 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002196 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002197 DEFINE_STACK_GUARD(compositorTiming);
2198
Brian Andersond0010582017-03-07 13:20:31 -08002199 {
David Sodman99974d22017-11-28 12:04:33 -08002200 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002201 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002202 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002203
2204 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002205 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002206
Robert Carr2047fae2016-11-28 14:09:09 -08002207 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002208 bool frameLatched =
2209 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2210 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002211 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002212 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002213 recordBufferingStats(layer->getName().string(),
2214 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002215 }
Ady Abraham8164d482019-01-11 14:47:59 -08002216 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002217 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002218
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002219 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002220 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002221 if (mUseScheduler) {
2222 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002223 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002224 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002225 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2226 enableHardwareVsync();
2227 } else {
2228 disableHardwareVsync(false);
2229 }
Ady Abraham8164d482019-01-11 14:47:59 -08002230 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002231 }
2232 }
2233
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002234 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002235 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2236 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002237 if (mUseScheduler) {
2238 mScheduler->enableHardwareVsync();
2239 } else {
2240 enableHardwareVsync();
2241 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002242 }
2243 }
2244
Ady Abraham8164d482019-01-11 14:47:59 -08002245 ASSERT_ON_STACK_GUARD();
2246
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002247 if (mAnimCompositionPending) {
2248 mAnimCompositionPending = false;
2249
Brian Anderson4e606e32017-03-16 15:34:57 -07002250 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002251 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002252 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002253
2254 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002255 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002256 // The HWC doesn't support present fences, so use the refresh
2257 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002258 const nsecs_t presentTime =
2259 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002260 DEFINE_STACK_GUARD(presentTime);
2261
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002262 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002263 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002264 }
2265 mAnimFrameTracker.advanceFrame();
2266 }
Dan Stozab90cf072015-03-05 11:05:59 -08002267
Ady Abraham8164d482019-01-11 14:47:59 -08002268 ASSERT_ON_STACK_GUARD();
2269
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002270 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002271 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002272 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002273 }
2274
Ady Abraham8164d482019-01-11 14:47:59 -08002275 ASSERT_ON_STACK_GUARD();
2276
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002277 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002278
Ady Abraham8164d482019-01-11 14:47:59 -08002279 ASSERT_ON_STACK_GUARD();
2280
Lloyd Pique32cbe282018-10-19 13:09:22 -07002281 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2282 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002283 return;
2284 }
2285
2286 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002287 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002288 if (mHasPoweredOff) {
2289 mHasPoweredOff = false;
2290 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002291 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002292 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002293 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002294 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002295 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2296 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002297 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002298 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002299 }
David Sodman4a36e932017-11-07 14:29:47 -08002300 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002301
2302 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002303 }
David Sodman4a36e932017-11-07 14:29:47 -08002304 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002305 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002306
2307 {
2308 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002309 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002310 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002311 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002312 if (refillCount > 0) {
2313 const size_t offset = mTexturePool.size();
2314 mTexturePool.resize(mTexturePoolSize);
2315 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2316 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2317 }
Ady Abraham8164d482019-01-11 14:47:59 -08002318 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002319 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002320
Marissa Wallfda30bb2018-10-12 11:34:28 -07002321 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002322 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002323
2324 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002325}
Ady Abraham8164d482019-01-11 14:47:59 -08002326#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002327
Vishnu Nair4351ad52019-02-11 14:13:02 -08002328void SurfaceFlinger::computeLayerBounds() {
2329 for (const auto& pair : mDisplays) {
2330 const auto& displayDevice = pair.second;
2331 const auto display = displayDevice->getCompositionDisplay();
2332 for (const auto& layer : mDrawingState.layersSortedByZ) {
2333 // only consider the layers on the given layer stack
2334 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002335 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002336 }
2337
2338 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2339 }
2340 }
2341}
2342
Mathias Agopiancd60f992012-08-16 16:28:27 -07002343void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002344 ATRACE_CALL();
2345 ALOGV("rebuildLayerStacks");
2346
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002347 // We need to clear these out now as these may be holding on to a
2348 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2349 // also holds a reference. When the set of visible layers is recomputed,
2350 // some layers may be destroyed if the only thing keeping them alive was
2351 // that list of visible layers associated with each display. The layer
2352 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2353 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2354 for (const auto& [token, display] : mDisplays) {
2355 getBE().mCompositionInfo[token].clear();
2356 }
2357
Mathias Agopiancd60f992012-08-16 16:28:27 -07002358 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002359 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002360 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002361 mVisibleRegionsDirty = false;
2362 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002363
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002364 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002365 const auto& displayDevice = pair.second;
2366 auto display = displayDevice->getCompositionDisplay();
2367 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002368 Region opaqueRegion;
2369 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002370 compositionengine::Output::OutputLayers layersSortedByZ;
2371 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002372 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002373 const ui::Transform& tr = displayState.transform;
2374 const Rect bounds = displayState.bounds;
2375 if (displayState.isEnabled) {
2376 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002377
Jeff Sharkey76488112017-02-27 14:15:18 -07002378 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002379 auto compositionLayer = layer->getCompositionLayer();
2380 if (compositionLayer == nullptr) {
2381 return;
2382 }
2383
Chia-I Wu83806892017-11-16 10:50:20 -08002384 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002385 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002386 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2387 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2388
Lloyd Piqueef36b002019-01-23 17:52:04 -08002389 if (display->belongsInOutput(layer->getLayerStack(),
2390 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002391 Region drawRegion(tr.transform(
2392 layer->visibleNonTransparentRegion));
2393 drawRegion.andSelf(bounds);
2394 if (!drawRegion.isEmpty()) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002395 layersSortedByZ.emplace_back(
2396 display->getOrCreateOutputLayer(layer->getCompositionLayer(),
2397 layerFE));
2398
2399 deprecated_layersSortedByZ.add(layer);
Jeff Sharkey76488112017-02-27 14:15:18 -07002400 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002401 // Clear out the HWC layer if this layer was
2402 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002403 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002404 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002405 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002406 // WM changes display->layerStack upon sleep/awake.
2407 // Here we make sure we delete the HWC layers even if
2408 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002409 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002410 }
2411
2412 // If a layer is not going to get a release fence because
2413 // it is invisible, but it is also going to release its
2414 // old buffer, add it to the list of layers needing
2415 // fences.
2416 if (hwcLayerDestroyed) {
2417 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2418 mLayersWithQueuedFrames.cend(), layer);
2419 if (found != mLayersWithQueuedFrames.cend()) {
2420 layersNeedingFences.add(layer);
2421 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002422 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002423 });
2424 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002425
2426 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2427
2428 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002429 displayDevice->setLayersNeedingFences(layersNeedingFences);
2430
2431 Region undefinedRegion{bounds};
2432 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2433
2434 display->editState().undefinedRegion = undefinedRegion;
2435 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002436 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002437 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002438}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002439
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002440// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002441// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002442// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002443// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002444// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002445// The returned HDR data space is one of
2446// - Dataspace::UNKNOWN
2447// - Dataspace::BT2020_HLG
2448// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002449Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2450 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002451 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002452 *outHdrDataSpace = Dataspace::UNKNOWN;
2453
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002454 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002455 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002456 case Dataspace::V0_SCRGB:
2457 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002458 case Dataspace::BT2020:
2459 case Dataspace::BT2020_ITU:
2460 case Dataspace::BT2020_LINEAR:
2461 case Dataspace::DISPLAY_BT2020:
2462 bestDataSpace = Dataspace::DISPLAY_BT2020;
2463 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002464 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002465 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002466 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002467 case Dataspace::BT2020_PQ:
2468 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002469 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002470 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002471 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002472 case Dataspace::BT2020_HLG:
2473 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002474 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002475 // When there's mixed PQ content and HLG content, we set the HDR
2476 // data space to be BT2020_PQ and convert HLG to PQ.
2477 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2478 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002479 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002480 break;
2481 default:
2482 break;
2483 }
Romain Guy54f154a2017-10-24 21:40:32 +01002484 }
2485
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002486 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002487}
2488
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002489// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002490void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2491 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002492 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2493 *outMode = ColorMode::NATIVE;
2494 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002495 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002496 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002497 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002498
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002499 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002500 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002501
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002502 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2503
Peiyong Lina3ea5592019-02-10 14:45:00 -08002504 switch (mForceColorMode) {
2505 case ColorMode::SRGB:
2506 bestDataSpace = Dataspace::V0_SRGB;
2507 break;
2508 case ColorMode::DISPLAY_P3:
2509 bestDataSpace = Dataspace::DISPLAY_P3;
2510 break;
2511 default:
2512 break;
2513 }
2514
Peiyong Lindfde5112018-06-05 10:58:41 -07002515 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002516 const bool isHdr =
2517 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002518 if (isHdr) {
2519 bestDataSpace = hdrDataSpace;
2520 }
2521
Chia-I Wu0d711262018-05-21 15:19:35 -07002522 RenderIntent intent;
2523 switch (mDisplayColorSetting) {
2524 case DisplayColorSetting::MANAGED:
2525 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002526 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002527 break;
2528 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002529 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002530 break;
2531 default: // vendor display color setting
2532 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2533 break;
2534 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002535
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002536 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002537}
2538
Lloyd Pique32cbe282018-10-19 13:09:22 -07002539void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2540 auto display = displayDevice->getCompositionDisplay();
2541 const auto& displayState = display->getState();
2542
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002543 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002544 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2545 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002546
David Sodmanfa9b2af2017-12-24 13:28:59 -08002547 // If nothing has changed (!dirty), don't recompose.
2548 // If something changed, but we don't currently have any visible layers,
2549 // and didn't when we last did a composition, then skip it this time.
2550 // The second rule does two things:
2551 // - When all layers are removed from a display, we'll emit one black
2552 // frame, then nothing more until we get new layers.
2553 // - When a display is created with a private layer stack, we won't
2554 // emit any black frames until a layer is added to the layer stack.
2555 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002556
Dominik Laskowski075d3172018-05-24 15:50:06 -07002557 const char flagPrefix[] = {'-', '+'};
2558 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002559 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2560 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2561 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2562 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002563
Lloyd Pique31cb2942018-10-19 17:23:03 -07002564 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002565
David Sodmanfa9b2af2017-12-24 13:28:59 -08002566 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002567 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002568 }
2569}
2570
Lloyd Pique32cbe282018-10-19 13:09:22 -07002571void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2572 auto display = displayDevice->getCompositionDisplay();
2573 const auto& displayState = display->getState();
2574
2575 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002576 return;
David Sodman2b406362017-12-15 13:33:47 -08002577 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002578
Lloyd Pique31cb2942018-10-19 17:23:03 -07002579 status_t result = display->getRenderSurface()->prepareFrame(
2580 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002581 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002582 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002583}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002584
Lloyd Pique32cbe282018-10-19 13:09:22 -07002585void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002586 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002587 ALOGV("doComposition");
2588
Lloyd Pique32cbe282018-10-19 13:09:22 -07002589 auto display = displayDevice->getCompositionDisplay();
2590 const auto& displayState = display->getState();
2591
2592 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002593 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002594 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002595
David Sodmanfa9b2af2017-12-24 13:28:59 -08002596 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002597 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002598
Lloyd Pique32cbe282018-10-19 13:09:22 -07002599 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002600 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002601 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002602 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002603}
2604
David Sodmanfa9b2af2017-12-24 13:28:59 -08002605void SurfaceFlinger::postFrame()
2606{
2607 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002608 const auto display = getDefaultDisplayDeviceLocked();
2609 if (display && getHwComposer().isConnected(*display->getId())) {
2610 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002611 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2612 logFrameStats();
2613 }
2614 }
2615}
2616
Lloyd Pique32cbe282018-10-19 13:09:22 -07002617void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002618 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002619 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002620
Lloyd Pique32cbe282018-10-19 13:09:22 -07002621 auto display = displayDevice->getCompositionDisplay();
2622 const auto& displayState = display->getState();
2623 const auto displayId = display->getId();
2624
David Sodmanfa9b2af2017-12-24 13:28:59 -08002625 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002626
Lloyd Pique32cbe282018-10-19 13:09:22 -07002627 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002628 if (displayId) {
2629 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002630 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002631 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002632 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002633 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002634
Chia-I Wu7b549592017-11-15 09:14:57 -08002635 // The layer buffer from the previous frame (if any) is released
2636 // by HWC only when the release fence from this frame (if any) is
2637 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002638 if (displayId && layer->hasHwcLayer(*displayId)) {
2639 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2640 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002641 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002642
2643 // If the layer was client composited in the previous frame, we
2644 // need to merge with the previous client target acquire fence.
2645 // Since we do not track that, always merge with the current
2646 // client target acquire fence when it is available, even though
2647 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002648 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002649 releaseFence =
2650 Fence::merge("LayerRelease", releaseFence,
2651 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002652 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002653
David Sodman15094112018-10-11 09:39:37 -07002654 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002655 }
Chia-I Wu83806892017-11-16 10:50:20 -08002656
2657 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002658 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002659 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002660 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002661 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002662 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002663 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002664 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002665 }
2666 }
2667
Dominik Laskowski075d3172018-05-24 15:50:06 -07002668 if (displayId) {
2669 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002670 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002671 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002672}
2673
Mathias Agopian87baae12012-07-31 12:38:26 -07002674void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002675{
Mathias Agopian841cde52012-03-01 15:44:37 -08002676 ATRACE_CALL();
2677
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002678 // here we keep a copy of the drawing state (that is the state that's
2679 // going to be overwritten by handleTransactionLocked()) outside of
2680 // mStateLock so that the side-effects of the State assignment
2681 // don't happen with mStateLock held (which can cause deadlocks).
2682 State drawingState(mDrawingState);
2683
Mathias Agopianca4d3602011-05-19 15:38:14 -07002684 Mutex::Autolock _l(mStateLock);
2685 const nsecs_t now = systemTime();
2686 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002687
Mathias Agopianca4d3602011-05-19 15:38:14 -07002688 // Here we're guaranteed that some transaction flags are set
2689 // so we can call handleTransactionLocked() unconditionally.
2690 // We call getTransactionFlags(), which will also clear the flags,
2691 // with mStateLock held to guarantee that mCurrentState won't change
2692 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002693
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002694 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002695 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002696 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002697
Mathias Agopianca4d3602011-05-19 15:38:14 -07002698 mLastTransactionTime = systemTime() - now;
2699 mDebugInTransaction = 0;
2700 invalidateHwcGeometry();
2701 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002702}
2703
Lloyd Piqueba04e622017-12-14 17:11:26 -08002704void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2705 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002706 const std::optional<DisplayIdentificationInfo> info =
2707 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002708
Dominik Laskowski075d3172018-05-24 15:50:06 -07002709 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002710 continue;
2711 }
2712
Lloyd Piqueba04e622017-12-14 17:11:26 -08002713 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002714 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002715 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002716 mPhysicalDisplayTokens[info->id] = new BBinder();
2717 DisplayDeviceState state;
2718 state.displayId = info->id;
2719 state.isSecure = true; // All physical displays are currently considered secure.
2720 state.displayName = info->name;
2721 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2722 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002723 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002724 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002725 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002726
Dominik Laskowski075d3172018-05-24 15:50:06 -07002727 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2728 if (index >= 0) {
2729 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2730 mInterceptor->saveDisplayDeletion(state.sequenceId);
2731 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002732 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002733 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002734 }
2735
2736 processDisplayChangesLocked();
2737 }
2738
2739 mPendingHotplugEvents.clear();
2740}
2741
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002742void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002743 if (mUseScheduler) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002744 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2745 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002746 } else {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002747 mEventThread->onHotplugReceived(displayId, connected);
2748 mSFEventThread->onHotplugReceived(displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002749 }
2750}
2751
Lloyd Pique99d3da52018-01-22 17:48:03 -08002752sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002753 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002754 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002755 const sp<IGraphicBufferProducer>& producer) {
2756 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002757 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002758 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002759 creationArgs.isSecure = state.isSecure;
2760 creationArgs.displaySurface = dispSurface;
2761 creationArgs.hasWideColorGamut = false;
2762 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002763
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002764 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002765 creationArgs.isPrimary = isInternalDisplay;
2766
2767 if (useColorManagement && displayId) {
2768 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002769 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002770 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002771 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002772 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002773
Dominik Laskowski7e045462018-05-30 13:02:02 -07002774 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002775 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002776 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002777 }
tangrobin6753a022018-08-10 10:58:54 +08002778 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002779
Dominik Laskowski075d3172018-05-24 15:50:06 -07002780 if (displayId) {
2781 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002782 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002783 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002784 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002785
Lloyd Pique90c115d2018-09-18 21:39:42 -07002786 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002787 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002788 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002789
Lloyd Pique99d3da52018-01-22 17:48:03 -08002790 // Make sure that composition can never be stalled by a virtual display
2791 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002792 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002793 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002794 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2795 }
2796
Dominik Laskowski075d3172018-05-24 15:50:06 -07002797 creationArgs.displayInstallOrientation =
2798 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002799
Lloyd Pique99d3da52018-01-22 17:48:03 -08002800 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002801 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002802
Lloyd Pique90c115d2018-09-18 21:39:42 -07002803 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002804
2805 if (maxFrameBufferAcquiredBuffers >= 3) {
2806 nativeWindowSurface->preallocateBuffers();
2807 }
2808
2809 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002810 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002811 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002812 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002813 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002814 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002815 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2816 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002817 if (!state.isVirtual()) {
2818 LOG_ALWAYS_FATAL_IF(!displayId);
2819 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002820 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002821
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002822 display->setLayerStack(state.layerStack);
2823 display->setProjection(state.orientation, state.viewport, state.frame);
2824 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002825
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002826 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002827}
2828
Lloyd Pique347200f2017-12-14 17:00:15 -08002829void SurfaceFlinger::processDisplayChangesLocked() {
2830 // here we take advantage of Vector's copy-on-write semantics to
2831 // improve performance by skipping the transaction entirely when
2832 // know that the lists are identical
2833 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2834 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2835 if (!curr.isIdenticalTo(draw)) {
2836 mVisibleRegionsDirty = true;
2837 const size_t cc = curr.size();
2838 size_t dc = draw.size();
2839
2840 // find the displays that were removed
2841 // (ie: in drawing state but not in current state)
2842 // also handle displays that changed
2843 // (ie: displays that are in both lists)
2844 for (size_t i = 0; i < dc;) {
2845 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2846 if (j < 0) {
2847 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002848 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002849 // Save display ID before disconnecting.
2850 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002851 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002852
2853 if (!display->isVirtual()) {
2854 LOG_ALWAYS_FATAL_IF(!displayId);
2855 dispatchDisplayHotplugEvent(displayId->value, false);
2856 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002857 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002858
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002859 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002860 } else {
2861 // this display is in both lists. see if something changed.
2862 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002863 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002864 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2865 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2866 if (state_binder != draw_binder) {
2867 // changing the surface is like destroying and
2868 // recreating the DisplayDevice, so we just remove it
2869 // from the drawing state, so that it get re-added
2870 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002871 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002872 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002873 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002874 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002875 mDrawingState.displays.removeItemsAt(i);
2876 dc--;
2877 // at this point we must loop to the next item
2878 continue;
2879 }
2880
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002881 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002882 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002883 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002884 }
2885 if ((state.orientation != draw[i].orientation) ||
2886 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002887 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002888 }
2889 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002890 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002891 }
2892 }
2893 }
2894 ++i;
2895 }
2896
2897 // find displays that were added
2898 // (ie: in current state but not in drawing state)
2899 for (size_t i = 0; i < cc; i++) {
2900 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2901 const DisplayDeviceState& state(curr[i]);
2902
Lloyd Pique542307f2018-10-19 13:24:08 -07002903 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002904 sp<IGraphicBufferProducer> producer;
2905 sp<IGraphicBufferProducer> bqProducer;
2906 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002907 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002908
Dominik Laskowski075d3172018-05-24 15:50:06 -07002909 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002910 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002911 // Virtual displays without a surface are dormant:
2912 // they have external state (layer stack, projection,
2913 // etc.) but no internal state (i.e. a DisplayDevice).
2914 if (state.surface != nullptr) {
2915 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002916 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002917 int width = 0;
2918 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2919 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2920 int height = 0;
2921 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2922 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2923 int intFormat = 0;
2924 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2925 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002926 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002927
Dominik Laskowski075d3172018-05-24 15:50:06 -07002928 displayId =
2929 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002930 }
2931
2932 // TODO: Plumb requested format back up to consumer
2933
2934 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002935 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002936 bqProducer, bqConsumer,
2937 state.displayName);
2938
2939 dispSurface = vds;
2940 producer = vds;
2941 }
2942 } else {
2943 ALOGE_IF(state.surface != nullptr,
2944 "adding a supported display, but rendering "
2945 "surface is provided (%p), ignoring it",
2946 state.surface.get());
2947
Dominik Laskowski075d3172018-05-24 15:50:06 -07002948 displayId = state.displayId;
2949 LOG_ALWAYS_FATAL_IF(!displayId);
2950 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002951 producer = bqProducer;
2952 }
2953
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002954 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002955 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002956 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002957 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002958 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002959 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002960 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002961 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002962 }
2963 }
2964 }
2965 }
2966 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002967
2968 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002969}
2970
Mathias Agopian87baae12012-07-31 12:38:26 -07002971void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002972{
Dan Stoza7dde5992015-05-22 09:51:44 -07002973 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002974 mCurrentState.traverseInZOrder([](Layer* layer) {
2975 layer->notifyAvailableFrames();
2976 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002977
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002978 /*
2979 * Traversal of the children
2980 * (perform the transaction for each of them if needed)
2981 */
2982
Mathias Agopian3559b072012-08-15 13:46:03 -07002983 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002984 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002985 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002986 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002987
2988 const uint32_t flags = layer->doTransaction(0);
2989 if (flags & Layer::eVisibleRegion)
2990 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002991
2992 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002993 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002994 }
Robert Carr2047fae2016-11-28 14:09:09 -08002995 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002996 }
2997
2998 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002999 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003000 */
3001
Mathias Agopiane57f2922012-08-09 16:29:12 -07003002 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08003003 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08003004 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07003005 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003006
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003007 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08003008 // The transform hint might have changed for some layers
3009 // (either because a display has changed, or because a layer
3010 // as changed).
3011 //
3012 // Walk through all the layers in currentLayers,
3013 // and update their transform hint.
3014 //
3015 // If a layer is visible only on a single display, then that
3016 // display is used to calculate the hint, otherwise we use the
3017 // default display.
3018 //
3019 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
3020 // the hint is set before we acquire a buffer from the surface texture.
3021 //
3022 // NOTE: layer transactions have taken place already, so we use their
3023 // drawing state. However, SurfaceFlinger's own transaction has not
3024 // happened yet, so we must use the current state layer list
3025 // (soon to become the drawing state list).
3026 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003027 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08003028 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08003029 bool first = true;
3030 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08003031 // NOTE: we rely on the fact that layers are sorted by
3032 // layerStack first (so we don't have to traverse the list
3033 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07003034 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08003035 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08003036 currentlayerStack = layerStack;
3037 // figure out if this layerstack is mirrored
3038 // (more than one display) if so, pick the default display,
3039 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003040 hintDisplay = nullptr;
3041 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08003042 if (display->getCompositionDisplay()
3043 ->belongsInOutput(layer->getLayerStack(),
3044 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003045 if (hintDisplay) {
3046 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08003047 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003048 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003049 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08003050 }
3051 }
3052 }
3053 }
Chet Haase91d25932013-04-11 15:24:55 -07003054
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003055 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003056 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
3057 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08003058
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003059 // could be null when this layer is using a layerStack
3060 // that is not visible on any display. Also can occur at
3061 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003062 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08003063 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003064
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003065 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003066 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003067 if (hintDisplay) {
3068 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08003069 }
Robert Carr2047fae2016-11-28 14:09:09 -08003070
3071 first = false;
3072 });
Mathias Agopian84300952012-11-21 16:02:13 -08003073 }
3074
3075
Mathias Agopian3559b072012-08-15 13:46:03 -07003076 /*
3077 * Perform our own transaction if needed
3078 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07003079
3080 if (mLayersAdded) {
3081 mLayersAdded = false;
3082 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07003083 mVisibleRegionsDirty = true;
3084 }
3085
3086 // some layers might have been removed, so
3087 // we need to update the regions they're exposing.
3088 if (mLayersRemoved) {
3089 mLayersRemoved = false;
3090 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08003091 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003092 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07003093 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07003094 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08003095 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07003096 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07003097 }
Robert Carr2047fae2016-11-28 14:09:09 -08003098 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003099 }
3100
Vishnu Nairec0ab382019-02-13 15:32:56 -08003101 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003102 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07003103}
3104
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003105void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003106 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003107 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08003108 return;
3109 }
3110
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003111 if (mVisibleRegionsDirty || mInputInfoChanged) {
3112 mInputInfoChanged = false;
3113 updateInputWindowInfo();
3114 }
3115
3116 executeInputWindowCommands();
3117}
3118
3119void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07003120 Vector<InputWindowInfo> inputHandles;
3121
3122 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
3123 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08003124 // When calculating the screen bounds we ignore the transparent region since it may
3125 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08003126 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07003127 }
3128 });
3129 mInputFlinger->setInputWindows(inputHandles);
3130}
3131
Vishnu Nairec0ab382019-02-13 15:32:56 -08003132void SurfaceFlinger::commitInputWindowCommands() {
3133 mInputWindowCommands.merge(mPendingInputWindowCommands);
3134 mPendingInputWindowCommands.clear();
3135}
3136
chaviwfbe5d9c2018-12-26 12:23:37 -08003137void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08003138 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3139 if (transferTouchFocusCommand.fromToken != nullptr &&
3140 transferTouchFocusCommand.toToken != nullptr &&
3141 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3142 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3143 transferTouchFocusCommand.toToken);
3144 }
3145 }
3146
3147 mInputWindowCommands.clear();
3148}
3149
Riley Andrews03414a12014-07-01 14:22:59 -07003150void SurfaceFlinger::updateCursorAsync()
3151{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003152 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003153 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003154 continue;
3155 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003156
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003157 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3158 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003159 }
3160 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003161}
3162
chaviw61626f22018-11-15 16:26:27 -08003163void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3164 if (layer->hasReadyFrame()) {
Ady Abrahamc3e21312019-02-07 14:30:23 -08003165 nsecs_t expectedPresentTime;
3166 if (mUseScheduler) {
3167 expectedPresentTime = mScheduler->expectedPresentTime();
3168 } else {
3169 expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3170 }
chaviw61626f22018-11-15 16:26:27 -08003171 if (layer->shouldPresentNow(expectedPresentTime)) {
3172 bool ignored = false;
3173 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3174 }
3175 }
3176 layer->releasePendingBuffer(systemTime());
3177}
3178
Mathias Agopian4fec8732012-06-29 14:12:52 -07003179void SurfaceFlinger::commitTransaction()
3180{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003181 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003182 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003183 for (const auto& l : mLayersPendingRemoval) {
3184 recordBufferingStats(l->getName().string(),
3185 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003186
3187 // We need to release the HWC layers when the Layer is removed
3188 // from the current state otherwise the HWC layer just continues
3189 // showing at its last configured state until we eventually
3190 // abandon the buffer queue.
3191 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003192 l->destroyHwcLayersForAllDisplays();
3193 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003194 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003195 }
3196 mLayersPendingRemoval.clear();
3197 }
3198
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003199 // If this transaction is part of a window animation then the next frame
3200 // we composite should be considered an animation as well.
3201 mAnimCompositionPending = mAnimTransactionPending;
3202
Mathias Agopian4fec8732012-06-29 14:12:52 -07003203 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003204 // clear the "changed" flags in current state
3205 mCurrentState.colorMatrixChanged = false;
3206
Robert Carr1f0a16a2016-10-24 16:27:39 -07003207 mDrawingState.traverseInZOrder([](Layer* layer) {
3208 layer->commitChildList();
3209 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003210 mTransactionPending = false;
3211 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003212 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003213}
3214
Lloyd Pique32cbe282018-10-19 13:09:22 -07003215void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003216 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003217 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003218 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003219
Lloyd Pique32cbe282018-10-19 13:09:22 -07003220 auto display = displayDevice->getCompositionDisplay();
3221
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003222 Region aboveOpaqueLayers;
3223 Region aboveCoveredLayers;
3224 Region dirty;
3225
Mathias Agopian87baae12012-07-31 12:38:26 -07003226 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003227
Robert Carr2047fae2016-11-28 14:09:09 -08003228 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003229 // start with the whole surface at its current location
3230 const Layer::State& s(layer->getDrawingState());
3231
Jesse Hall01e29052013-02-19 16:13:35 -08003232 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003233 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003234 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003235 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003236
Mathias Agopianab028732010-03-16 16:41:46 -07003237 /*
3238 * opaqueRegion: area of a surface that is fully opaque.
3239 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003240 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003241
3242 /*
3243 * visibleRegion: area of a surface that is visible on screen
3244 * and not fully transparent. This is essentially the layer's
3245 * footprint minus the opaque regions above it.
3246 * Areas covered by a translucent surface are considered visible.
3247 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003248 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003249
3250 /*
3251 * coveredRegion: area of a surface that is covered by all
3252 * visible regions above it (which includes the translucent areas).
3253 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003254 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003255
Jesse Halla8026d22012-09-25 13:25:04 -07003256 /*
3257 * transparentRegion: area of a surface that is hinted to be completely
3258 * transparent. This is only used to tell when the layer has no visible
3259 * non-transparent regions and can be removed from the layer list. It
3260 * does not affect the visibleRegion of this layer or any layers
3261 * beneath it. The hint may not be correct if apps don't respect the
3262 * SurfaceView restrictions (which, sadly, some don't).
3263 */
3264 Region transparentRegion;
3265
Mathias Agopianab028732010-03-16 16:41:46 -07003266
3267 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003268 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003269 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003270 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003271
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003272 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003273 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003274 if (!visibleRegion.isEmpty()) {
3275 // Remove the transparent area from the visible region
3276 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003277 if (tr.preserveRects()) {
3278 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003279 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003280 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003281 // transformation too complex, can't do the
3282 // transparent region optimization.
3283 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003284 }
Mathias Agopianab028732010-03-16 16:41:46 -07003285 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003286
Mathias Agopianab028732010-03-16 16:41:46 -07003287 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003288 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003289 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003290 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003291 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003292 // the opaque region is the layer's footprint
3293 opaqueRegion = visibleRegion;
3294 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003295 }
3296 }
3297
Robert Carre5f4f692018-01-12 13:12:28 -08003298 if (visibleRegion.isEmpty()) {
3299 layer->clearVisibilityRegions();
3300 return;
3301 }
3302
Mathias Agopianab028732010-03-16 16:41:46 -07003303 // Clip the covered region to the visible region
3304 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3305
3306 // Update aboveCoveredLayers for next (lower) layer
3307 aboveCoveredLayers.orSelf(visibleRegion);
3308
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003309 // subtract the opaque region covered by the layers above us
3310 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003311
3312 // compute this layer's dirty region
3313 if (layer->contentDirty) {
3314 // we need to invalidate the whole region
3315 dirty = visibleRegion;
3316 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003317 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003318 layer->contentDirty = false;
3319 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003320 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003321 * the exposed region consists of two components:
3322 * 1) what's VISIBLE now and was COVERED before
3323 * 2) what's EXPOSED now less what was EXPOSED before
3324 *
3325 * note that (1) is conservative, we start with the whole
3326 * visible region but only keep what used to be covered by
3327 * something -- which mean it may have been exposed.
3328 *
3329 * (2) handles areas that were not covered by anything but got
3330 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003331 */
Mathias Agopianab028732010-03-16 16:41:46 -07003332 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003333 const Region oldVisibleRegion = layer->visibleRegion;
3334 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003335 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3336 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003337 }
3338 dirty.subtractSelf(aboveOpaqueLayers);
3339
3340 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003341 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003342
Mathias Agopianab028732010-03-16 16:41:46 -07003343 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003344 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003345
Jesse Halla8026d22012-09-25 13:25:04 -07003346 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003347 layer->setVisibleRegion(visibleRegion);
3348 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003349 layer->setVisibleNonTransparentRegion(
3350 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003351 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003352
Mathias Agopian87baae12012-07-31 12:38:26 -07003353 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003354}
3355
Chia-I Wuab0c3192017-08-01 11:29:00 -07003356void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003357 for (const auto& [token, displayDevice] : mDisplays) {
3358 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003359 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003360 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003361 }
3362 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003363}
3364
Daniel Solomon42d04562019-01-20 21:03:19 -08003365void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3366 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3367 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3368 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3369 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3370 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3371 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3372 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3373 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3374 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3375 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3376 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3377 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3378}
3379
Dan Stoza6b9454d2014-11-07 16:00:59 -08003380bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003381{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003382 ALOGV("handlePageFlip");
3383
Brian Andersond6927fb2016-07-23 23:37:30 -07003384 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003385
Mathias Agopian4fec8732012-06-29 14:12:52 -07003386 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003387 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003388 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003389
3390 // Store the set of layers that need updates. This set must not change as
3391 // buffers are being latched, as this could result in a deadlock.
3392 // Example: Two producers share the same command stream and:
3393 // 1.) Layer 0 is latched
3394 // 2.) Layer 0 gets a new frame
3395 // 2.) Layer 1 gets a new frame
3396 // 3.) Layer 1 is latched.
3397 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3398 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003399 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003400 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003401 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003402 nsecs_t expectedPresentTime;
3403 if (mUseScheduler) {
3404 expectedPresentTime = mScheduler->expectedPresentTime();
3405 } else {
3406 expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3407 }
Ana Krulec010d2192018-10-08 06:29:54 -07003408 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003409 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003410 } else {
3411 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003412 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003413 } else {
3414 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003415 }
Robert Carr2047fae2016-11-28 14:09:09 -08003416 });
3417
Lloyd Piquef2c79392018-12-20 16:23:33 -08003418 if (!mLayersWithQueuedFrames.empty()) {
3419 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3420 // writes to Layer current state. See also b/119481871
3421 Mutex::Autolock lock(mStateLock);
3422
3423 for (auto& layer : mLayersWithQueuedFrames) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003424 if (layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence)) {
3425 mLayersPendingRefresh.push_back(layer);
3426 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003427 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003428 if (layer->isBufferLatched()) {
3429 newDataLatched = true;
3430 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003431 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003432 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003433
Alec Mouri86770e52018-09-24 22:40:58 +00003434 // Clear the renderengine fence here...
3435 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3436 // clear instead of sp::clear.
3437 getBE().flushFence = Fence::NO_FENCE;
3438
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003439 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003440
3441 // If we will need to wake up at some time in the future to deal with a
3442 // queued frame that shouldn't be displayed during this vsync period, wake
3443 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003444 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003445 signalLayerUpdate();
3446 }
3447
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003448 // enter boot animation on first buffer latch
3449 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3450 ALOGI("Enter boot animation");
3451 mBootStage = BootStage::BOOTANIMATION;
3452 }
3453
Dan Stoza6b9454d2014-11-07 16:00:59 -08003454 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003455 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003456}
3457
Mathias Agopianad456f92011-01-13 17:53:01 -08003458void SurfaceFlinger::invalidateHwcGeometry()
3459{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003460 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003461}
3462
Lloyd Pique32cbe282018-10-19 13:09:22 -07003463void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003464 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003465 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003466 // We only need to actually compose the display if:
3467 // 1) It is being handled by hardware composer, which may need this to
3468 // keep its virtual display state machine in sync, or
3469 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003470 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003471 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003472 return;
3473 }
3474
Dan Stoza9e56aa02015-11-02 13:00:03 -08003475 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003476 base::unique_fd readyFence;
3477 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003478
3479 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003480 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003481}
3482
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003483bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3484 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003485 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003486 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003487
Lloyd Pique32cbe282018-10-19 13:09:22 -07003488 auto display = displayDevice->getCompositionDisplay();
3489 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003490 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003491
3492 const Region bounds(displayState.bounds);
3493 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003494 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003495 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003496
Peiyong Lind3788632018-09-18 16:01:31 -07003497 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003498 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003499
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003500 renderengine::DisplaySettings clientCompositionDisplay;
3501 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3502 sp<GraphicBuffer> buf;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003503
Dan Stoza9e56aa02015-11-02 13:00:03 -08003504 if (hasClientComposition) {
3505 ALOGV("hasClientComposition");
3506
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003507 buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003508
3509 if (buf == nullptr) {
3510 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3511 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003512 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003513 return false;
3514 }
3515
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003516 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3517 clientCompositionDisplay.clip = displayState.scissor;
3518 const ui::Transform& displayTransform = displayState.transform;
3519 mat4 m;
3520 m[0][0] = displayTransform[0][0];
3521 m[0][1] = displayTransform[0][1];
3522 m[0][3] = displayTransform[0][2];
3523 m[1][0] = displayTransform[1][0];
3524 m[1][1] = displayTransform[1][1];
3525 m[1][3] = displayTransform[1][2];
3526 m[3][0] = displayTransform[2][0];
3527 m[3][1] = displayTransform[2][1];
3528 m[3][3] = displayTransform[2][2];
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003529
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003530 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003531
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003532 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003533 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003534 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003535 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003536 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003537 clientCompositionDisplay.outputDataspace = outputDataspace;
3538 clientCompositionDisplay.maxLuminance =
3539 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003540
Lloyd Pique441d5042018-10-18 16:49:51 -07003541 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003542 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003543 getHwComposer()
3544 .hasDisplayCapability(displayId,
3545 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003546
Peiyong Lind3788632018-09-18 16:01:31 -07003547 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003548 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3549 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003550 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003551 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003552 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003553
Mathias Agopian85d751c2012-08-29 16:59:24 -07003554 /*
3555 * and then, render the layers targeted at the framebuffer
3556 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003557
Dan Stoza9e56aa02015-11-02 13:00:03 -08003558 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003559 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003560 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003561 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003562 const Region viewportRegion(displayState.viewport);
3563 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003564 ALOGV("Layer: %s", layer->getName().string());
3565 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003566 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003567 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003568 case HWC2::Composition::Cursor:
3569 case HWC2::Composition::Device:
3570 case HWC2::Composition::Sideband:
3571 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003572 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003573 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003574 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003575 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003576 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003577 // never clear the very first layer since we're
3578 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003579 renderengine::LayerSettings layerSettings;
3580 Region dummyRegion;
3581 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3582 layerSettings);
3583
3584 if (prepared) {
3585 layerSettings.source.buffer.buffer = nullptr;
3586 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3587 layerSettings.alpha = half(0.0);
3588 layerSettings.disableBlending = true;
3589 clientCompositionLayers.push_back(layerSettings);
3590 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003591 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003592 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003593 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003594 case HWC2::Composition::Client: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003595 renderengine::LayerSettings layerSettings;
3596 bool prepared =
3597 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3598 if (prepared) {
3599 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003600 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003601 break;
3602 }
3603 default:
3604 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003605 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003606 } else {
3607 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003608 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003609 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003610 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003611
Alec Mouri820c7402019-01-23 13:02:39 -08003612 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003613 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003614 clientCompositionDisplay.clearRegion = clearRegion;
3615 if (!debugRegion.isEmpty()) {
3616 Region::const_iterator it = debugRegion.begin();
3617 Region::const_iterator end = debugRegion.end();
3618 while (it != end) {
3619 const Rect& rect = *it++;
3620 renderengine::LayerSettings layerSettings;
3621 layerSettings.source.buffer.buffer = nullptr;
3622 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3623 layerSettings.geometry.boundaries = rect.toFloatRect();
3624 layerSettings.alpha = half(1.0);
3625 clientCompositionLayers.push_back(layerSettings);
3626 }
3627 }
3628 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
3629 buf->getNativeBuffer(), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003630 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003631 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003632}
3633
Chia-I Wu28e3a252018-09-07 12:05:02 -07003634void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003635 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003636 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003637}
3638
Dan Stoza7d89d062015-04-30 13:29:25 -07003639status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003640 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003641 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003642 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003643 const sp<Layer>& parent,
3644 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003645{
Dan Stoza7d89d062015-04-30 13:29:25 -07003646 // add this layer to the current state list
3647 {
3648 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003649 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003650 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3651 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003652 return NO_MEMORY;
3653 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003654 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003655 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003656 } else if (parent == nullptr) {
3657 lbc->onRemovedFromCurrentState();
3658 } else if (parent->isRemovedFromCurrentState()) {
3659 parent->addChild(lbc);
3660 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003661 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003662 parent->addChild(lbc);
3663 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003664
Yiwei Zhang243b3782018-05-15 17:40:04 -07003665 if (gbc != nullptr) {
3666 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3667 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3668 mMaxGraphicBufferProducerListSize,
3669 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3670 mGraphicBufferProducerList.size(),
3671 mMaxGraphicBufferProducerListSize, mNumLayers);
3672 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003673 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003674 }
3675
Mathias Agopian96f08192010-06-02 23:28:45 -07003676 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003677 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003678
Dan Stoza7d89d062015-04-30 13:29:25 -07003679 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003680}
3681
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003682uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003683 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003684}
3685
Mathias Agopian3f844832013-08-07 21:24:32 -07003686uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003687 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003688}
3689
Mathias Agopian3f844832013-08-07 21:24:32 -07003690uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003691 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003692}
3693
3694uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003695 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003696 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003697 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003698 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003699 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003700 }
3701 return old;
3702}
3703
Marissa Wall713b63f2018-10-17 15:42:43 -07003704bool SurfaceFlinger::flushTransactionQueues() {
3705 Mutex::Autolock _l(mStateLock);
3706 auto it = mTransactionQueues.begin();
3707 while (it != mTransactionQueues.end()) {
3708 auto& [applyToken, transactionQueue] = *it;
3709
3710 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003711 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3712 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003713 break;
3714 }
Vishnu Nairec0ab382019-02-13 15:32:56 -08003715 applyTransactionState(states, displays, flags, mPendingInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003716 transactionQueue.pop();
3717 }
3718
3719 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3720 }
3721 return mTransactionQueues.empty();
3722}
3723
chaviwca27f252018-02-06 16:46:39 -08003724bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3725 for (const ComposerState& state : states) {
3726 // Here we need to check that the interface we're given is indeed
3727 // one of our own. A malicious client could give us a nullptr
3728 // IInterface, or one of its own or even one of our own but a
3729 // different type. All these situations would cause us to crash.
3730 if (state.client == nullptr) {
3731 return true;
3732 }
3733
3734 sp<IBinder> binder = IInterface::asBinder(state.client);
3735 if (binder == nullptr) {
3736 return true;
3737 }
3738
3739 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3740 return true;
3741 }
3742 }
3743 return false;
3744}
3745
Marissa Wall17b4e452018-12-26 16:32:34 -08003746bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3747 const Vector<ComposerState>& states) {
Ady Abrahamc3e21312019-02-07 14:30:23 -08003748 nsecs_t expectedPresentTime;
3749 if (mUseScheduler) {
3750 expectedPresentTime = mScheduler->expectedPresentTime();
3751 } else {
3752 expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3753 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003754 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3755 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3756 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3757 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3758 return false;
3759 }
3760
Marissa Wall713b63f2018-10-17 15:42:43 -07003761 for (const ComposerState& state : states) {
3762 const layer_state_t& s = state.state;
3763 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3764 continue;
3765 }
3766 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003767 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003768 }
3769 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003770 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003771}
3772
3773void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3774 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003775 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003776 const InputWindowCommands& inputWindowCommands,
3777 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003778 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003779 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003780
chaviwca27f252018-02-06 16:46:39 -08003781 if (containsAnyInvalidClientState(states)) {
3782 return;
3783 }
3784
Marissa Wall713b63f2018-10-17 15:42:43 -07003785 // If its TransactionQueue already has a pending TransactionState or if it is pending
3786 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003787 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3788 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003789 setTransactionFlags(eTransactionNeeded);
3790 return;
3791 }
3792
chaviw273171b2018-12-26 11:46:30 -08003793 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003794}
3795
3796void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003797 const Vector<DisplayState>& displays, uint32_t flags,
3798 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003799 uint32_t transactionFlags = 0;
3800
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003801 if (flags & eAnimation) {
3802 // For window updates that are part of an animation we must wait for
3803 // previous animation "frames" to be handled.
3804 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003805 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003806 if (CC_UNLIKELY(err != NO_ERROR)) {
3807 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003808 // caller after a few seconds.
3809 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3810 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003811 mAnimTransactionPending = false;
3812 break;
3813 }
3814 }
3815 }
3816
chaviwca27f252018-02-06 16:46:39 -08003817 for (const DisplayState& display : displays) {
3818 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003819 }
3820
Marissa Walle2ffb422018-10-12 11:33:52 -07003821 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003822 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003823 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003824 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003825 // If the state doesn't require a traversal and there are callbacks, send them now
3826 if (!(clientStateFlags & eTraversalNeeded)) {
3827 mTransactionCompletedThread.sendCallbacks();
3828 }
3829 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003830
chaviw273171b2018-12-26 11:46:30 -08003831 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3832
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003833 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3834 // anyway. This can be used as a flush mechanism for previous async transactions.
3835 // Empty animation transaction can be used to simulate back-pressure, so also force a
3836 // transaction for empty animation transactions.
3837 if (transactionFlags == 0 &&
3838 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003839 transactionFlags = eTransactionNeeded;
3840 }
3841
Mathias Agopian386aa982011-11-07 21:58:03 -08003842 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003843 if (mInterceptor->isEnabled()) {
3844 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003845 }
Irvel468051e2016-06-13 16:44:44 -07003846
Mathias Agopian386aa982011-11-07 21:58:03 -08003847 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003848 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3849 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003850 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003851
3852 // if this is a synchronous transaction, wait for it to take effect
3853 // before returning.
3854 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003855 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003856 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003857 if (flags & eAnimation) {
3858 mAnimTransactionPending = true;
3859 }
3860 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003861 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3862 if (CC_UNLIKELY(err != NO_ERROR)) {
3863 // just in case something goes wrong in SF, return to the
3864 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003865 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3866 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003867 break;
3868 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003869 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003870 }
3871}
3872
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003873uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3874 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3875 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003876
Mathias Agopiane57f2922012-08-09 16:29:12 -07003877 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003878 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3879
3880 const uint32_t what = s.what;
3881 if (what & DisplayState::eSurfaceChanged) {
3882 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3883 state.surface = s.surface;
3884 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003885 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003886 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003887 if (what & DisplayState::eLayerStackChanged) {
3888 if (state.layerStack != s.layerStack) {
3889 state.layerStack = s.layerStack;
3890 flags |= eDisplayTransactionNeeded;
3891 }
3892 }
3893 if (what & DisplayState::eDisplayProjectionChanged) {
3894 if (state.orientation != s.orientation) {
3895 state.orientation = s.orientation;
3896 flags |= eDisplayTransactionNeeded;
3897 }
3898 if (state.frame != s.frame) {
3899 state.frame = s.frame;
3900 flags |= eDisplayTransactionNeeded;
3901 }
3902 if (state.viewport != s.viewport) {
3903 state.viewport = s.viewport;
3904 flags |= eDisplayTransactionNeeded;
3905 }
3906 }
3907 if (what & DisplayState::eDisplaySizeChanged) {
3908 if (state.width != s.width) {
3909 state.width = s.width;
3910 flags |= eDisplayTransactionNeeded;
3911 }
3912 if (state.height != s.height) {
3913 state.height = s.height;
3914 flags |= eDisplayTransactionNeeded;
3915 }
3916 }
3917
Mathias Agopiane57f2922012-08-09 16:29:12 -07003918 return flags;
3919}
3920
Robert Carrd4ae7f32018-06-07 16:10:57 -07003921bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3922 IPCThreadState* ipc = IPCThreadState::self();
3923 const int pid = ipc->getCallingPid();
3924 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003925 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003926 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003927 return false;
3928 }
3929 return true;
3930}
3931
chaviwca27f252018-02-06 16:46:39 -08003932uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3933 const layer_state_t& s = composerState.state;
3934 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3935
Mathias Agopian13127d82013-03-05 17:47:11 -08003936 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003937 if (layer == nullptr) {
3938 return 0;
3939 }
3940
chaviw8b3871a2017-11-01 17:41:01 -07003941 uint32_t flags = 0;
3942
Garfield Tan8a3083e2018-12-03 13:21:07 -08003943 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003944 bool geometryAppliesWithResize =
3945 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003946
3947 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3948 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003949 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003950 layer->pushPendingState();
3951 }
3952
chaviw8b3871a2017-11-01 17:41:01 -07003953 if (what & layer_state_t::ePositionChanged) {
3954 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3955 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003956 }
chaviw8b3871a2017-11-01 17:41:01 -07003957 }
3958 if (what & layer_state_t::eLayerChanged) {
3959 // NOTE: index needs to be calculated before we update the state
3960 const auto& p = layer->getParent();
3961 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003962 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003963 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003964 mCurrentState.layersSortedByZ.removeAt(idx);
3965 mCurrentState.layersSortedByZ.add(layer);
3966 // we need traversal (state changed)
3967 // AND transaction (list changed)
3968 flags |= eTransactionNeeded|eTraversalNeeded;
3969 }
chaviw8b3871a2017-11-01 17:41:01 -07003970 } else {
3971 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003972 flags |= eTransactionNeeded|eTraversalNeeded;
3973 }
3974 }
chaviw8b3871a2017-11-01 17:41:01 -07003975 }
3976 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003977 // NOTE: index needs to be calculated before we update the state
3978 const auto& p = layer->getParent();
3979 if (p == nullptr) {
3980 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3981 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3982 mCurrentState.layersSortedByZ.removeAt(idx);
3983 mCurrentState.layersSortedByZ.add(layer);
3984 // we need traversal (state changed)
3985 // AND transaction (list changed)
3986 flags |= eTransactionNeeded|eTraversalNeeded;
3987 }
3988 } else {
3989 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3990 flags |= eTransactionNeeded|eTraversalNeeded;
3991 }
chaviw8b3871a2017-11-01 17:41:01 -07003992 }
3993 }
3994 if (what & layer_state_t::eSizeChanged) {
3995 if (layer->setSize(s.w, s.h)) {
3996 flags |= eTraversalNeeded;
3997 }
3998 }
3999 if (what & layer_state_t::eAlphaChanged) {
4000 if (layer->setAlpha(s.alpha))
4001 flags |= eTraversalNeeded;
4002 }
4003 if (what & layer_state_t::eColorChanged) {
4004 if (layer->setColor(s.color))
4005 flags |= eTraversalNeeded;
4006 }
Peiyong Lind3788632018-09-18 16:01:31 -07004007 if (what & layer_state_t::eColorTransformChanged) {
4008 if (layer->setColorTransform(s.colorTransform)) {
4009 flags |= eTraversalNeeded;
4010 }
4011 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004012 if (what & layer_state_t::eBackgroundColorChanged) {
4013 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
4014 flags |= eTraversalNeeded;
4015 }
4016 }
chaviw8b3871a2017-11-01 17:41:01 -07004017 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004018 // TODO: b/109894387
4019 //
4020 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
4021 // rotation. To see the problem observe that if we have a square parent, and a child
4022 // of the same size, then we rotate the child 45 degrees around it's center, the child
4023 // must now be cropped to a non rectangular 8 sided region.
4024 //
4025 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
4026 // private API, and the WindowManager only uses rotation in one case, which is on a top
4027 // level layer in which cropping is not an issue.
4028 //
4029 // However given that abuse of rotation matrices could lead to surfaces extending outside
4030 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
4031 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
4032 // transformations.
4033 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07004034 flags |= eTraversalNeeded;
4035 }
4036 if (what & layer_state_t::eTransparentRegionChanged) {
4037 if (layer->setTransparentRegionHint(s.transparentRegion))
4038 flags |= eTraversalNeeded;
4039 }
4040 if (what & layer_state_t::eFlagsChanged) {
4041 if (layer->setFlags(s.flags, s.mask))
4042 flags |= eTraversalNeeded;
4043 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004044 if (what & layer_state_t::eCropChanged_legacy) {
4045 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07004046 flags |= eTraversalNeeded;
4047 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004048 if (what & layer_state_t::eCornerRadiusChanged) {
4049 if (layer->setCornerRadius(s.cornerRadius))
4050 flags |= eTraversalNeeded;
4051 }
chaviw8b3871a2017-11-01 17:41:01 -07004052 if (what & layer_state_t::eLayerStackChanged) {
4053 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4054 // We only allow setting layer stacks for top level layers,
4055 // everything else inherits layer stack from its parent.
4056 if (layer->hasParent()) {
4057 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
4058 layer->getName().string());
4059 } else if (idx < 0) {
4060 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
4061 "that also does not appear in the top level layer list. Something"
4062 " has gone wrong.", layer->getName().string());
4063 } else if (layer->setLayerStack(s.layerStack)) {
4064 mCurrentState.layersSortedByZ.removeAt(idx);
4065 mCurrentState.layersSortedByZ.add(layer);
4066 // we need traversal (state changed)
4067 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07004068 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07004069 }
4070 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004071 if (what & layer_state_t::eDeferTransaction_legacy) {
4072 if (s.barrierHandle_legacy != nullptr) {
4073 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
4074 } else if (s.barrierGbp_legacy != nullptr) {
4075 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07004076 if (authenticateSurfaceTextureLocked(gbp)) {
4077 const auto& otherLayer =
4078 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07004079 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07004080 } else {
4081 ALOGE("Attempt to defer transaction to to an"
4082 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08004083 }
4084 }
chaviw8b3871a2017-11-01 17:41:01 -07004085 // We don't trigger a traversal here because if no other state is
4086 // changed, we don't want this to cause any more work
4087 }
4088 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08004089 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07004090 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08004091 if (!hadParent) {
4092 mCurrentState.layersSortedByZ.remove(layer);
4093 }
chaviw8b3871a2017-11-01 17:41:01 -07004094 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08004095 }
chaviw8b3871a2017-11-01 17:41:01 -07004096 }
4097 if (what & layer_state_t::eReparentChildren) {
4098 if (layer->reparentChildren(s.reparentHandle)) {
4099 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07004100 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004101 }
chaviw8b3871a2017-11-01 17:41:01 -07004102 if (what & layer_state_t::eDetachChildren) {
4103 layer->detachChildren();
4104 }
4105 if (what & layer_state_t::eOverrideScalingModeChanged) {
4106 layer->setOverrideScalingMode(s.overrideScalingMode);
4107 // We don't trigger a traversal here because if no other state is
4108 // changed, we don't want this to cause any more work
4109 }
Marissa Wall61c58622018-07-18 10:12:20 -07004110 if (what & layer_state_t::eTransformChanged) {
4111 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4112 }
4113 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4114 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4115 flags |= eTraversalNeeded;
4116 }
4117 if (what & layer_state_t::eCropChanged) {
4118 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4119 }
Marissa Wall861616d2018-10-22 12:52:23 -07004120 if (what & layer_state_t::eFrameChanged) {
4121 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4122 }
Marissa Wall61c58622018-07-18 10:12:20 -07004123 if (what & layer_state_t::eAcquireFenceChanged) {
4124 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4125 }
4126 if (what & layer_state_t::eDataspaceChanged) {
4127 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4128 }
4129 if (what & layer_state_t::eHdrMetadataChanged) {
4130 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4131 }
4132 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4133 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4134 }
4135 if (what & layer_state_t::eApiChanged) {
4136 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4137 }
4138 if (what & layer_state_t::eSidebandStreamChanged) {
4139 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4140 }
Robert Carr720e5062018-07-30 17:45:14 -07004141 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004142 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
4143 layer->setInputInfo(s.inputInfo);
4144 flags |= eTraversalNeeded;
4145 } else {
4146 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4147 }
Robert Carr720e5062018-07-30 17:45:14 -07004148 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004149 if (what & layer_state_t::eMetadataChanged) {
4150 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4151 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004152 std::vector<sp<CallbackHandle>> callbackHandles;
4153 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
4154 mTransactionCompletedThread.run();
4155 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
4156 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4157 }
4158 }
Marissa Wall73411622019-01-25 10:45:41 -08004159
4160 if (what & layer_state_t::eBufferChanged) {
4161 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
4162 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
4163 s.buffer);
4164 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004165 if (what & layer_state_t::eCachedBufferChanged) {
4166 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08004167 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
4168 s.cachedBuffer.bufferId);
Marissa Wallebc2c052019-01-16 19:16:55 -08004169 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4170 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004171 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4172 // Do not put anything that updates layer state or modifies flags after
4173 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004174 return flags;
4175}
4176
chaviw273171b2018-12-26 11:46:30 -08004177uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4178 uint32_t flags = 0;
4179 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4180 flags |= eTraversalNeeded;
4181 }
4182
chaviwa911b102019-02-14 10:18:33 -08004183 if (inputWindowCommands.syncInputWindows) {
4184 flags |= eTraversalNeeded;
4185 }
4186
Vishnu Nairec0ab382019-02-13 15:32:56 -08004187 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004188 return flags;
4189}
4190
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004191status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4192 uint32_t h, PixelFormat format, uint32_t flags,
4193 LayerMetadata metadata, sp<IBinder>* handle,
4194 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004195 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004196 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004197 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004198 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004199 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004200
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004201 status_t result = NO_ERROR;
4202
4203 sp<Layer> layer;
4204
Cody Northropbc755282017-03-31 12:00:08 -06004205 String8 uniqueName = getUniqueLayerName(name);
4206
Mathias Agopian3165cc22012-08-08 19:42:09 -07004207 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004208 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004209 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4210 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004211
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004212 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004213 case ISurfaceComposerClient::eFXSurfaceBufferState:
4214 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4215 break;
chaviw13fdc492017-06-27 12:40:18 -07004216 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004217 // check if buffer size is set for color layer.
4218 if (w > 0 || h > 0) {
4219 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4220 int(w), int(h));
4221 return BAD_VALUE;
4222 }
4223
chaviw13fdc492017-06-27 12:40:18 -07004224 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004225 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004226 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004227 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004228 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004229 // check if buffer size is set for container layer.
4230 if (w > 0 || h > 0) {
4231 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4232 int(w), int(h));
4233 return BAD_VALUE;
4234 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004235 result = createContainerLayer(client,
4236 uniqueName, w, h, flags,
4237 handle, &layer);
4238 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004239 default:
4240 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004241 break;
4242 }
4243
Dan Stoza7d89d062015-04-30 13:29:25 -07004244 if (result != NO_ERROR) {
4245 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004246 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004247
Chia-I Wuab0c3192017-08-01 11:29:00 -07004248 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4249 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004250 if (metadata.has(METADATA_WINDOW_TYPE)) {
4251 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4252 if (windowType == 441731) {
4253 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4254 layer->setPrimaryDisplayOnly();
4255 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004256 }
4257
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004258 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004259
Robert Carrb89ea9d2018-12-10 13:01:14 -08004260 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4261 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4262 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004263 if (result != NO_ERROR) {
4264 return result;
4265 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004266 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004267
4268 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004269 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004270}
4271
Cody Northropbc755282017-03-31 12:00:08 -06004272String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4273{
4274 bool matchFound = true;
4275 uint32_t dupeCounter = 0;
4276
4277 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4278 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4279
Dan Stoza436ccf32018-06-21 12:10:12 -07004280 // Grab the state lock since we're accessing mCurrentState
4281 Mutex::Autolock lock(mStateLock);
4282
Cody Northropbc755282017-03-31 12:00:08 -06004283 // Loop over layers until we're sure there is no matching name
4284 while (matchFound) {
4285 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004286 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004287 if (layer->getName() == uniqueName) {
4288 matchFound = true;
4289 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4290 }
4291 });
4292 }
4293
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004294 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4295 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004296
4297 return uniqueName;
4298}
4299
Marissa Wallfd668622018-05-10 10:21:13 -07004300status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4301 uint32_t w, uint32_t h, uint32_t flags,
4302 PixelFormat& format, sp<IBinder>* handle,
4303 sp<IGraphicBufferProducer>* gbp,
4304 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004305 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004306 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004307 case PIXEL_FORMAT_TRANSPARENT:
4308 case PIXEL_FORMAT_TRANSLUCENT:
4309 format = PIXEL_FORMAT_RGBA_8888;
4310 break;
4311 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004312 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004313 break;
4314 }
4315
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004316 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004317 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004318 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004319 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004320 *handle = layer->getHandle();
4321 *gbp = layer->getProducer();
4322 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004323 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004324
Marissa Wallfd668622018-05-10 10:21:13 -07004325 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004326 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004327}
4328
Marissa Wall61c58622018-07-18 10:12:20 -07004329status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4330 uint32_t w, uint32_t h, uint32_t flags,
4331 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004332 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004333 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004334 *handle = layer->getHandle();
4335 *outLayer = layer;
4336
4337 return NO_ERROR;
4338}
4339
chaviw13fdc492017-06-27 12:40:18 -07004340status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004341 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004342 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004343{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004344 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004345 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004346 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004347}
4348
Robert Carr6b3f6c52018-08-13 13:05:17 -07004349status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4350 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4351 sp<IBinder>* handle, sp<Layer>* outLayer)
4352{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004353 *outLayer =
4354 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004355 *handle = (*outLayer)->getHandle();
4356 return NO_ERROR;
4357}
4358
4359
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004360void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004361 mLayersPendingRemoval.add(layer);
4362 mLayersRemoved = true;
4363 setTransactionFlags(eTransactionNeeded);
4364}
4365
Robert Carr695d5282018-12-18 15:27:58 -08004366void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004367{
Robert Carr2e102c92018-10-23 12:11:15 -07004368 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004369 // If a layer has a parent, we allow it to out-live it's handle
4370 // with the idea that the parent holds a reference and will eventually
4371 // be cleaned up. However no one cleans up the top-level so we do so
4372 // here.
4373 if (layer->getParent() == nullptr) {
4374 mCurrentState.layersSortedByZ.remove(layer);
4375 }
4376 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004377 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004378}
4379
Mathias Agopianb60314a2012-04-10 22:09:54 -07004380// ---------------------------------------------------------------------------
4381
Andy McFadden13a082e2012-08-24 10:16:42 -07004382void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004383 const auto display = getDefaultDisplayDeviceLocked();
4384 if (!display) return;
4385
4386 const sp<IBinder> token = display->getDisplayToken().promote();
4387 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004388
Jesse Hall01e29052013-02-19 16:13:35 -08004389 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004390 Vector<ComposerState> state;
4391 Vector<DisplayState> displays;
4392 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004393 d.what = DisplayState::eDisplayProjectionChanged |
4394 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004395 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004396 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004397 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004398 d.frame.makeInvalid();
4399 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004400 d.width = 0;
4401 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004402 displays.add(d);
Vishnu Nairec0ab382019-02-13 15:32:56 -08004403 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004404
Dominik Laskowskie9774092018-12-11 10:04:24 -08004405 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004406
Dominik Laskowski83b88212018-12-11 13:34:06 -08004407 const nsecs_t vsyncPeriod = getVsyncPeriod();
4408 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004409
Brian Andersond0010582017-03-07 13:20:31 -08004410 // Use phase of 0 since phase is not known.
4411 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004412 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004413 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004414}
4415
4416void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004417 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004418 postMessageAsync(
4419 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004420}
4421
Dominik Laskowskie9774092018-12-11 10:04:24 -08004422void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004423 if (display->isVirtual()) {
4424 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004425 return;
4426 }
4427
Dominik Laskowski075d3172018-05-24 15:50:06 -07004428 const auto displayId = display->getId();
4429 LOG_ALWAYS_FATAL_IF(!displayId);
4430
Dominik Laskowski34157762018-10-31 13:07:19 -07004431 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004432
4433 int currentMode = display->getPowerMode();
4434 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004435 return;
4436 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004437
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004438 display->setPowerMode(mode);
4439
Lloyd Pique4dccc412018-01-22 17:21:36 -08004440 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004441 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004442 }
4443
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004444 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004445 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004446 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004447 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004448 if (mUseScheduler) {
4449 mScheduler->onScreenAcquired(mAppConnectionHandle);
4450 } else {
4451 mEventThread->onScreenAcquired();
4452 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004453 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004454 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004455
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004456 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004457 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004458 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004459
4460 struct sched_param param = {0};
4461 param.sched_priority = 1;
4462 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4463 ALOGW("Couldn't set SCHED_FIFO on display on");
4464 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004465 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004466 // Turn off the display
4467 struct sched_param param = {0};
4468 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4469 ALOGW("Couldn't set SCHED_OTHER on display off");
4470 }
4471
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004472 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004473 if (mUseScheduler) {
4474 mScheduler->disableHardwareVsync(true);
4475 } else {
4476 disableHardwareVsync(true); // also cancels any in-progress resync
4477 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004478 if (mUseScheduler) {
4479 mScheduler->onScreenReleased(mAppConnectionHandle);
4480 } else {
4481 mEventThread->onScreenReleased();
4482 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004483 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004484
Dominik Laskowski075d3172018-05-24 15:50:06 -07004485 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004486 mVisibleRegionsDirty = true;
4487 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004488 } else if (mode == HWC_POWER_MODE_DOZE ||
4489 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004490 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004491 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004492 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004493 if (mUseScheduler) {
4494 mScheduler->onScreenAcquired(mAppConnectionHandle);
4495 } else {
4496 mEventThread->onScreenAcquired();
4497 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004498 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004499 }
4500 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4501 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004502 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004503 if (mUseScheduler) {
4504 mScheduler->disableHardwareVsync(true);
4505 } else {
4506 disableHardwareVsync(true); // also cancels any in-progress resync
4507 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004508 if (mUseScheduler) {
4509 mScheduler->onScreenReleased(mAppConnectionHandle);
4510 } else {
4511 mEventThread->onScreenReleased();
4512 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004513 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004514 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004515 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004516 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004517 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004518 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004519
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004520 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004521 mTimeStats->setPowerMode(mode);
Ana Krulec4593b692019-01-11 22:07:25 -08004522 if (mUseScheduler && mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004523 // Update refresh rate stats.
4524 mRefreshRateStats->setPowerMode(mode);
4525 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004526 }
4527
Dominik Laskowski34157762018-10-31 13:07:19 -07004528 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004529}
4530
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004531void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004532 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004533 const auto display = getDisplayDevice(displayToken);
4534 if (!display) {
4535 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4536 displayToken.get());
4537 } else if (display->isVirtual()) {
4538 ALOGW("Attempt to set power mode %d for virtual display", mode);
4539 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004540 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004541 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004542 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004543}
4544
4545// ---------------------------------------------------------------------------
4546
Dominik Laskowskic2867142019-01-21 11:33:38 -08004547status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4548 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004549 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004550
Mathias Agopianbd115332013-04-18 16:41:04 -07004551 IPCThreadState* ipc = IPCThreadState::self();
4552 const int pid = ipc->getCallingPid();
4553 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004554
Mathias Agopianbd115332013-04-18 16:41:04 -07004555 if ((uid != AID_SHELL) &&
4556 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004557 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4558 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004559 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004560 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004561 // (this would indicate SF is stuck, but we want to be able to
4562 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004563 status_t err = mStateLock.timedLock(s2ns(1));
4564 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004565 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004566 StringAppendF(&result,
4567 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4568 "(no locks held)\n",
4569 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004570 }
4571
Dominik Laskowskic2867142019-01-21 11:33:38 -08004572 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004573
Dominik Laskowskic2867142019-01-21 11:33:38 -08004574 static const std::unordered_map<std::string, Dumper> dumpers = {
4575 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4576 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4577 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004578 {"--dispsync"s, dumper([this](std::string& s) {
4579 if (mUseScheduler) {
4580 mScheduler->dumpPrimaryDispSync(s);
4581 } else {
4582 mPrimaryDispSync->dump(s);
4583 }
4584 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004585 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4586 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
4587 {"--frame-composition"s, dumper(&SurfaceFlinger::dumpFrameCompositionInfo)},
4588 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4589 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4590 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4591 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4592 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4593 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004594 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004595 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4596 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004597
Dominik Laskowskic2867142019-01-21 11:33:38 -08004598 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004599
Dominik Laskowskic2867142019-01-21 11:33:38 -08004600 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4601 (it->second)(args, asProto, result);
4602 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004603 if (asProto) {
4604 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4605 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4606 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004607 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004608 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004609 }
4610
Mathias Agopian9795c422009-08-26 16:36:26 -07004611 if (locked) {
4612 mStateLock.unlock();
4613 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004614 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004615 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004616 return NO_ERROR;
4617}
4618
Dominik Laskowskic2867142019-01-21 11:33:38 -08004619void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004620 mCurrentState.traverseInZOrder(
4621 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004622}
4623
Dominik Laskowskic2867142019-01-21 11:33:38 -08004624void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004625 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004626
Dominik Laskowskic2867142019-01-21 11:33:38 -08004627 if (args.size() > 1) {
4628 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004629 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004630 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004631 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004632 }
Robert Carr2047fae2016-11-28 14:09:09 -08004633 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004634 } else {
4635 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004636 }
4637}
4638
Dominik Laskowskic2867142019-01-21 11:33:38 -08004639void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004640 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004641 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004642 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004643 }
Robert Carr2047fae2016-11-28 14:09:09 -08004644 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004645
Svetoslavd85084b2014-03-20 10:28:31 -07004646 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004647}
4648
Dominik Laskowskic2867142019-01-21 11:33:38 -08004649void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4650 mTimeStats->parseArgs(asProto, args, result);
4651}
4652
Jamie Gennis6547ff42013-07-16 20:12:42 -07004653// This should only be called from the main thread. Otherwise it would need
4654// the lock and should use mCurrentState rather than mDrawingState.
4655void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004656 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004657 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004658 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004659
4660 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4661}
4662
Yiwei Zhang5434a782018-12-05 18:06:32 -08004663void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004664 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004665
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004666 if (isLayerTripleBufferingDisabled())
4667 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004668
Yiwei Zhang5434a782018-12-05 18:06:32 -08004669 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4670 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4671 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4672 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4673 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4674 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004675 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004676}
4677
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004678void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004679 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004680 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004681 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004682 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004683
4684 StringAppendF(&result, "Scheduler: %s\n\n", mUseScheduler ? "enabled" : "disabled");
4685
4686 if (mUseScheduler) {
4687 mScheduler->dump(mAppConnectionHandle, result);
4688 } else {
4689 mEventThread->dump(result);
4690 }
4691}
4692
Yiwei Zhang5434a782018-12-05 18:06:32 -08004693void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4694 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004695 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4696 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004697 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004698 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004699 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004700 }
David Sodman4a36e932017-11-07 14:29:47 -08004701 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004702 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004703 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004704 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4705 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004706}
4707
Dan Stozae77c7662016-05-13 11:37:28 -07004708void SurfaceFlinger::recordBufferingStats(const char* layerName,
4709 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004710 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4711 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004712 for (const auto& segment : history) {
4713 if (!segment.usedThirdBuffer) {
4714 stats.twoBufferTime += segment.totalTime;
4715 }
4716 if (segment.occupancyAverage < 1.0f) {
4717 stats.doubleBufferedTime += segment.totalTime;
4718 } else if (segment.occupancyAverage < 2.0f) {
4719 stats.tripleBufferedTime += segment.totalTime;
4720 }
4721 ++stats.numSegments;
4722 stats.totalTime += segment.totalTime;
4723 }
4724}
4725
Yiwei Zhang5434a782018-12-05 18:06:32 -08004726void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4727 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004728
4729 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4730 const size_t count = currentLayers.size();
4731 for (size_t i=0 ; i<count ; i++) {
4732 currentLayers[i]->dumpFrameEvents(result);
4733 }
4734}
4735
Yiwei Zhang5434a782018-12-05 18:06:32 -08004736void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004737 result.append("Buffering stats:\n");
4738 result.append(" [Layer name] <Active time> <Two buffer> "
4739 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004740 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004741 typedef std::tuple<std::string, float, float, float> BufferTuple;
4742 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004743 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004744 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004745 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004746 if (stats.numSegments == 0) {
4747 continue;
4748 }
4749 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4750 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4751 stats.totalTime;
4752 float doubleBufferRatio = static_cast<float>(
4753 stats.doubleBufferedTime) / stats.totalTime;
4754 float tripleBufferRatio = static_cast<float>(
4755 stats.tripleBufferedTime) / stats.totalTime;
4756 sorted.insert({activeTime, {name, twoBufferRatio,
4757 doubleBufferRatio, tripleBufferRatio}});
4758 }
4759 for (const auto& sortedPair : sorted) {
4760 float activeTime = sortedPair.first;
4761 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004762 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4763 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004764 }
4765 result.append("\n");
4766}
4767
Yiwei Zhang5434a782018-12-05 18:06:32 -08004768void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004769 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004770 const auto displayId = display->getId();
4771 if (!displayId) {
4772 continue;
4773 }
4774 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004775 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004776 continue;
4777 }
4778
Yiwei Zhang5434a782018-12-05 18:06:32 -08004779 StringAppendF(&result,
4780 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4781 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004782 uint8_t port;
4783 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004784 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004785 result.append("no identification data\n");
4786 continue;
4787 }
4788
4789 if (!isEdid(data)) {
4790 result.append("unknown identification data: ");
4791 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004792 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004793 }
4794 result.append("\n");
4795 continue;
4796 }
4797
4798 const auto edid = parseEdid(data);
4799 if (!edid) {
4800 result.append("invalid EDID: ");
4801 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004802 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004803 }
4804 result.append("\n");
4805 continue;
4806 }
4807
Yiwei Zhang5434a782018-12-05 18:06:32 -08004808 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004809 result.append(edid->displayName.data(), edid->displayName.length());
4810 result.append("\"\n");
4811 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004812}
4813
Yiwei Zhang5434a782018-12-05 18:06:32 -08004814void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4815 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4816 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4817 StringAppendF(&result, "DisplayColorSetting: %s\n",
4818 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004819
4820 // TODO: print out if wide-color mode is active or not
4821
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004822 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004823 const auto displayId = display->getId();
4824 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004825 continue;
4826 }
4827
Yiwei Zhang5434a782018-12-05 18:06:32 -08004828 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004829 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004830 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004831 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004832 }
4833
Lloyd Pique32cbe282018-10-19 13:09:22 -07004834 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004835 StringAppendF(&result, " Current color mode: %s (%d)\n",
4836 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004837 }
4838 result.append("\n");
4839}
4840
Yiwei Zhang5434a782018-12-05 18:06:32 -08004841void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004842 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004843 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4844 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004845 continue;
4846 }
4847
Dominik Laskowski05275f12018-11-01 15:03:24 -07004848 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004849 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4850 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004851 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004852 compositionInfo.dump(result, nullptr);
4853 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004854 }
4855 }
David Sodman7e4ae112018-02-09 15:02:28 -08004856}
4857
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004858LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004859 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004860 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4861 const State& state = useDrawing ? mDrawingState : mCurrentState;
4862 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004863 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004864 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004865 });
4866
4867 return layersProto;
4868}
4869
Lloyd Pique32cbe282018-10-19 13:09:22 -07004870LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004871 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004872
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004873 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004874 resolution->set_w(displayDevice.getWidth());
4875 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004876
Lloyd Pique32cbe282018-10-19 13:09:22 -07004877 auto display = displayDevice.getCompositionDisplay();
4878 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004879
Lloyd Pique32cbe282018-10-19 13:09:22 -07004880 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4881 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4882 layersProto.set_global_transform(displayState.orientation);
4883
4884 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004885 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004886 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004887 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004888 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004889 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004890 }
4891 });
4892
4893 return layersProto;
4894}
4895
Dominik Laskowskic2867142019-01-21 11:33:38 -08004896void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4897 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004898 Colorizer colorizer(colorize);
4899
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004900 // figure out if we're stuck somewhere
4901 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004902 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004903 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4904
4905 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004906 * Dump library configuration.
4907 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004908
4909 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004910 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004911 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004912 appendSfConfigString(result);
4913 appendUiConfigString(result);
4914 appendGuiConfigString(result);
4915 result.append("\n");
4916
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004917 result.append("\nDisplay identification data:\n");
4918 dumpDisplayIdentificationData(result);
4919
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004920 result.append("\nWide-Color information:\n");
4921 dumpWideColorInfo(result);
4922
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004923 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004924 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004925 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004926 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004927 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004928
Andy McFadden41d67d72014-04-25 16:58:34 -07004929 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004930 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004931 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004932 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004933 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004934
Dan Stozab90cf072015-03-05 11:05:59 -08004935 dumpStaticScreenStats(result);
4936 result.append("\n");
4937
Yiwei Zhang5434a782018-12-05 18:06:32 -08004938 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004939
Dan Stozae77c7662016-05-13 11:37:28 -07004940 dumpBufferingStats(result);
4941
Andy McFadden4803b742012-09-24 19:07:20 -07004942 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004943 * Dump the visible layer list
4944 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004945 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004946 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4947 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4948 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004949 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004950
Chia-I Wu2f884132018-09-13 15:17:58 -07004951 {
4952 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4953 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004954 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004955 result.append("\n");
4956 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004957
David Sodman7e4ae112018-02-09 15:02:28 -08004958 result.append("\nFrame-Composition information:\n");
4959 dumpFrameCompositionInfo(result);
4960 result.append("\n");
4961
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004962 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004963 * Dump Display state
4964 */
4965
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004966 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004967 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004968 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004969 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004970 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004971 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004972 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004973
4974 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004975 * Dump SurfaceFlinger global state
4976 */
4977
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004978 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004979 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004980 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004981
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004982 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004983
Dominik Laskowski075d3172018-05-24 15:50:06 -07004984 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004985 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4986 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004987 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4988 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004989 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004990 StringAppendF(&result,
4991 " transaction-flags : %08x\n"
4992 " gpu_to_cpu_unsupported : %d\n",
4993 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004994
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004995 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004996 displayId && getHwComposer().isConnected(*displayId)) {
4997 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004998 StringAppendF(&result,
4999 " refresh-rate : %f fps\n"
5000 " x-dpi : %f\n"
5001 " y-dpi : %f\n",
5002 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
5003 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005004 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005005
Yiwei Zhang5434a782018-12-05 18:06:32 -08005006 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005007
Dan Stozae22aec72016-08-01 13:20:59 -07005008 /*
Yichi Chenadc69612018-09-15 14:51:18 +08005009 * Tracing state
5010 */
5011 mTracing.dump(result);
5012 result.append("\n");
5013
5014 /*
Dan Stozae22aec72016-08-01 13:20:59 -07005015 * HWC layer minidump
5016 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005017 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07005018 const auto displayId = display->getId();
5019 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07005020 continue;
5021 }
5022
Yiwei Zhang5434a782018-12-05 18:06:32 -08005023 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07005024 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07005025 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07005026 result.append("\n");
5027 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005028
5029 /*
5030 * Dump HWComposer state
5031 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005032 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005033 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005034 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005035 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005036 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07005037 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005038
5039 /*
5040 * Dump gralloc state
5041 */
5042 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5043 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005044
5045 /*
5046 * Dump VrFlinger state if in use.
5047 */
5048 if (mVrFlingerRequestsDisplay && mVrFlinger) {
5049 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08005050 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005051 result.append("\n");
5052 }
Ana Krulecb43429d2019-01-09 14:28:51 -08005053
5054 /**
5055 * Scheduler dump state.
5056 */
5057 if (mUseScheduler) {
5058 result.append("\nScheduler state:\n");
5059 result.append(mScheduler->doDump() + "\n");
5060 result.append(mRefreshRateStats->doDump() + "\n");
5061 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005062}
5063
Dominik Laskowski075d3172018-05-24 15:50:06 -07005064const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07005065 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005066 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07005067 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005068 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07005069 }
5070 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005071
Dominik Laskowski34157762018-10-31 13:07:19 -07005072 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005073 static const Vector<sp<Layer>> empty;
5074 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07005075}
5076
Chia-I Wu28f320b2018-05-03 11:02:56 -07005077void SurfaceFlinger::updateColorMatrixLocked() {
5078 mat4 colorMatrix;
5079 if (mGlobalSaturationFactor != 1.0f) {
5080 // Rec.709 luma coefficients
5081 float3 luminance{0.213f, 0.715f, 0.072f};
5082 luminance *= 1.0f - mGlobalSaturationFactor;
5083 mat4 saturationMatrix = mat4(
5084 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
5085 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
5086 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
5087 vec4{0.0f, 0.0f, 0.0f, 1.0f}
5088 );
5089 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
5090 } else {
5091 colorMatrix = mClientColorMatrix * mDaltonizer();
5092 }
5093
5094 if (mCurrentState.colorMatrix != colorMatrix) {
5095 mCurrentState.colorMatrix = colorMatrix;
5096 mCurrentState.colorMatrixChanged = true;
5097 setTransactionFlags(eTransactionNeeded);
5098 }
5099}
5100
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005101status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005102#pragma clang diagnostic push
5103#pragma clang diagnostic error "-Wswitch-enum"
5104 switch (static_cast<ISurfaceComposerTag>(code)) {
5105 // These methods should at minimum make sure that the client requested
5106 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005107 case BOOT_FINISHED:
5108 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005109 case CREATE_DISPLAY:
5110 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005111 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005112 case GET_ACTIVE_COLOR_MODE:
5113 case GET_ANIMATION_FRAME_STATS:
5114 case GET_HDR_CAPABILITIES:
5115 case SET_ACTIVE_CONFIG:
5116 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005117 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005118 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005119 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005120 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
5121 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005122 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5123 IPCThreadState* ipc = IPCThreadState::self();
5124 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5125 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005126 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005127 }
Robert Carr1db73f62016-12-21 12:58:51 -08005128 return OK;
5129 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005130 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005131 IPCThreadState* ipc = IPCThreadState::self();
5132 const int pid = ipc->getCallingPid();
5133 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005134 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5135 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005136 return PERMISSION_DENIED;
5137 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005138 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005139 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005140 // Used by apps to hook Choreographer to SurfaceFlinger.
5141 case CREATE_DISPLAY_EVENT_CONNECTION:
5142 // The following calls are currently used by clients that do not
5143 // request necessary permissions. However, they do not expose any secret
5144 // information, so it is OK to pass them.
5145 case AUTHENTICATE_SURFACE:
5146 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005147 case GET_PHYSICAL_DISPLAY_IDS:
5148 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005149 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005150 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005151 case GET_DISPLAY_CONFIGS:
5152 case GET_DISPLAY_STATS:
5153 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5154 // Calling setTransactionState is safe, because you need to have been
5155 // granted a reference to Client* and Handle* to do anything with it.
5156 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005157 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005158 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005159 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005160 case GET_PROTECTED_CONTENT_SUPPORT:
chaviw5f21a5e2019-02-14 10:00:34 -08005161 case IS_WIDE_COLOR_DISPLAY:
5162 case SET_INPUT_WINDOWS_FINISHED: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005163 return OK;
5164 }
5165 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08005166 case CAPTURE_SCREEN:
5167 case ADD_REGION_SAMPLING_LISTENER:
5168 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005169 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005170 IPCThreadState* ipc = IPCThreadState::self();
5171 const int pid = ipc->getCallingPid();
5172 const int uid = ipc->getCallingUid();
5173 if ((uid != AID_GRAPHICS) &&
5174 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5175 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5176 return PERMISSION_DENIED;
5177 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005178 return OK;
5179 }
5180 // The following codes are deprecated and should never be allowed to access SF.
5181 case CONNECT_DISPLAY_UNUSED:
5182 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5183 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5184 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005185 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005186 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005187
5188 // These codes are used for the IBinder protocol to either interrogate the recipient
5189 // side of the transaction for its canonical interface descriptor or to dump its state.
5190 // We let them pass by default.
5191 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5192 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5193 code == IBinder::SYSPROPS_TRANSACTION) {
5194 return OK;
5195 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005196 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005197 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005198 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005199 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5200 return OK;
5201 }
5202 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5203 return PERMISSION_DENIED;
5204#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005205}
5206
Ana Krulec13be8ad2018-08-21 02:43:56 +00005207status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5208 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005209 status_t credentialCheck = CheckTransactCodeCredentials(code);
5210 if (credentialCheck != OK) {
5211 return credentialCheck;
5212 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005213
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005214 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5215 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005216 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005217 IPCThreadState* ipc = IPCThreadState::self();
5218 const int uid = ipc->getCallingUid();
5219 if (CC_UNLIKELY(uid != AID_SYSTEM
5220 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005221 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005222 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005223 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005224 return PERMISSION_DENIED;
5225 }
5226 int n;
5227 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005228 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005229 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005230 return NO_ERROR;
5231 case 1002: // SHOW_UPDATES
5232 n = data.readInt32();
5233 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005234 invalidateHwcGeometry();
5235 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005236 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005237 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005238 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005239 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005240 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005241 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005242 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005243 setTransactionFlags(
5244 eTransactionNeeded|
5245 eDisplayTransactionNeeded|
5246 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005247 return NO_ERROR;
5248 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005249 case 1006:{ // send empty update
5250 signalRefresh();
5251 return NO_ERROR;
5252 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005253 case 1008: // toggle use of hw composer
5254 n = data.readInt32();
5255 mDebugDisableHWC = n ? 1 : 0;
5256 invalidateHwcGeometry();
5257 repaintEverything();
5258 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005259 case 1009: // toggle use of transform hint
5260 n = data.readInt32();
5261 mDebugDisableTransformHint = n ? 1 : 0;
5262 invalidateHwcGeometry();
5263 repaintEverything();
5264 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005265 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005266 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005267 reply->writeInt32(0);
5268 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005269 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005270 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005271 return NO_ERROR;
5272 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005273 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005274 if (!display) {
5275 return NAME_NOT_FOUND;
5276 }
5277
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005278 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005279 return NO_ERROR;
5280 }
5281 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005282 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005283 // daltonize
5284 n = data.readInt32();
5285 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005286 case 1:
5287 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5288 break;
5289 case 2:
5290 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5291 break;
5292 case 3:
5293 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5294 break;
5295 default:
5296 mDaltonizer.setType(ColorBlindnessType::None);
5297 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005298 }
5299 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005300 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005301 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005302 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005303 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005304
5305 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005306 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005307 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005308 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005309 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005310 // apply a color matrix
5311 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005312 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005313 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005314 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005315 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005316 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005317 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005318 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005319 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005320 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005321 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005322
5323 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5324 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005325 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005326 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5327 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5328 }
5329
Chia-I Wu28f320b2018-05-03 11:02:56 -07005330 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005331 return NO_ERROR;
5332 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005333 // This is an experimental interface
5334 // Needs to be shifted to proper binder interface when we productize
5335 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005336 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005337 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005338 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005339 return NO_ERROR;
5340 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005341 case 1017: {
5342 n = data.readInt32();
5343 mForceFullDamage = static_cast<bool>(n);
5344 return NO_ERROR;
5345 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005346 case 1018: { // Modify Choreographer's phase offset
5347 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005348 if (mUseScheduler) {
5349 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5350 } else {
5351 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5352 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005353 return NO_ERROR;
5354 }
5355 case 1019: { // Modify SurfaceFlinger's phase offset
5356 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005357 if (mUseScheduler) {
5358 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5359 } else {
5360 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5361 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005362 return NO_ERROR;
5363 }
Irvel468051e2016-06-13 16:44:44 -07005364 case 1020: { // Layer updates interceptor
5365 n = data.readInt32();
5366 if (n) {
5367 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005368 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005369 }
5370 else{
5371 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005372 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005373 }
5374 return NO_ERROR;
5375 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005376 case 1021: { // Disable HWC virtual displays
5377 n = data.readInt32();
5378 mUseHwcVirtualDisplays = !n;
5379 return NO_ERROR;
5380 }
Romain Guy0147a172017-06-01 13:53:56 -07005381 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005382 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005383 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005384
Chia-I Wu28f320b2018-05-03 11:02:56 -07005385 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005386 return NO_ERROR;
5387 }
Romain Guy54f154a2017-10-24 21:40:32 +01005388 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005389 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005390 invalidateHwcGeometry();
5391 repaintEverything();
5392 return NO_ERROR;
5393 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005394 // Deprecate, use 1030 to check whether the device is color managed.
5395 case 1024: {
5396 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005397 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005398 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005399 n = data.readInt32();
5400 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005401 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005402 mTracing.enable();
5403 doTracing("tracing.enable");
5404 reply->writeInt32(NO_ERROR);
5405 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005406 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005407 status_t err = mTracing.disable();
5408 reply->writeInt32(err);
5409 }
5410 return NO_ERROR;
5411 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005412 case 1026: { // Get layer tracing status
5413 reply->writeBool(mTracing.isEnabled());
5414 return NO_ERROR;
5415 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005416 // Is a DisplayColorSetting supported?
5417 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005418 const auto display = getDefaultDisplayDevice();
5419 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005420 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005421 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005422
5423 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5424 switch (setting) {
5425 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005426 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005427 break;
5428 case DisplayColorSetting::UNMANAGED:
5429 reply->writeBool(true);
5430 break;
5431 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005432 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005433 break;
5434 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005435 reply->writeBool(
5436 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005437 break;
5438 }
5439 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005440 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005441 // Is VrFlinger active?
5442 case 1028: {
5443 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005444 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005445 return NO_ERROR;
5446 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005447 // Is device color managed?
5448 case 1030: {
5449 reply->writeBool(useColorManagement);
5450 return NO_ERROR;
5451 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005452 // Override default composition data space
5453 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5454 // && adb shell stop zygote && adb shell start zygote
5455 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5456 // adb shell stop zygote && adb shell start zygote
5457 case 1031: {
5458 Mutex::Autolock _l(mStateLock);
5459 n = data.readInt32();
5460 if (n) {
5461 n = data.readInt32();
5462 if (n) {
5463 Dataspace dataspace = static_cast<Dataspace>(n);
5464 if (!validateCompositionDataspace(dataspace)) {
5465 return BAD_VALUE;
5466 }
5467 mDefaultCompositionDataspace = dataspace;
5468 }
5469 n = data.readInt32();
5470 if (n) {
5471 Dataspace dataspace = static_cast<Dataspace>(n);
5472 if (!validateCompositionDataspace(dataspace)) {
5473 return BAD_VALUE;
5474 }
5475 mWideColorGamutCompositionDataspace = dataspace;
5476 }
5477 } else {
5478 // restore composition data space.
5479 mDefaultCompositionDataspace = defaultCompositionDataspace;
5480 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5481 }
5482 return NO_ERROR;
5483 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005484 }
5485 }
5486 return err;
5487}
5488
Steven Thomas6d8110b2017-08-31 18:24:21 -07005489void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005490 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005491 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005492}
5493
Ana Krulec7d1d6832018-12-27 11:10:09 -08005494void SurfaceFlinger::repaintEverythingForHWC() {
5495 mRepaintEverything = true;
5496 mEventQueue->invalidateForHWC();
5497}
5498
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005499// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5500class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005501public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005502 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5503 ~WindowDisconnector() {
5504 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005505 }
5506
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005507private:
5508 ANativeWindow* mWindow;
5509 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005510};
5511
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005512status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005513 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5514 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005515 uint32_t reqWidth, uint32_t reqHeight,
5516 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005517 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005518 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005519
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005520 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005521
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005522 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5523
Chia-I Wu20261cb2018-08-23 12:55:44 -07005524 sp<DisplayDevice> display;
5525 {
5526 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005527
Chia-I Wu20261cb2018-08-23 12:55:44 -07005528 display = getDisplayDeviceLocked(displayToken);
5529 if (!display) return BAD_VALUE;
5530
Chia-I Wucb023152018-08-28 12:57:23 -07005531 // set the requested width/height to the logical display viewport size
5532 // by default
5533 if (reqWidth == 0 || reqHeight == 0) {
5534 reqWidth = uint32_t(display->getViewport().width());
5535 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005536 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005537 }
5538
Peiyong Lin0e003c92018-09-17 11:09:51 -07005539 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5540 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005541
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005542 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5543 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005544 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5545 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005546}
5547
5548status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005549 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5550 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005551 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005552 ATRACE_CALL();
5553
5554 class LayerRenderArea : public RenderArea {
5555 public:
Robert Carr578038f2018-03-09 12:25:24 -08005556 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005557 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5558 bool childrenOnly)
5559 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005560 mLayer(layer),
5561 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005562 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005563 mFlinger(flinger),
5564 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005565 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005566 Rect getBounds() const override {
5567 const Layer::State& layerState(mLayer->getDrawingState());
5568 return mLayer->getBufferSize(layerState);
5569 }
Marissa Wall61c58622018-07-18 10:12:20 -07005570 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005571 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005572 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005573 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005574 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005575 }
chaviwa76b2712017-09-20 12:02:26 -07005576 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005577 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005578 Rect getSourceCrop() const override {
5579 if (mCrop.isEmpty()) {
5580 return getBounds();
5581 } else {
5582 return mCrop;
5583 }
5584 }
Robert Carr578038f2018-03-09 12:25:24 -08005585 class ReparentForDrawing {
5586 public:
5587 const sp<Layer>& oldParent;
5588 const sp<Layer>& newParent;
5589
Vishnu Nair4351ad52019-02-11 14:13:02 -08005590 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5591 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005592 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005593 // Compute and cache the bounds for the new parent layer.
5594 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005595 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005596 }
Vishnu Nair4351ad52019-02-11 14:13:02 -08005597 ~ReparentForDrawing() { newParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005598 };
5599
5600 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005601 const Rect sourceCrop = getSourceCrop();
5602 // no need to check rotation because there is none
5603 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5604 sourceCrop.height() != getReqHeight();
5605
Robert Carr578038f2018-03-09 12:25:24 -08005606 if (!mChildrenOnly) {
5607 mTransform = mLayer->getTransform().inverse();
5608 drawLayers();
5609 } else {
5610 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005611 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005612 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5613 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005614
Vishnu Nair4351ad52019-02-11 14:13:02 -08005615 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005616 drawLayers();
5617 }
5618 }
chaviwa76b2712017-09-20 12:02:26 -07005619
chaviwa76b2712017-09-20 12:02:26 -07005620 private:
chaviw7206d492017-11-10 16:16:12 -08005621 const sp<Layer> mLayer;
5622 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005623
5624 // In the "childrenOnly" case we reparent the children to a screenshot
5625 // layer which has no properties set and which does not draw.
5626 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005627 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005628 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005629
5630 SurfaceFlinger* mFlinger;
5631 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005632 };
5633
5634 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5635 auto parent = layerHandle->owner.promote();
5636
Robert Carr2e102c92018-10-23 12:11:15 -07005637 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005638 ALOGE("captureLayers called with a removed parent");
5639 return NAME_NOT_FOUND;
5640 }
5641
Robert Carr578038f2018-03-09 12:25:24 -08005642 const int uid = IPCThreadState::self()->getCallingUid();
5643 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005644 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005645 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5646 return PERMISSION_DENIED;
5647 }
5648
chaviw7206d492017-11-10 16:16:12 -08005649 Rect crop(sourceCrop);
5650 if (sourceCrop.width() <= 0) {
5651 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005652 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005653 }
5654
5655 if (sourceCrop.height() <= 0) {
5656 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005657 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005658 }
5659
5660 int32_t reqWidth = crop.width() * frameScale;
5661 int32_t reqHeight = crop.height() * frameScale;
5662
Chia-I Wu20261cb2018-08-23 12:55:44 -07005663 // really small crop or frameScale
5664 if (reqWidth <= 0) {
5665 reqWidth = 1;
5666 }
5667 if (reqHeight <= 0) {
5668 reqHeight = 1;
5669 }
5670
Peiyong Lin0e003c92018-09-17 11:09:51 -07005671 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005672
Robert Carr578038f2018-03-09 12:25:24 -08005673 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005674 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5675 if (!layer->isVisible()) {
5676 return;
Robert Carr578038f2018-03-09 12:25:24 -08005677 } else if (childrenOnly && layer == parent.get()) {
5678 return;
chaviwa76b2712017-09-20 12:02:26 -07005679 }
5680 visitor(layer);
5681 });
5682 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005683 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005684}
5685
5686status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5687 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005688 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005689 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005690 bool useIdentityTransform) {
5691 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005692
Peiyong Lin0e003c92018-09-17 11:09:51 -07005693 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005694 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5695 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005696 *outBuffer =
5697 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5698 static_cast<android_pixel_format>(reqPixelFormat), 1,
5699 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005700
5701 // This mutex protects syncFd and captureResult for communication of the return values from the
5702 // main thread back to this Binder thread
5703 std::mutex captureMutex;
5704 std::condition_variable captureCondition;
5705 std::unique_lock<std::mutex> captureLock(captureMutex);
5706 int syncFd = -1;
5707 std::optional<status_t> captureResult;
5708
Robert Carr03480e22018-01-04 16:02:06 -08005709 const int uid = IPCThreadState::self()->getCallingUid();
5710 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5711
Dominik Laskowski8c001672018-05-30 16:52:06 -07005712 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005713 // If there is a refresh pending, bug out early and tell the binder thread to try again
5714 // after the refresh.
5715 if (mRefreshPending) {
5716 ATRACE_NAME("Skipping screenshot for now");
5717 std::unique_lock<std::mutex> captureLock(captureMutex);
5718 captureResult = std::make_optional<status_t>(EAGAIN);
5719 captureCondition.notify_one();
5720 return;
5721 }
5722
5723 status_t result = NO_ERROR;
5724 int fd = -1;
5725 {
5726 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005727 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005728 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5729 useIdentityTransform, forSystem, &fd);
5730 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005731 }
5732
5733 {
5734 std::unique_lock<std::mutex> captureLock(captureMutex);
5735 syncFd = fd;
5736 captureResult = std::make_optional<status_t>(result);
5737 captureCondition.notify_one();
5738 }
5739 });
5740
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005741 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005742 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005743 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005744 while (*captureResult == EAGAIN) {
5745 captureResult.reset();
5746 result = postMessageAsync(message);
5747 if (result != NO_ERROR) {
5748 return result;
5749 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005750 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005751 }
5752 result = *captureResult;
5753 }
5754
5755 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005756 sync_wait(syncFd, -1);
5757 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005758 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005759
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005760 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005761}
5762
chaviwa76b2712017-09-20 12:02:26 -07005763void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005764 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005765 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5766 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005767 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005768
chaviwa76b2712017-09-20 12:02:26 -07005769 const auto reqWidth = renderArea.getReqWidth();
5770 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005771 const auto sourceCrop = renderArea.getSourceCrop();
5772 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005773
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005774 renderengine::DisplaySettings clientCompositionDisplay;
5775 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005776
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005777 // assume that bounds are never offset, and that they are the same as the
5778 // buffer bounds.
5779 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5780 ui::Transform transform = renderArea.getTransform();
5781 mat4 m;
5782 m[0][0] = transform[0][0];
5783 m[0][1] = transform[0][1];
5784 m[0][3] = transform[0][2];
5785 m[1][0] = transform[1][0];
5786 m[1][1] = transform[1][1];
5787 m[1][3] = transform[1][2];
5788 m[3][0] = transform[2][0];
5789 m[3][1] = transform[2][1];
5790 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005791
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005792 clientCompositionDisplay.globalTransform = m;
5793 mat4 rotMatrix;
5794 // Displacement for repositioning the clipping rectangle after rotating it
5795 // with the rotation hint.
5796 int displacementX = 0;
5797 int displacementY = 0;
5798 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5799 switch (rotation) {
5800 case ui::Transform::ROT_90:
5801 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5802 displacementX = reqWidth;
5803 break;
5804 case ui::Transform::ROT_180:
5805 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5806 displacementX = reqWidth;
5807 displacementY = reqHeight;
5808 break;
5809 case ui::Transform::ROT_270:
5810 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5811 displacementY = reqHeight;
5812 break;
5813 default:
5814 break;
5815 }
5816 // We need to transform the clipping window into the right spot.
5817 // First, rotate the clipping rectangle by the rotation hint to get the
5818 // right orientation
5819 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5820 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5821 const vec4 rotClipTL = rotMatrix * clipTL;
5822 const vec4 rotClipBR = rotMatrix * clipBR;
5823 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5824 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5825 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5826 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5827
5828 // Now reposition the clipping rectangle with the displacement vector
5829 // computed above.
5830 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5831
5832 clientCompositionDisplay.clip =
5833 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5834 newClipRight + displacementX, newClipBottom + displacementY);
5835
5836 // We need to perform the same transformation in layer space, so propagate
5837 // it to the global transform.
5838 mat4 clipTransform = displacementMat * rotMatrix;
5839 clientCompositionDisplay.globalTransform *= clipTransform;
5840 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5841 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005842
chaviw50da5042018-04-09 13:49:37 -07005843 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005844
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005845 renderengine::LayerSettings fillLayer;
5846 fillLayer.source.buffer.buffer = nullptr;
5847 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5848 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5849 fillLayer.alpha = half(alpha);
5850 clientCompositionLayers.push_back(fillLayer);
5851
5852 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005853 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005854 renderengine::LayerSettings layerSettings;
5855 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5856 layerSettings);
5857 if (prepared) {
5858 clientCompositionLayers.push_back(layerSettings);
5859 }
chaviwa76b2712017-09-20 12:02:26 -07005860 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005861
5862 clientCompositionDisplay.clearRegion = clearRegion;
5863 base::unique_fd drawFence;
5864 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
5865 &drawFence);
5866
5867 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005868}
5869
chaviwa76b2712017-09-20 12:02:26 -07005870status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5871 TraverseLayersFunction traverseLayers,
5872 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005873 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005874 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005875 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005876 ATRACE_CALL();
5877
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005878 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005879
5880 traverseLayers([&](Layer* layer) {
5881 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5882 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005883
Robert Carr03480e22018-01-04 16:02:06 -08005884 // We allow the system server to take screenshots of secure layers for
5885 // use in situations like the Screen-rotation animation and place
5886 // the impetus on WindowManager to not persist them.
5887 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005888 ALOGW("FB is protected: PERMISSION_DENIED");
5889 return PERMISSION_DENIED;
5890 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005891 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005892 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005893}
5894
chaviw5f21a5e2019-02-14 10:00:34 -08005895void SurfaceFlinger::setInputWindowsFinished() {}
5896
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005897// ---------------------------------------------------------------------------
5898
Dan Stoza412903f2017-04-27 13:42:17 -07005899void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5900 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005901}
5902
Dan Stoza412903f2017-04-27 13:42:17 -07005903void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5904 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005905}
5906
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005907void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005908 const LayerVector::Visitor& visitor) {
5909 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005910 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005911 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005912 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005913 continue;
5914 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005915 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005916 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005917 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005918 return;
5919 }
chaviwa76b2712017-09-20 12:02:26 -07005920 if (!layer->isVisible()) {
5921 return;
5922 }
5923 visitor(layer);
5924 });
5925 }
5926}
5927
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005928}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005929
Lloyd Pique074e8122018-07-26 12:57:23 -07005930
Mathias Agopian3f844832013-08-07 21:24:32 -07005931#if defined(__gl_h_)
5932#error "don't include gl/gl.h in this file"
5933#endif
5934
5935#if defined(__gl2_h_)
5936#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005937#endif