blob: c127609370c9bba8992a5185db4fcda457f3c8d9 [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));
Romain Guy11d63f42017-07-20 12:47:14 -0700774}
775
Mathias Agopiana67e4182012-06-19 17:26:12 -0700776void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800777 // Start boot animation service by setting a property mailbox
778 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700779 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800780 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700781 if (mStartPropertySetThread->join() != NO_ERROR) {
782 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800783 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700784}
785
Mathias Agopian875d8e12013-06-07 15:35:48 -0700786size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700787 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700788}
789
Mathias Agopian875d8e12013-06-07 15:35:48 -0700790size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700791 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700792}
793
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800794// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800795
Jamie Gennis582270d2011-08-17 18:19:00 -0700796bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800797 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800798 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800799 return authenticateSurfaceTextureLocked(bufferProducer);
800}
801
802bool SurfaceFlinger::authenticateSurfaceTextureLocked(
803 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800804 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800805 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800806}
807
Brian Anderson6b376712017-04-04 10:51:39 -0700808status_t SurfaceFlinger::getSupportedFrameTimestamps(
809 std::vector<FrameEvent>* outSupported) const {
810 *outSupported = {
811 FrameEvent::REQUESTED_PRESENT,
812 FrameEvent::ACQUIRE,
813 FrameEvent::LATCH,
814 FrameEvent::FIRST_REFRESH_START,
815 FrameEvent::LAST_REFRESH_START,
816 FrameEvent::GPU_COMPOSITION_DONE,
817 FrameEvent::DEQUEUE_READY,
818 FrameEvent::RELEASE,
819 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700820 ConditionalLock _l(mStateLock,
821 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700822 if (!getHwComposer().hasCapability(
823 HWC2::Capability::PresentFenceIsNotReliable)) {
824 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
825 }
826 return NO_ERROR;
827}
828
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800829status_t SurfaceFlinger::getDisplayConfigsLocked(const sp<IBinder>& displayToken,
830 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700831 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700832 return BAD_VALUE;
833 }
834
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800835 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700836 if (!displayId) {
837 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700838 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700839
Mathias Agopian8b736f12012-08-13 17:54:26 -0700840 // TODO: Not sure if display density should handled by SF any longer
841 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700842 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700843 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700844 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800845 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700846 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700847 }
848 return density;
849 }
850 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700851 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700852 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700853 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700854 return getDensityFromProperty("ro.sf.lcd_density"); }
855 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700856
Dan Stoza7f7da322014-05-02 15:26:25 -0700857 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700858
Dominik Laskowski075d3172018-05-24 15:50:06 -0700859 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700860 DisplayInfo info = DisplayInfo();
861
Dan Stoza9e56aa02015-11-02 13:00:03 -0800862 float xdpi = hwConfig->getDpiX();
863 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700864
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700865 info.w = hwConfig->getWidth();
866 info.h = hwConfig->getHeight();
867 // Default display viewport to display width and height
868 info.viewportW = info.w;
869 info.viewportH = info.h;
870
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800871 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700872 // The density of the device is provided by a build property
873 float density = Density::getBuildDensity() / 160.0f;
874 if (density == 0) {
875 // the build doesn't provide a density -- this is wrong!
876 // use xdpi instead
877 ALOGE("ro.sf.lcd_density must be defined as a build property");
878 density = xdpi / 160.0f;
879 }
880 if (Density::getEmuDensity()) {
881 // if "qemu.sf.lcd_density" is specified, it overrides everything
882 xdpi = ydpi = density = Density::getEmuDensity();
883 density /= 160.0f;
884 }
885 info.density = density;
886
887 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700888 const auto display = getDefaultDisplayDeviceLocked();
889 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700890
891 // This is for screenrecord
892 const Rect viewport = display->getViewport();
893 if (viewport.isValid()) {
894 info.viewportW = uint32_t(viewport.getWidth());
895 info.viewportH = uint32_t(viewport.getHeight());
896 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700897 } else {
898 // TODO: where should this value come from?
899 static const int TV_DENSITY = 213;
900 info.density = TV_DENSITY / 160.0f;
901 info.orientation = 0;
902 }
903
Dan Stoza7f7da322014-05-02 15:26:25 -0700904 info.xdpi = xdpi;
905 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800906 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800907 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800908
Andy McFadden91b2ca82014-06-13 14:04:23 -0700909 // This is how far in advance a buffer must be queued for
910 // presentation at a given time. If you want a buffer to appear
911 // on the screen at time N, you must submit the buffer before
912 // (N - presentationDeadline).
913 //
914 // Normally it's one full refresh period (to give SF a chance to
915 // latch the buffer), but this can be reduced by configuring a
916 // DispSync offset. Any additional delays introduced by the hardware
917 // composer or panel must be accounted for here.
918 //
919 // We add an additional 1ms to allow for processing time and
920 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800921 info.presentationDeadline =
922 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700923
924 // All non-virtual displays are currently considered secure.
925 info.secure = true;
926
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800927 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700928 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800929 std::swap(info.w, info.h);
930 }
931
Michael Wright28f24d02016-07-12 13:30:53 -0700932 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700933 }
934
Dan Stoza7f7da322014-05-02 15:26:25 -0700935 return NO_ERROR;
936}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700937
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700938status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
939 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700940 return BAD_VALUE;
941 }
942
Ana Krulece588e312018-09-18 12:32:24 -0700943 if (mUseScheduler) {
944 mScheduler->getDisplayStatInfo(stats);
945 } else {
946 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
947 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
948 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700949 return NO_ERROR;
950}
951
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700952int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
953 const auto display = getDisplayDevice(displayToken);
954 if (!display) {
955 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800956 return BAD_VALUE;
957 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700958
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700959 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700960}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700961
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800962void SurfaceFlinger::setDesiredActiveConfig(const sp<IBinder>& displayToken, int mode) {
963 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800964
Ana Krulec7d1d6832018-12-27 11:10:09 -0800965 Vector<DisplayInfo> configs;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800966 // Lock is acquired by setRefreshRateTo.
967 getDisplayConfigsLocked(displayToken, &configs);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800968 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
969 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
970 return;
971 }
972
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800973 // Lock is acquired by setRefreshRateTo.
974 const auto display = getDisplayDeviceLocked(displayToken);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800975 if (!display) {
976 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
977 displayToken.get());
978 return;
979 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700980 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800981 ALOGW("Attempt to set active config %d for virtual display", mode);
982 return;
983 }
984 int currentDisplayPowerMode = display->getPowerMode();
985 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
986 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700987 return;
988 }
989
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800990 // Don't check against the current mode yet. Worst case we set the desired
991 // config twice.
992 {
993 std::lock_guard<std::mutex> lock(mActiveConfigLock);
994 mDesiredActiveConfig = ActiveConfigInfo{mode, displayToken};
995 }
996 // This will trigger HWC refresh without resetting the idle timer.
997 repaintEverythingForHWC();
998}
999
1000status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
1001 ATRACE_CALL();
1002 postMessageSync(new LambdaMessage(
1003 [&]() NO_THREAD_SAFETY_ANALYSIS { setDesiredActiveConfig(displayToken, mode); }));
1004 return NO_ERROR;
1005}
1006
1007void SurfaceFlinger::setActiveConfigInHWC() {
1008 ATRACE_CALL();
1009
1010 const auto display = getDisplayDevice(mUpcomingActiveConfig.displayToken);
1011 if (!display) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001012 return;
1013 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001014 const auto displayId = display->getId();
1015 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001016
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001017 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1018 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1019 mSetActiveConfigState = SetActiveConfigState::NOTIFIED_HWC;
1020 ATRACE_INT("SetActiveConfigState", mSetActiveConfigState);
1021}
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001022
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001023void SurfaceFlinger::setActiveConfigInternal() {
1024 ATRACE_CALL();
1025
1026 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1027 if (mUseScheduler) {
1028 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
1029 }
1030
1031 const auto display = getDisplayDeviceLocked(mUpcomingActiveConfig.displayToken);
1032 display->setActiveConfig(mUpcomingActiveConfig.configId);
1033
1034 mSetActiveConfigState = SetActiveConfigState::NONE;
1035 ATRACE_INT("SetActiveConfigState", mSetActiveConfigState);
1036
Dominik Laskowski83b88212018-12-11 13:34:06 -08001037 resyncToHardwareVsync(true, getVsyncPeriod());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001038 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
1039}
1040
1041bool SurfaceFlinger::updateSetActiveConfigStateMachine() NO_THREAD_SAFETY_ANALYSIS {
1042 // Store the local variable to release the lock.
1043 ActiveConfigInfo desiredActiveConfig;
1044 {
1045 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1046 desiredActiveConfig = mDesiredActiveConfig;
1047 }
1048
1049 const auto display = getDisplayDevice(desiredActiveConfig.displayToken);
1050 if (display) {
1051 if (mSetActiveConfigState == SetActiveConfigState::NONE &&
1052 display->getActiveConfig() != desiredActiveConfig.configId) {
1053 // Step 1) Desired active config was set, it is different than the
1054 // config currently in use. Notify HWC.
1055 mUpcomingActiveConfig = desiredActiveConfig;
1056 setActiveConfigInHWC();
1057 } else if (mSetActiveConfigState == SetActiveConfigState::NOTIFIED_HWC) {
1058 // Step 2) HWC was notified and we received refresh from it.
1059 mSetActiveConfigState = SetActiveConfigState::REFRESH_RECEIVED;
1060 ATRACE_INT("SetActiveConfigState", mSetActiveConfigState);
1061 repaintEverythingForHWC();
1062 // We do not want to give another frame to HWC while we are transitioning.
1063 return false;
1064 } else if (mSetActiveConfigState == SetActiveConfigState::REFRESH_RECEIVED &&
1065 !(mPreviousPresentFence != Fence::NO_FENCE &&
1066 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled))) {
1067 // Step 3) We received the present fence from the HWC, so we assume it
1068 // successfully updated the config, hence we update SF.
1069 setActiveConfigInternal();
1070 // If the config changed again while we were transitioning, restart the
1071 // process.
1072 if (desiredActiveConfig != mUpcomingActiveConfig) {
1073 mUpcomingActiveConfig = desiredActiveConfig;
1074 setActiveConfigInHWC(); // sets the state to NOTIFY_HWC
1075 }
1076 }
1077 }
1078 return true;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001079}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001080
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001081status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1082 Vector<ColorMode>* outColorModes) {
1083 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001084 return BAD_VALUE;
1085 }
1086
Peiyong Lina52f0292018-03-14 17:26:31 -07001087 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001088 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001089 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1090
1091 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1092 if (!displayId) {
1093 return NAME_NOT_FOUND;
1094 }
1095
Dominik Laskowski075d3172018-05-24 15:50:06 -07001096 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001097 }
Michael Wright28f24d02016-07-12 13:30:53 -07001098 outColorModes->clear();
1099 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1100
1101 return NO_ERROR;
1102}
1103
Daniel Solomon42d04562019-01-20 21:03:19 -08001104status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1105 ui::DisplayPrimaries &primaries) {
1106 if (!displayToken) {
1107 return BAD_VALUE;
1108 }
1109
1110 // Currently we only support this API for a single internal display.
1111 if (getInternalDisplayToken() != displayToken) {
1112 return BAD_VALUE;
1113 }
1114
1115 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1116 return NO_ERROR;
1117}
1118
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001119ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1120 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001121 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001122 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001123 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001124}
1125
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001126status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001127 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001128 Vector<ColorMode> modes;
1129 getDisplayColorModes(displayToken, &modes);
1130 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1131 if (mode < ColorMode::NATIVE || !exists) {
1132 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1133 decodeColorMode(mode).c_str(), mode, displayToken.get());
1134 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001135 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001136 const auto display = getDisplayDevice(displayToken);
1137 if (!display) {
1138 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1139 decodeColorMode(mode).c_str(), mode, displayToken.get());
1140 } else if (display->isVirtual()) {
1141 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1142 decodeColorMode(mode).c_str(), mode);
1143 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001144 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1145 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001146 }
1147 }));
1148
Michael Wright28f24d02016-07-12 13:30:53 -07001149 return NO_ERROR;
1150}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001151
Svetoslavd85084b2014-03-20 10:28:31 -07001152status_t SurfaceFlinger::clearAnimationFrameStats() {
1153 Mutex::Autolock _l(mStateLock);
1154 mAnimFrameTracker.clearStats();
1155 return NO_ERROR;
1156}
1157
1158status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1159 Mutex::Autolock _l(mStateLock);
1160 mAnimFrameTracker.getStats(outStats);
1161 return NO_ERROR;
1162}
1163
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001164status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1165 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001166 Mutex::Autolock _l(mStateLock);
1167
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001168 const auto display = getDisplayDeviceLocked(displayToken);
1169 if (!display) {
1170 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001171 return BAD_VALUE;
1172 }
1173
Peiyong Linfb069302018-04-25 14:34:31 -07001174 // At this point the DisplayDeivce should already be set up,
1175 // meaning the luminance information is already queried from
1176 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001177 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001178 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1179 capabilities.getDesiredMaxLuminance(),
1180 capabilities.getDesiredMaxAverageLuminance(),
1181 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001182
1183 return NO_ERROR;
1184}
1185
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001186status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1187 ui::PixelFormat* outFormat,
1188 ui::Dataspace* outDataspace,
1189 uint8_t* outComponentMask) const {
1190 if (!outFormat || !outDataspace || !outComponentMask) {
1191 return BAD_VALUE;
1192 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001193 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001194 if (!display || !display->getId()) {
1195 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1196 return BAD_VALUE;
1197 }
1198 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1199 outDataspace, outComponentMask);
1200}
1201
Kevin DuBois74e53772018-11-19 10:52:38 -08001202status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1203 bool enable, uint8_t componentMask,
1204 uint64_t maxFrames) const {
1205 const auto display = getDisplayDevice(displayToken);
1206 if (!display || !display->getId()) {
1207 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1208 return BAD_VALUE;
1209 }
1210
1211 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1212 componentMask, maxFrames);
1213}
1214
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001215status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1216 uint64_t maxFrames, uint64_t timestamp,
1217 DisplayedFrameStats* outStats) const {
1218 const auto display = getDisplayDevice(displayToken);
1219 if (!display || !display->getId()) {
1220 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1221 return BAD_VALUE;
1222 }
1223
1224 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1225 outStats);
1226}
1227
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001228status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1229 if (!outSupported) {
1230 return BAD_VALUE;
1231 }
1232 *outSupported = getRenderEngine().supportsProtectedContent();
1233 return NO_ERROR;
1234}
1235
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001236status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1237 bool* outIsWideColorDisplay) const {
1238 if (!displayToken || !outIsWideColorDisplay) {
1239 return BAD_VALUE;
1240 }
1241 Mutex::Autolock _l(mStateLock);
1242 const auto display = getDisplayDeviceLocked(displayToken);
1243 if (!display) {
1244 return BAD_VALUE;
1245 }
1246 *outIsWideColorDisplay = display->hasWideColorGamut();
1247 return NO_ERROR;
1248}
1249
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001250status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001251 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001252 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001253
Chia-I Wu90f669f2017-10-05 14:24:41 -07001254 if (mInjectVSyncs == enable) {
1255 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001256 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001257
Dominik Laskowski83b88212018-12-11 13:34:06 -08001258 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001259
Ana Krulec98b5b242018-08-10 15:03:23 -07001260 // TODO(akrulec): Part of the Injector should be refactored, so that it
1261 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001262 if (enable) {
1263 ALOGV("VSync Injections enabled");
1264 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001265 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001266 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001267 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001268 impl::EventThread::InterceptVSyncsCallback(),
1269 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001270 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001271 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001272 } else {
1273 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001274 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001275 }
1276
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001277 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001278 }));
1279
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001280 return NO_ERROR;
1281}
1282
1283status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001284 Mutex::Autolock _l(mStateLock);
1285
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001286 if (!mInjectVSyncs) {
1287 ALOGE("VSync Injections not enabled");
1288 return BAD_VALUE;
1289 }
1290 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1291 ALOGV("Injecting VSync inside SurfaceFlinger");
1292 mVSyncInjector->onInjectSyncEvent(when);
1293 }
1294 return NO_ERROR;
1295}
1296
Lloyd Pique755e3192018-01-31 16:46:15 -08001297status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1298 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001299 // Try to acquire a lock for 1s, fail gracefully
1300 const status_t err = mStateLock.timedLock(s2ns(1));
1301 const bool locked = (err == NO_ERROR);
1302 if (!locked) {
1303 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1304 return TIMED_OUT;
1305 }
1306
1307 outLayers->clear();
1308 mCurrentState.traverseInZOrder([&](Layer* layer) {
1309 outLayers->push_back(layer->getLayerDebugInfo());
1310 });
1311
1312 mStateLock.unlock();
1313 return NO_ERROR;
1314}
1315
Peiyong Linc6780972018-10-28 15:24:08 -07001316status_t SurfaceFlinger::getCompositionPreference(
1317 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1318 Dataspace* outWideColorGamutDataspace,
1319 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001320 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001321 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001322 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001323 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001324 return NO_ERROR;
1325}
1326
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001327// ----------------------------------------------------------------------------
1328
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001329sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1330 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001331 auto resyncCallback = makeResyncCallback([this] {
1332 Mutex::Autolock lock(mStateLock);
1333 return getVsyncPeriod();
1334 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001335
Ana Krulec98b5b242018-08-10 15:03:23 -07001336 if (mUseScheduler) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001337 const auto& handle = vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle
1338 : mAppConnectionHandle;
1339
Ady Abrahama1a49af2019-02-07 14:36:55 -08001340 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001341 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001342 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001343 return mSFEventThread->createEventConnection(resyncCallback, ResetIdleTimerCallback());
Ana Krulec98b5b242018-08-10 15:03:23 -07001344 } else {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001345 return mEventThread->createEventConnection(resyncCallback, ResetIdleTimerCallback());
Ana Krulec98b5b242018-08-10 15:03:23 -07001346 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001347 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001348}
1349
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001350// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001351
1352void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001353 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001354}
1355
1356void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001357 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001358}
1359
1360void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001361 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001362}
1363
1364void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001365 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001366 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001367}
1368
1369status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001370 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001371 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001372}
1373
1374status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001375 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001376 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001377 if (res == NO_ERROR) {
1378 msg->wait();
1379 }
1380 return res;
1381}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001382
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001383void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001384 do {
1385 waitForEvent();
1386 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001387}
1388
Dominik Laskowski83b88212018-12-11 13:34:06 -08001389nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001390 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001391 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1392 return 0;
1393 }
1394
1395 const auto config = getHwComposer().getActiveConfig(*displayId);
1396 return config ? config->getVsyncPeriod() : 0;
1397}
1398
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001399void SurfaceFlinger::enableHardwareVsync() {
Ady Abrahamc3e21312019-02-07 14:30:23 -08001400 assert(!mUseScheduler);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001401 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001402 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001403 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001404 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001405 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001406 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001407}
1408
Dominik Laskowski83b88212018-12-11 13:34:06 -08001409void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001410 Mutex::Autolock _l(mHWVsyncLock);
Ady Abraham3aff9172019-02-07 19:10:26 -08001411 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1412 if (mUseScheduler) {
1413 if (makeAvailable) {
Ana Krulec7ab56032018-11-02 20:51:06 +01001414 mScheduler->makeHWSyncAvailable(true);
Ady Abraham3aff9172019-02-07 19:10:26 -08001415 } else if (!mScheduler->getHWSyncAvailable()) {
1416 // Hardware vsync is not currently available, so abort the resync
1417 // attempt for now
1418 return;
Ana Krulec7ab56032018-11-02 20:51:06 +01001419 }
Ady Abraham3aff9172019-02-07 19:10:26 -08001420 } else {
1421 if (makeAvailable) {
1422 mHWVsyncAvailable = true;
1423 } else if (!mHWVsyncAvailable) {
1424 // Hardware vsync is not currently available, so abort the resync
1425 // attempt for now
1426 return;
1427 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001428 }
1429
Dominik Laskowski83b88212018-12-11 13:34:06 -08001430 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001431 return;
1432 }
1433
Ana Krulece588e312018-09-18 12:32:24 -07001434 if (mUseScheduler) {
1435 mScheduler->setVsyncPeriod(period);
1436 } else {
1437 mPrimaryDispSync->reset();
1438 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001439
Ana Krulece588e312018-09-18 12:32:24 -07001440 if (!mPrimaryHWVsyncEnabled) {
1441 mPrimaryDispSync->beginResync();
1442 mEventControlThread->setVsyncEnabled(true);
1443 mPrimaryHWVsyncEnabled = true;
1444 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001445 }
1446}
1447
Jesse Hall948fe0c2013-10-14 12:56:09 -07001448void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Ady Abrahamc3e21312019-02-07 14:30:23 -08001449 assert(!mUseScheduler);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001450 Mutex::Autolock _l(mHWVsyncLock);
1451 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001452 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001453 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001454 mPrimaryHWVsyncEnabled = false;
1455 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001456 if (makeUnavailable) {
1457 mHWVsyncAvailable = false;
1458 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001459}
1460
Dominik Laskowski83b88212018-12-11 13:34:06 -08001461void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001462 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001463
Dan Stoza57164302017-05-08 14:03:54 -07001464 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001465 const nsecs_t last = lastResyncTime.exchange(now);
1466
1467 if (now - last > kIgnoreDelay) {
1468 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001469 }
1470}
1471
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001472void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1473 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001474 ATRACE_NAME("SF onVsync");
1475
Steven Thomas3cfac282017-02-06 12:29:30 -08001476 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001477 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001478 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001479 return;
1480 }
1481
Dominik Laskowski075d3172018-05-24 15:50:06 -07001482 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001483 return;
1484 }
1485
Dominik Laskowski075d3172018-05-24 15:50:06 -07001486 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001487 // For now, we don't do anything with external display vsyncs.
1488 return;
1489 }
1490
Ana Krulece588e312018-09-18 12:32:24 -07001491 if (mUseScheduler) {
1492 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001493 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001494 bool needsHwVsync = false;
1495 { // Scope for the lock
1496 Mutex::Autolock _l(mHWVsyncLock);
1497 if (mPrimaryHWVsyncEnabled) {
1498 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1499 }
1500 }
1501
1502 if (needsHwVsync) {
1503 enableHardwareVsync();
1504 } else {
1505 disableHardwareVsync(false);
1506 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001507 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001508}
1509
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001510void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001511 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1512 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001513}
1514
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001515void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate) {
1516 mPhaseOffsets->setRefreshRateType(refreshRate);
1517
1518 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1519 mVsyncModulator.setPhaseOffsets(early, gl, late);
1520
1521 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001522 return;
1523 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001524
Ana Krulec7d1d6832018-12-27 11:10:09 -08001525 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1526 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1527 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1528 // refresh cycle.
1529
1530 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001531 const nsecs_t currentVsyncPeriod = getVsyncPeriod();
Ana Krulec7d1d6832018-12-27 11:10:09 -08001532 if (currentVsyncPeriod == 0) {
1533 return;
1534 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001535
Ana Krulec7d1d6832018-12-27 11:10:09 -08001536 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1537 // floating numbers.
1538 const float currentFps = 1e9 / currentVsyncPeriod;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001539 const float newFps = refreshRate == RefreshRateType::PERFORMANCE ? kPerformanceRefreshRate
1540 : kDefaultRefreshRate;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001541 if (std::abs(currentFps - newFps) <= 1) {
1542 return;
1543 }
1544
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001545 const auto displayId = getInternalDisplayIdLocked();
1546 LOG_ALWAYS_FATAL_IF(!displayId);
1547
1548 auto configs = getHwComposer().getConfigs(*displayId);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001549 for (int i = 0; i < configs.size(); i++) {
1550 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1551 if (vsyncPeriod == 0) {
1552 continue;
1553 }
1554 const float fps = 1e9 / vsyncPeriod;
1555 // TODO(b/113612090): There should be a better way at determining which config
1556 // has the right refresh rate.
1557 if (std::abs(fps - newFps) <= 1) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001558 setDesiredActiveConfig(getInternalDisplayTokenLocked(), i);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001559 }
1560 }
1561}
1562
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001563void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001564 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001565 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001566 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001567
Lloyd Piqueba04e622017-12-14 17:11:26 -08001568 // Ignore events that do not have the right sequenceId.
1569 if (sequenceId != getBE().mComposerSequenceId) {
1570 return;
1571 }
1572
Steven Thomasb02664d2017-07-26 18:48:28 -07001573 // Only lock if we're not on the main thread. This function is normally
1574 // called on a hwbinder thread, but for the primary display it's called on
1575 // the main thread with the state lock already held, so don't attempt to
1576 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001577 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001578
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001579 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001580
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001581 if (std::this_thread::get_id() == mMainThreadId) {
1582 // Process all pending hot plug events immediately if we are on the main thread.
1583 processDisplayHotplugEventsLocked();
1584 }
1585
Lloyd Piqueba04e622017-12-14 17:11:26 -08001586 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001587}
1588
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001589void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001590 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001591 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001592 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001593 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001594 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001595}
1596
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001597void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001598 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001599 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001600 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001601 getHwComposer().setVsyncEnabled(*displayId,
1602 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1603 }
Mathias Agopian86303202012-07-24 22:46:10 -07001604}
1605
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001606// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001607void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001608 if (mUseScheduler) {
1609 mScheduler->disableHardwareVsync(true);
1610 } else {
1611 disableHardwareVsync(true);
1612 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001613 // Clear the drawing state so that the logic inside of
1614 // handleTransactionLocked will fire. It will determine the delta between
1615 // mCurrentState and mDrawingState and re-apply all changes when we make the
1616 // transition.
1617 mDrawingState.displays.clear();
1618 mDisplays.clear();
1619}
1620
Steven Thomas050b2c82017-03-06 11:45:16 -08001621void SurfaceFlinger::updateVrFlinger() {
1622 if (!mVrFlinger)
1623 return;
1624 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001625 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001626 return;
1627 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001628
Lloyd Pique441d5042018-10-18 16:49:51 -07001629 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001630 ALOGE("Vr flinger is only supported for remote hardware composer"
1631 " service connections. Ignoring request to transition to vr"
1632 " flinger.");
1633 mVrFlingerRequestsDisplay = false;
1634 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001635 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001636
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001637 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001638
Steven Thomas0123ac62018-07-12 11:32:34 -07001639 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001640 LOG_ALWAYS_FATAL_IF(!display);
1641 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001642 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1643 // called below. Clear the reference now so we don't accidentally use it
1644 // later.
1645 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001646
Steven Thomasb02664d2017-07-26 18:48:28 -07001647 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001648 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001649 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001650
Steven Thomasb02664d2017-07-26 18:48:28 -07001651 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001652 // Delete the current instance before creating the new one
1653 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1654 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1655 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1656 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001657
Lloyd Pique441d5042018-10-18 16:49:51 -07001658 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001659 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001660
1661 if (vrFlingerRequestsDisplay) {
1662 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001663 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001664
1665 mVisibleRegionsDirty = true;
1666 invalidateHwcGeometry();
1667
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001668 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001669 display = getDefaultDisplayDeviceLocked();
1670 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001671 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001672
Steven Thomasb02664d2017-07-26 18:48:28 -07001673 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001674 const nsecs_t vsyncPeriod = getVsyncPeriod();
1675 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001676
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001677 // The present fences returned from vr_hwc are not an accurate
1678 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001679 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001680 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1681 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001682 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001683 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001684 !hasSyncFramework);
1685 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001686
Steven Thomasb02664d2017-07-26 18:48:28 -07001687 // Use phase of 0 since phase is not known.
1688 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001689 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001690 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001691
Dominik Laskowski83b88212018-12-11 13:34:06 -08001692 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001693
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001694 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001695 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001696}
1697
Mathias Agopian4fec8732012-06-29 14:12:52 -07001698void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001699 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001700 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001701 case MessageQueue::INVALIDATE: {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001702 if (!updateSetActiveConfigStateMachine()) {
1703 break;
1704 }
1705
Ana Krulec3084c052018-11-21 20:27:17 +01001706 if (mUseScheduler) {
1707 // This call is made each time SF wakes up and creates a new frame.
1708 mScheduler->incrementFrameCounter();
1709 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001710 bool frameMissed = !mHadClientComposition && mPreviousPresentFence != Fence::NO_FENCE &&
1711 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001712 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001713 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001714 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001715 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001716 if (mPropagateBackpressure) {
1717 signalLayerUpdate();
1718 break;
1719 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001720 }
Dan Stoza50182882016-07-08 12:02:20 -07001721
Steven Thomas050b2c82017-03-06 11:45:16 -08001722 // Now that we're going to make it to the handleMessageTransaction()
1723 // call below it's safe to call updateVrFlinger(), which will
1724 // potentially trigger a display handoff.
1725 updateVrFlinger();
1726
Dan Stoza6b9454d2014-11-07 16:00:59 -08001727 bool refreshNeeded = handleMessageTransaction();
1728 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001729
1730 updateCursorAsync();
1731 updateInputFlinger();
1732
Dan Stoza58784442014-12-02 16:58:17 -08001733 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001734 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001735 // Signal a refresh if a transaction modified the window state,
1736 // a new buffer was latched, or if HWC has requested a full
1737 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001738 signalRefresh();
1739 }
1740 break;
1741 }
1742 case MessageQueue::REFRESH: {
1743 handleMessageRefresh();
1744 break;
1745 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001746 }
1747}
1748
Dan Stoza6b9454d2014-11-07 16:00:59 -08001749bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001750 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001751
1752 // Apply any ready transactions in the queues if there are still transactions that have not been
1753 // applied, wake up during the next vsync period and check again
1754 bool transactionNeeded = false;
1755 if (!flushTransactionQueues()) {
1756 transactionNeeded = true;
1757 }
1758
Mathias Agopian4fec8732012-06-29 14:12:52 -07001759 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001760 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001761 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001762
1763 if (transactionNeeded) {
1764 setTransactionFlags(eTransactionNeeded);
1765 }
1766
1767 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001768}
1769
Mathias Agopian4fec8732012-06-29 14:12:52 -07001770void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001771 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001772
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001773 mRefreshPending = false;
1774
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001775 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001776 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001777 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001778 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001779 for (const auto& [token, display] : mDisplays) {
1780 beginFrame(display);
1781 prepareFrame(display);
1782 doDebugFlashRegions(display, repaintEverything);
1783 doComposition(display, repaintEverything);
1784 }
1785
Adrian Roos1e1a1282017-11-01 19:05:31 +01001786 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001787 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001788
1789 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001790 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001791
Dan Stozabfbffeb2016-07-21 14:49:33 -07001792 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001793 for (const auto& [token, displayDevice] : mDisplays) {
1794 auto display = displayDevice->getCompositionDisplay();
1795 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001796 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001797 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001798 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001799
Alec Mouri86770e52018-09-24 22:40:58 +00001800 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001801 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001802 if (mHadClientComposition) {
1803 base::unique_fd flushFence(getRenderEngine().flush());
1804 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1805 getBE().flushFence = new Fence(std::move(flushFence));
1806 } else {
1807 // Cleanup for hygiene.
1808 getBE().flushFence = Fence::NO_FENCE;
1809 }
1810 }
1811
Jorim Jaggi90535212018-05-23 23:44:06 +02001812 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001813
David Sodman7e4ae112018-02-09 15:02:28 -08001814 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001815 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001816 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001817 compositionInfo.hwc.hwcLayer = nullptr;
1818 }
David Sodmanba340492018-08-05 21:51:33 -07001819 }
David Sodman7e4ae112018-02-09 15:02:28 -08001820
1821 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001822}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001823
David Sodmanfa9b2af2017-12-24 13:28:59 -08001824
1825bool SurfaceFlinger::handleMessageInvalidate() {
1826 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001827 bool refreshNeeded = handlePageFlip();
1828
1829 for (auto& layer : mLayersPendingRefresh) {
1830 Region visibleReg;
1831 visibleReg.set(layer->computeScreenBounds());
1832 invalidateLayerStack(layer, visibleReg);
1833 }
1834 mLayersPendingRefresh.clear();
1835 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001836}
1837
David Sodman79bba0e2018-08-05 18:07:49 -07001838void SurfaceFlinger::calculateWorkingSet() {
1839 ATRACE_CALL();
1840 ALOGV(__FUNCTION__);
1841
David Sodman79bba0e2018-08-05 18:07:49 -07001842 // build the h/w work list
1843 if (CC_UNLIKELY(mGeometryInvalid)) {
1844 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001845 for (const auto& [token, displayDevice] : mDisplays) {
1846 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001847 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001848 if (!displayId) {
1849 continue;
1850 }
David Sodman79bba0e2018-08-05 18:07:49 -07001851
Lloyd Pique32cbe282018-10-19 13:09:22 -07001852 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001853 for (size_t i = 0; i < currentLayers.size(); i++) {
1854 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001855
Dominik Laskowski075d3172018-05-24 15:50:06 -07001856 if (!layer->hasHwcLayer(*displayId)) {
1857 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1858 layer->forceClientComposition(*displayId);
1859 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001860 }
1861 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001862
Lloyd Pique32cbe282018-10-19 13:09:22 -07001863 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001864 if (mDebugDisableHWC || mDebugRegion) {
1865 layer->forceClientComposition(*displayId);
1866 }
David Sodman79bba0e2018-08-05 18:07:49 -07001867 }
1868 }
1869 }
1870
1871 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001872 for (const auto& [token, displayDevice] : mDisplays) {
1873 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001874 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001875 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001876 continue;
1877 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001878 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001879
1880 if (mDrawingState.colorMatrixChanged) {
1881 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001882 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001883 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001884 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001885 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001886 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1887 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001888 !profile->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001889 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001890 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1891 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001892 !profile->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001893 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001894 }
1895
Peiyong Lind3788632018-09-18 16:01:31 -07001896 // TODO(b/111562338) remove when composer 2.3 is shipped.
1897 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001898 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001899 }
1900
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001901 if (layer->getRoundedCornerState().radius > 0.0f) {
1902 layer->forceClientComposition(*displayId);
1903 }
1904
Dominik Laskowski075d3172018-05-24 15:50:06 -07001905 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001906 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001907 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001908 continue;
1909 }
1910
Lloyd Pique32cbe282018-10-19 13:09:22 -07001911 const auto& displayState = display->getState();
1912 layer->setPerFrameData(*displayId, displayState.transform, displayState.viewport,
1913 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001914 }
1915
Peiyong Lin13effd12018-07-24 17:01:47 -07001916 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001917 ColorMode colorMode;
1918 Dataspace dataSpace;
1919 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001920 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001921 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001922 }
1923 }
1924
1925 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001926
1927 for (const auto& [token, display] : mDisplays) {
1928 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001929 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001930 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001931
1932 if (displayId) {
1933 if (!layer->setHwcLayer(*displayId)) {
1934 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1935 }
1936 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001937 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001938
Dominik Laskowski05275f12018-11-01 15:03:24 -07001939 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001940 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1941 }
1942 }
David Sodman79bba0e2018-08-05 18:07:49 -07001943}
1944
Lloyd Pique32cbe282018-10-19 13:09:22 -07001945void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1946 bool repaintEverything) {
1947 auto display = displayDevice->getCompositionDisplay();
1948 const auto& displayState = display->getState();
1949
Mathias Agopiancd60f992012-08-16 16:28:27 -07001950 // is debugging enabled
1951 if (CC_LIKELY(!mDebugRegion))
1952 return;
1953
Lloyd Pique32cbe282018-10-19 13:09:22 -07001954 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001955 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001956 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001957 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001958 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001959 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001960 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001961
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001962 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001963 }
1964 }
1965
Lloyd Pique32cbe282018-10-19 13:09:22 -07001966 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001967
1968 if (mDebugRegion > 1) {
1969 usleep(mDebugRegion * 1000);
1970 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001971
Lloyd Pique32cbe282018-10-19 13:09:22 -07001972 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001973}
1974
Adrian Roos1e1a1282017-11-01 19:05:31 +01001975void SurfaceFlinger::doTracing(const char* where) {
1976 ATRACE_CALL();
1977 ATRACE_NAME(where);
1978 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001979 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001980 }
1981}
1982
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001983void SurfaceFlinger::logLayerStats() {
1984 ATRACE_CALL();
1985 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001986 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001987 if (display->isPrimary()) {
1988 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001989 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001990 }
1991 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001992
1993 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001994 }
1995}
1996
David Sodman2b406362017-12-15 13:33:47 -08001997void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001998{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001999 ATRACE_CALL();
2000 ALOGV("preComposition");
2001
David Sodman2b406362017-12-15 13:33:47 -08002002 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
2003
Mathias Agopiancd60f992012-08-16 16:28:27 -07002004 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08002005 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08002006 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002007 needExtraInvalidate = true;
2008 }
Robert Carr2047fae2016-11-28 14:09:09 -08002009 });
2010
Mathias Agopiancd60f992012-08-16 16:28:27 -07002011 if (needExtraInvalidate) {
2012 signalLayerUpdate();
2013 }
2014}
2015
Ana Krulece588e312018-09-18 12:32:24 -07002016void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2017 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002018 // Update queue of past composite+present times and determine the
2019 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002020 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002021 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002022 while (!getBE().mCompositePresentTimes.empty()) {
2023 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002024 // Cached values should have been updated before calling this method,
2025 // which helps avoid duplicate syscalls.
2026 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2027 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2028 break;
2029 }
2030 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002031 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002032 }
2033
2034 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002035 while (getBE().mCompositePresentTimes.size() > 16) {
2036 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002037 }
2038
Ana Krulece588e312018-09-18 12:32:24 -07002039 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002040}
2041
Ana Krulece588e312018-09-18 12:32:24 -07002042void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2043 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002044 // Integer division and modulo round toward 0 not -inf, so we need to
2045 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08002046 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
2047 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
2048 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002049
Ana Krulec757f63a2019-01-25 10:46:18 -08002050 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002051 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002052 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002053 }
2054
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002055 // Snap the latency to a value that removes scheduling jitter from the
2056 // composition and present times, which often have >1ms of jitter.
2057 // Reducing jitter is important if an app attempts to extrapolate
2058 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08002059 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002060 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002061 nsecs_t bias = stats.vsyncPeriod / 2;
2062 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2063 nsecs_t snappedCompositeToPresentLatency =
2064 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002065
David Sodman99974d22017-11-28 12:04:33 -08002066 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002067 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2068 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002069 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002070}
2071
Ady Abraham8164d482019-01-11 14:47:59 -08002072// debug patch for b/119477596 - add stack guards to catch stack
2073// corruptions and disable clang optimizations.
2074// The code below is temporary and planned to be removed once stack
2075// corruptions are found.
2076#pragma clang optimize off
2077class StackGuard {
2078public:
2079 StackGuard(const char* name, const char* func, int line) {
2080 guarders.reserve(MIN_CAPACITY);
2081 guarders.push_back({this, name, func, line});
2082 validate();
2083 }
2084 ~StackGuard() {
2085 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
2086 if (i->guard == this) {
2087 guarders.erase(i);
2088 break;
2089 }
2090 }
2091 }
2092
2093 static void validate() {
2094 for (const auto& guard : guarders) {
2095 if (guard.guard->cookie != COOKIE_VALUE) {
2096 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
2097 CallStack stack(LOG_TAG);
2098 abort();
2099 }
2100 }
2101 }
2102
2103private:
2104 uint64_t cookie = COOKIE_VALUE;
2105 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
2106 static constexpr size_t MIN_CAPACITY = 16;
2107
2108 struct GuarderElement {
2109 StackGuard* guard;
2110 const char* name;
2111 const char* func;
2112 int line;
2113 };
2114
2115 static std::vector<GuarderElement> guarders;
2116};
2117std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2118
2119#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2120
2121#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002122void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002123{
Ady Abraham8164d482019-01-11 14:47:59 -08002124 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002125 ATRACE_CALL();
2126 ALOGV("postComposition");
2127
Brian Anderson3546a3f2016-07-14 11:51:14 -07002128 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002129 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002130 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002131 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002132 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002133 }
Ady Abraham8164d482019-01-11 14:47:59 -08002134 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002135
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002136 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002137 const auto displayDevice = getDefaultDisplayDeviceLocked();
2138 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002139
David Sodman73beded2017-11-15 11:56:06 -08002140 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002141 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002142 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2143
Lloyd Pique32cbe282018-10-19 13:09:22 -07002144 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002145 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002146 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2147 ->getRenderSurface()
2148 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002149 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002150 } else {
2151 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2152 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002153
Ady Abraham8164d482019-01-11 14:47:59 -08002154 ASSERT_ON_STACK_GUARD();
2155
David Sodman73beded2017-11-15 11:56:06 -08002156 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002157 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2158 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002159 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002160 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002161 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002162
Ana Krulece588e312018-09-18 12:32:24 -07002163 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002164 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002165 if (mUseScheduler) {
2166 mScheduler->getDisplayStatInfo(&stats);
2167 } else {
2168 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2169 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2170 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002171
Ady Abraham8164d482019-01-11 14:47:59 -08002172 ASSERT_ON_STACK_GUARD();
2173
David Sodman2b406362017-12-15 13:33:47 -08002174 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002175 // when we started doing work for this frame, but that should be okay
2176 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002177 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002178 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002179 DEFINE_STACK_GUARD(compositorTiming);
2180
Brian Andersond0010582017-03-07 13:20:31 -08002181 {
David Sodman99974d22017-11-28 12:04:33 -08002182 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002183 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002184 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002185
2186 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002187 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002188
Robert Carr2047fae2016-11-28 14:09:09 -08002189 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002190 bool frameLatched =
2191 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2192 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002193 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002194 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002195 recordBufferingStats(layer->getName().string(),
2196 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002197 }
Ady Abraham8164d482019-01-11 14:47:59 -08002198 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002199 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002200
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002201 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002202 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002203 if (mUseScheduler) {
2204 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002205 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002206 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002207 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2208 enableHardwareVsync();
2209 } else {
2210 disableHardwareVsync(false);
2211 }
Ady Abraham8164d482019-01-11 14:47:59 -08002212 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002213 }
2214 }
2215
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002216 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002217 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2218 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002219 if (mUseScheduler) {
2220 mScheduler->enableHardwareVsync();
2221 } else {
2222 enableHardwareVsync();
2223 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002224 }
2225 }
2226
Ady Abraham8164d482019-01-11 14:47:59 -08002227 ASSERT_ON_STACK_GUARD();
2228
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002229 if (mAnimCompositionPending) {
2230 mAnimCompositionPending = false;
2231
Brian Anderson4e606e32017-03-16 15:34:57 -07002232 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002233 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002234 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002235
2236 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002237 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002238 // The HWC doesn't support present fences, so use the refresh
2239 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002240 const nsecs_t presentTime =
2241 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002242 DEFINE_STACK_GUARD(presentTime);
2243
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002244 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002245 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002246 }
2247 mAnimFrameTracker.advanceFrame();
2248 }
Dan Stozab90cf072015-03-05 11:05:59 -08002249
Ady Abraham8164d482019-01-11 14:47:59 -08002250 ASSERT_ON_STACK_GUARD();
2251
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002252 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002253 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002254 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002255 }
2256
Ady Abraham8164d482019-01-11 14:47:59 -08002257 ASSERT_ON_STACK_GUARD();
2258
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002259 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002260
Ady Abraham8164d482019-01-11 14:47:59 -08002261 ASSERT_ON_STACK_GUARD();
2262
Lloyd Pique32cbe282018-10-19 13:09:22 -07002263 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2264 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002265 return;
2266 }
2267
2268 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002269 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002270 if (mHasPoweredOff) {
2271 mHasPoweredOff = false;
2272 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002273 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002274 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002275 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002276 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002277 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2278 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002279 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002280 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002281 }
David Sodman4a36e932017-11-07 14:29:47 -08002282 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002283
2284 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002285 }
David Sodman4a36e932017-11-07 14:29:47 -08002286 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002287 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002288
2289 {
2290 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002291 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002292 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002293 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002294 if (refillCount > 0) {
2295 const size_t offset = mTexturePool.size();
2296 mTexturePool.resize(mTexturePoolSize);
2297 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2298 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2299 }
Ady Abraham8164d482019-01-11 14:47:59 -08002300 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002301 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002302
Marissa Wallfda30bb2018-10-12 11:34:28 -07002303 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002304 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002305
2306 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002307}
Ady Abraham8164d482019-01-11 14:47:59 -08002308#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002309
2310void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002311 ATRACE_CALL();
2312 ALOGV("rebuildLayerStacks");
2313
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002314 // We need to clear these out now as these may be holding on to a
2315 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2316 // also holds a reference. When the set of visible layers is recomputed,
2317 // some layers may be destroyed if the only thing keeping them alive was
2318 // that list of visible layers associated with each display. The layer
2319 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2320 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2321 for (const auto& [token, display] : mDisplays) {
2322 getBE().mCompositionInfo[token].clear();
2323 }
2324
Mathias Agopiancd60f992012-08-16 16:28:27 -07002325 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002326 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002327 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002328 mVisibleRegionsDirty = false;
2329 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002330
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002331 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002332 const auto& displayDevice = pair.second;
2333 auto display = displayDevice->getCompositionDisplay();
2334 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002335 Region opaqueRegion;
2336 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002337 compositionengine::Output::OutputLayers layersSortedByZ;
2338 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002339 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002340 const ui::Transform& tr = displayState.transform;
2341 const Rect bounds = displayState.bounds;
2342 if (displayState.isEnabled) {
2343 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002344
Jeff Sharkey76488112017-02-27 14:15:18 -07002345 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002346 auto compositionLayer = layer->getCompositionLayer();
2347 if (compositionLayer == nullptr) {
2348 return;
2349 }
2350
Chia-I Wu83806892017-11-16 10:50:20 -08002351 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002352 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002353 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2354 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2355
Lloyd Piqueef36b002019-01-23 17:52:04 -08002356 if (display->belongsInOutput(layer->getLayerStack(),
2357 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002358 Region drawRegion(tr.transform(
2359 layer->visibleNonTransparentRegion));
2360 drawRegion.andSelf(bounds);
2361 if (!drawRegion.isEmpty()) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002362 layersSortedByZ.emplace_back(
2363 display->getOrCreateOutputLayer(layer->getCompositionLayer(),
2364 layerFE));
2365
2366 deprecated_layersSortedByZ.add(layer);
Jeff Sharkey76488112017-02-27 14:15:18 -07002367 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002368 // Clear out the HWC layer if this layer was
2369 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002370 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002371 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002372 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002373 // WM changes display->layerStack upon sleep/awake.
2374 // Here we make sure we delete the HWC layers even if
2375 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002376 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002377 }
2378
2379 // If a layer is not going to get a release fence because
2380 // it is invisible, but it is also going to release its
2381 // old buffer, add it to the list of layers needing
2382 // fences.
2383 if (hwcLayerDestroyed) {
2384 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2385 mLayersWithQueuedFrames.cend(), layer);
2386 if (found != mLayersWithQueuedFrames.cend()) {
2387 layersNeedingFences.add(layer);
2388 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002389 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002390 });
2391 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002392
2393 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2394
2395 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002396 displayDevice->setLayersNeedingFences(layersNeedingFences);
2397
2398 Region undefinedRegion{bounds};
2399 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2400
2401 display->editState().undefinedRegion = undefinedRegion;
2402 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002403 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002404 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002405}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002406
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002407// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002408// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002409// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002410// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002411// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002412// The returned HDR data space is one of
2413// - Dataspace::UNKNOWN
2414// - Dataspace::BT2020_HLG
2415// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002416Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2417 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002418 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002419 *outHdrDataSpace = Dataspace::UNKNOWN;
2420
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002421 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002422 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002423 case Dataspace::V0_SCRGB:
2424 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002425 case Dataspace::BT2020:
2426 case Dataspace::BT2020_ITU:
2427 case Dataspace::BT2020_LINEAR:
2428 case Dataspace::DISPLAY_BT2020:
2429 bestDataSpace = Dataspace::DISPLAY_BT2020;
2430 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002431 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002432 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002433 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002434 case Dataspace::BT2020_PQ:
2435 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002436 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002437 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002438 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002439 case Dataspace::BT2020_HLG:
2440 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002441 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002442 // When there's mixed PQ content and HLG content, we set the HDR
2443 // data space to be BT2020_PQ and convert HLG to PQ.
2444 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2445 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002446 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002447 break;
2448 default:
2449 break;
2450 }
Romain Guy54f154a2017-10-24 21:40:32 +01002451 }
2452
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002453 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002454}
2455
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002456// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002457void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2458 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002459 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2460 *outMode = ColorMode::NATIVE;
2461 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002462 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002463 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002464 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002465
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002466 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002467 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002468
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002469 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2470
Peiyong Lindfde5112018-06-05 10:58:41 -07002471 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002472 const bool isHdr =
2473 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002474 if (isHdr) {
2475 bestDataSpace = hdrDataSpace;
2476 }
2477
Chia-I Wu0d711262018-05-21 15:19:35 -07002478 RenderIntent intent;
2479 switch (mDisplayColorSetting) {
2480 case DisplayColorSetting::MANAGED:
2481 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002482 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002483 break;
2484 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002485 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002486 break;
2487 default: // vendor display color setting
2488 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2489 break;
2490 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002491
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002492 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002493}
2494
Lloyd Pique32cbe282018-10-19 13:09:22 -07002495void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2496 auto display = displayDevice->getCompositionDisplay();
2497 const auto& displayState = display->getState();
2498
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002499 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002500 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2501 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002502
David Sodmanfa9b2af2017-12-24 13:28:59 -08002503 // If nothing has changed (!dirty), don't recompose.
2504 // If something changed, but we don't currently have any visible layers,
2505 // and didn't when we last did a composition, then skip it this time.
2506 // The second rule does two things:
2507 // - When all layers are removed from a display, we'll emit one black
2508 // frame, then nothing more until we get new layers.
2509 // - When a display is created with a private layer stack, we won't
2510 // emit any black frames until a layer is added to the layer stack.
2511 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002512
Dominik Laskowski075d3172018-05-24 15:50:06 -07002513 const char flagPrefix[] = {'-', '+'};
2514 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002515 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2516 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2517 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2518 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002519
Lloyd Pique31cb2942018-10-19 17:23:03 -07002520 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002521
David Sodmanfa9b2af2017-12-24 13:28:59 -08002522 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002523 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002524 }
2525}
2526
Lloyd Pique32cbe282018-10-19 13:09:22 -07002527void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2528 auto display = displayDevice->getCompositionDisplay();
2529 const auto& displayState = display->getState();
2530
2531 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002532 return;
David Sodman2b406362017-12-15 13:33:47 -08002533 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002534
Lloyd Pique31cb2942018-10-19 17:23:03 -07002535 status_t result = display->getRenderSurface()->prepareFrame(
2536 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002537 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002538 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002539}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002540
Lloyd Pique32cbe282018-10-19 13:09:22 -07002541void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002542 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002543 ALOGV("doComposition");
2544
Lloyd Pique32cbe282018-10-19 13:09:22 -07002545 auto display = displayDevice->getCompositionDisplay();
2546 const auto& displayState = display->getState();
2547
2548 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002549 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002550 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002551
David Sodmanfa9b2af2017-12-24 13:28:59 -08002552 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002553 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002554
Lloyd Pique32cbe282018-10-19 13:09:22 -07002555 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002556 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002557 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002558 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002559}
2560
David Sodmanfa9b2af2017-12-24 13:28:59 -08002561void SurfaceFlinger::postFrame()
2562{
2563 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002564 const auto display = getDefaultDisplayDeviceLocked();
2565 if (display && getHwComposer().isConnected(*display->getId())) {
2566 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002567 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2568 logFrameStats();
2569 }
2570 }
2571}
2572
Lloyd Pique32cbe282018-10-19 13:09:22 -07002573void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002574 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002575 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002576
Lloyd Pique32cbe282018-10-19 13:09:22 -07002577 auto display = displayDevice->getCompositionDisplay();
2578 const auto& displayState = display->getState();
2579 const auto displayId = display->getId();
2580
David Sodmanfa9b2af2017-12-24 13:28:59 -08002581 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002582
Lloyd Pique32cbe282018-10-19 13:09:22 -07002583 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002584 if (displayId) {
2585 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002586 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002587 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002588 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002589 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002590
Chia-I Wu7b549592017-11-15 09:14:57 -08002591 // The layer buffer from the previous frame (if any) is released
2592 // by HWC only when the release fence from this frame (if any) is
2593 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002594 if (displayId && layer->hasHwcLayer(*displayId)) {
2595 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2596 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002597 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002598
2599 // If the layer was client composited in the previous frame, we
2600 // need to merge with the previous client target acquire fence.
2601 // Since we do not track that, always merge with the current
2602 // client target acquire fence when it is available, even though
2603 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002604 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002605 releaseFence =
2606 Fence::merge("LayerRelease", releaseFence,
2607 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002608 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002609
David Sodman15094112018-10-11 09:39:37 -07002610 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002611 }
Chia-I Wu83806892017-11-16 10:50:20 -08002612
2613 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002614 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002615 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002616 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002617 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002618 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002619 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002620 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002621 }
2622 }
2623
Dominik Laskowski075d3172018-05-24 15:50:06 -07002624 if (displayId) {
2625 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002626 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002627 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002628}
2629
Mathias Agopian87baae12012-07-31 12:38:26 -07002630void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002631{
Mathias Agopian841cde52012-03-01 15:44:37 -08002632 ATRACE_CALL();
2633
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002634 // here we keep a copy of the drawing state (that is the state that's
2635 // going to be overwritten by handleTransactionLocked()) outside of
2636 // mStateLock so that the side-effects of the State assignment
2637 // don't happen with mStateLock held (which can cause deadlocks).
2638 State drawingState(mDrawingState);
2639
Mathias Agopianca4d3602011-05-19 15:38:14 -07002640 Mutex::Autolock _l(mStateLock);
2641 const nsecs_t now = systemTime();
2642 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002643
Mathias Agopianca4d3602011-05-19 15:38:14 -07002644 // Here we're guaranteed that some transaction flags are set
2645 // so we can call handleTransactionLocked() unconditionally.
2646 // We call getTransactionFlags(), which will also clear the flags,
2647 // with mStateLock held to guarantee that mCurrentState won't change
2648 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002649
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002650 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002651 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002652 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002653
Mathias Agopianca4d3602011-05-19 15:38:14 -07002654 mLastTransactionTime = systemTime() - now;
2655 mDebugInTransaction = 0;
2656 invalidateHwcGeometry();
2657 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002658}
2659
Lloyd Piqueba04e622017-12-14 17:11:26 -08002660void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2661 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002662 const std::optional<DisplayIdentificationInfo> info =
2663 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002664
Dominik Laskowski075d3172018-05-24 15:50:06 -07002665 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002666 continue;
2667 }
2668
Lloyd Piqueba04e622017-12-14 17:11:26 -08002669 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002670 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002671 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002672 mPhysicalDisplayTokens[info->id] = new BBinder();
2673 DisplayDeviceState state;
2674 state.displayId = info->id;
2675 state.isSecure = true; // All physical displays are currently considered secure.
2676 state.displayName = info->name;
2677 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2678 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002679 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002680 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002681 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002682
Dominik Laskowski075d3172018-05-24 15:50:06 -07002683 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2684 if (index >= 0) {
2685 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2686 mInterceptor->saveDisplayDeletion(state.sequenceId);
2687 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002688 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002689 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002690 }
2691
2692 processDisplayChangesLocked();
2693 }
2694
2695 mPendingHotplugEvents.clear();
2696}
2697
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002698void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002699 if (mUseScheduler) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002700 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2701 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002702 } else {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002703 mEventThread->onHotplugReceived(displayId, connected);
2704 mSFEventThread->onHotplugReceived(displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002705 }
2706}
2707
Lloyd Pique99d3da52018-01-22 17:48:03 -08002708sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002709 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002710 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002711 const sp<IGraphicBufferProducer>& producer) {
2712 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002713 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002714 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002715 creationArgs.isSecure = state.isSecure;
2716 creationArgs.displaySurface = dispSurface;
2717 creationArgs.hasWideColorGamut = false;
2718 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002719
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002720 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002721 creationArgs.isPrimary = isInternalDisplay;
2722
2723 if (useColorManagement && displayId) {
2724 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002725 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002726 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002727 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002728 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002729
Dominik Laskowski7e045462018-05-30 13:02:02 -07002730 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002731 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002732 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002733 }
tangrobin6753a022018-08-10 10:58:54 +08002734 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002735
Dominik Laskowski075d3172018-05-24 15:50:06 -07002736 if (displayId) {
2737 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002738 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002739 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002740 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002741
Lloyd Pique90c115d2018-09-18 21:39:42 -07002742 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002743 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002744 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002745
Lloyd Pique99d3da52018-01-22 17:48:03 -08002746 // Make sure that composition can never be stalled by a virtual display
2747 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002748 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002749 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002750 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2751 }
2752
Dominik Laskowski075d3172018-05-24 15:50:06 -07002753 creationArgs.displayInstallOrientation =
2754 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002755
Lloyd Pique99d3da52018-01-22 17:48:03 -08002756 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002757 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002758
Lloyd Pique90c115d2018-09-18 21:39:42 -07002759 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002760
2761 if (maxFrameBufferAcquiredBuffers >= 3) {
2762 nativeWindowSurface->preallocateBuffers();
2763 }
2764
2765 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002766 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002767 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002768 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002769 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002770 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002771 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2772 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002773 if (!state.isVirtual()) {
2774 LOG_ALWAYS_FATAL_IF(!displayId);
2775 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002776 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002777
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002778 display->setLayerStack(state.layerStack);
2779 display->setProjection(state.orientation, state.viewport, state.frame);
2780 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002781
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002782 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002783}
2784
Lloyd Pique347200f2017-12-14 17:00:15 -08002785void SurfaceFlinger::processDisplayChangesLocked() {
2786 // here we take advantage of Vector's copy-on-write semantics to
2787 // improve performance by skipping the transaction entirely when
2788 // know that the lists are identical
2789 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2790 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2791 if (!curr.isIdenticalTo(draw)) {
2792 mVisibleRegionsDirty = true;
2793 const size_t cc = curr.size();
2794 size_t dc = draw.size();
2795
2796 // find the displays that were removed
2797 // (ie: in drawing state but not in current state)
2798 // also handle displays that changed
2799 // (ie: displays that are in both lists)
2800 for (size_t i = 0; i < dc;) {
2801 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2802 if (j < 0) {
2803 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002804 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002805 // Save display ID before disconnecting.
2806 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002807 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002808
2809 if (!display->isVirtual()) {
2810 LOG_ALWAYS_FATAL_IF(!displayId);
2811 dispatchDisplayHotplugEvent(displayId->value, false);
2812 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002813 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002814
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002815 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002816 } else {
2817 // this display is in both lists. see if something changed.
2818 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002819 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002820 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2821 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2822 if (state_binder != draw_binder) {
2823 // changing the surface is like destroying and
2824 // recreating the DisplayDevice, so we just remove it
2825 // from the drawing state, so that it get re-added
2826 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002827 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002828 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002829 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002830 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002831 mDrawingState.displays.removeItemsAt(i);
2832 dc--;
2833 // at this point we must loop to the next item
2834 continue;
2835 }
2836
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002837 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002838 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002839 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002840 }
2841 if ((state.orientation != draw[i].orientation) ||
2842 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002843 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002844 }
2845 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002846 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002847 }
2848 }
2849 }
2850 ++i;
2851 }
2852
2853 // find displays that were added
2854 // (ie: in current state but not in drawing state)
2855 for (size_t i = 0; i < cc; i++) {
2856 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2857 const DisplayDeviceState& state(curr[i]);
2858
Lloyd Pique542307f2018-10-19 13:24:08 -07002859 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002860 sp<IGraphicBufferProducer> producer;
2861 sp<IGraphicBufferProducer> bqProducer;
2862 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002863 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002864
Dominik Laskowski075d3172018-05-24 15:50:06 -07002865 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002866 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002867 // Virtual displays without a surface are dormant:
2868 // they have external state (layer stack, projection,
2869 // etc.) but no internal state (i.e. a DisplayDevice).
2870 if (state.surface != nullptr) {
2871 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002872 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002873 int width = 0;
2874 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2875 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2876 int height = 0;
2877 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2878 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2879 int intFormat = 0;
2880 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2881 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002882 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002883
Dominik Laskowski075d3172018-05-24 15:50:06 -07002884 displayId =
2885 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002886 }
2887
2888 // TODO: Plumb requested format back up to consumer
2889
2890 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002891 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002892 bqProducer, bqConsumer,
2893 state.displayName);
2894
2895 dispSurface = vds;
2896 producer = vds;
2897 }
2898 } else {
2899 ALOGE_IF(state.surface != nullptr,
2900 "adding a supported display, but rendering "
2901 "surface is provided (%p), ignoring it",
2902 state.surface.get());
2903
Dominik Laskowski075d3172018-05-24 15:50:06 -07002904 displayId = state.displayId;
2905 LOG_ALWAYS_FATAL_IF(!displayId);
2906 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002907 producer = bqProducer;
2908 }
2909
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002910 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002911 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002912 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002913 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002914 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002915 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002916 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002917 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002918 }
2919 }
2920 }
2921 }
2922 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002923
2924 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002925}
2926
Mathias Agopian87baae12012-07-31 12:38:26 -07002927void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002928{
Dan Stoza7dde5992015-05-22 09:51:44 -07002929 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002930 mCurrentState.traverseInZOrder([](Layer* layer) {
2931 layer->notifyAvailableFrames();
2932 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002933
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002934 /*
2935 * Traversal of the children
2936 * (perform the transaction for each of them if needed)
2937 */
2938
Mathias Agopian3559b072012-08-15 13:46:03 -07002939 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002940 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002941 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002942 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002943
2944 const uint32_t flags = layer->doTransaction(0);
2945 if (flags & Layer::eVisibleRegion)
2946 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002947
2948 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002949 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002950 }
Robert Carr2047fae2016-11-28 14:09:09 -08002951 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002952 }
2953
2954 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002955 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002956 */
2957
Mathias Agopiane57f2922012-08-09 16:29:12 -07002958 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002959 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002960 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002961 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002962
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002963 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002964 // The transform hint might have changed for some layers
2965 // (either because a display has changed, or because a layer
2966 // as changed).
2967 //
2968 // Walk through all the layers in currentLayers,
2969 // and update their transform hint.
2970 //
2971 // If a layer is visible only on a single display, then that
2972 // display is used to calculate the hint, otherwise we use the
2973 // default display.
2974 //
2975 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2976 // the hint is set before we acquire a buffer from the surface texture.
2977 //
2978 // NOTE: layer transactions have taken place already, so we use their
2979 // drawing state. However, SurfaceFlinger's own transaction has not
2980 // happened yet, so we must use the current state layer list
2981 // (soon to become the drawing state list).
2982 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002983 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002984 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002985 bool first = true;
2986 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002987 // NOTE: we rely on the fact that layers are sorted by
2988 // layerStack first (so we don't have to traverse the list
2989 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002990 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002991 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002992 currentlayerStack = layerStack;
2993 // figure out if this layerstack is mirrored
2994 // (more than one display) if so, pick the default display,
2995 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002996 hintDisplay = nullptr;
2997 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002998 if (display->getCompositionDisplay()
2999 ->belongsInOutput(layer->getLayerStack(),
3000 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003001 if (hintDisplay) {
3002 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08003003 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003004 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003005 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08003006 }
3007 }
3008 }
3009 }
Chet Haase91d25932013-04-11 15:24:55 -07003010
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003011 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003012 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
3013 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08003014
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003015 // could be null when this layer is using a layerStack
3016 // that is not visible on any display. Also can occur at
3017 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003018 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08003019 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003020
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003021 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003022 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003023 if (hintDisplay) {
3024 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08003025 }
Robert Carr2047fae2016-11-28 14:09:09 -08003026
3027 first = false;
3028 });
Mathias Agopian84300952012-11-21 16:02:13 -08003029 }
3030
3031
Mathias Agopian3559b072012-08-15 13:46:03 -07003032 /*
3033 * Perform our own transaction if needed
3034 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07003035
3036 if (mLayersAdded) {
3037 mLayersAdded = false;
3038 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07003039 mVisibleRegionsDirty = true;
3040 }
3041
3042 // some layers might have been removed, so
3043 // we need to update the regions they're exposing.
3044 if (mLayersRemoved) {
3045 mLayersRemoved = false;
3046 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08003047 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003048 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07003049 // this layer is not visible anymore
3050 // TODO: we could traverse the tree from front to back and
3051 // compute the actual visible region
3052 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003053 Region visibleReg;
3054 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07003055 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07003056 }
Robert Carr2047fae2016-11-28 14:09:09 -08003057 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003058 }
3059
3060 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07003061}
3062
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003063void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003064 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003065 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08003066 return;
3067 }
3068
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003069 if (mVisibleRegionsDirty || mInputInfoChanged) {
3070 mInputInfoChanged = false;
3071 updateInputWindowInfo();
3072 }
3073
3074 executeInputWindowCommands();
3075}
3076
3077void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07003078 Vector<InputWindowInfo> inputHandles;
3079
3080 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
3081 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08003082 // When calculating the screen bounds we ignore the transparent region since it may
3083 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08003084 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07003085 }
3086 });
3087 mInputFlinger->setInputWindows(inputHandles);
3088}
3089
chaviwfbe5d9c2018-12-26 12:23:37 -08003090void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08003091 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3092 if (transferTouchFocusCommand.fromToken != nullptr &&
3093 transferTouchFocusCommand.toToken != nullptr &&
3094 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3095 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3096 transferTouchFocusCommand.toToken);
3097 }
3098 }
3099
3100 mInputWindowCommands.clear();
3101}
3102
Riley Andrews03414a12014-07-01 14:22:59 -07003103void SurfaceFlinger::updateCursorAsync()
3104{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003105 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003106 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003107 continue;
3108 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003109
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003110 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3111 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003112 }
3113 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003114}
3115
chaviw61626f22018-11-15 16:26:27 -08003116void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3117 if (layer->hasReadyFrame()) {
Ady Abrahamc3e21312019-02-07 14:30:23 -08003118 nsecs_t expectedPresentTime;
3119 if (mUseScheduler) {
3120 expectedPresentTime = mScheduler->expectedPresentTime();
3121 } else {
3122 expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3123 }
chaviw61626f22018-11-15 16:26:27 -08003124 if (layer->shouldPresentNow(expectedPresentTime)) {
3125 bool ignored = false;
3126 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3127 }
3128 }
3129 layer->releasePendingBuffer(systemTime());
3130}
3131
Mathias Agopian4fec8732012-06-29 14:12:52 -07003132void SurfaceFlinger::commitTransaction()
3133{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003134 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003135 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003136 for (const auto& l : mLayersPendingRemoval) {
3137 recordBufferingStats(l->getName().string(),
3138 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003139
3140 // We need to release the HWC layers when the Layer is removed
3141 // from the current state otherwise the HWC layer just continues
3142 // showing at its last configured state until we eventually
3143 // abandon the buffer queue.
3144 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003145 l->destroyHwcLayersForAllDisplays();
3146 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003147 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003148 }
3149 mLayersPendingRemoval.clear();
3150 }
3151
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003152 // If this transaction is part of a window animation then the next frame
3153 // we composite should be considered an animation as well.
3154 mAnimCompositionPending = mAnimTransactionPending;
3155
Mathias Agopian4fec8732012-06-29 14:12:52 -07003156 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003157 // clear the "changed" flags in current state
3158 mCurrentState.colorMatrixChanged = false;
3159
Robert Carr1f0a16a2016-10-24 16:27:39 -07003160 mDrawingState.traverseInZOrder([](Layer* layer) {
3161 layer->commitChildList();
3162 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003163 mTransactionPending = false;
3164 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003165 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003166}
3167
Lloyd Pique32cbe282018-10-19 13:09:22 -07003168void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003169 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003170 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003171 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003172
Lloyd Pique32cbe282018-10-19 13:09:22 -07003173 auto display = displayDevice->getCompositionDisplay();
3174
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003175 Region aboveOpaqueLayers;
3176 Region aboveCoveredLayers;
3177 Region dirty;
3178
Mathias Agopian87baae12012-07-31 12:38:26 -07003179 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003180
Robert Carr2047fae2016-11-28 14:09:09 -08003181 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003182 // start with the whole surface at its current location
3183 const Layer::State& s(layer->getDrawingState());
3184
Jesse Hall01e29052013-02-19 16:13:35 -08003185 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003186 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003187 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003188 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003189
Mathias Agopianab028732010-03-16 16:41:46 -07003190 /*
3191 * opaqueRegion: area of a surface that is fully opaque.
3192 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003193 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003194
3195 /*
3196 * visibleRegion: area of a surface that is visible on screen
3197 * and not fully transparent. This is essentially the layer's
3198 * footprint minus the opaque regions above it.
3199 * Areas covered by a translucent surface are considered visible.
3200 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003201 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003202
3203 /*
3204 * coveredRegion: area of a surface that is covered by all
3205 * visible regions above it (which includes the translucent areas).
3206 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003207 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003208
Jesse Halla8026d22012-09-25 13:25:04 -07003209 /*
3210 * transparentRegion: area of a surface that is hinted to be completely
3211 * transparent. This is only used to tell when the layer has no visible
3212 * non-transparent regions and can be removed from the layer list. It
3213 * does not affect the visibleRegion of this layer or any layers
3214 * beneath it. The hint may not be correct if apps don't respect the
3215 * SurfaceView restrictions (which, sadly, some don't).
3216 */
3217 Region transparentRegion;
3218
Mathias Agopianab028732010-03-16 16:41:46 -07003219
3220 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003221 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003222 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003223 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003224
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003225 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003226 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003227 if (!visibleRegion.isEmpty()) {
3228 // Remove the transparent area from the visible region
3229 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003230 if (tr.preserveRects()) {
3231 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003232 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003233 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003234 // transformation too complex, can't do the
3235 // transparent region optimization.
3236 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003237 }
Mathias Agopianab028732010-03-16 16:41:46 -07003238 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003239
Mathias Agopianab028732010-03-16 16:41:46 -07003240 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003241 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003242 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003243 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003244 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003245 // the opaque region is the layer's footprint
3246 opaqueRegion = visibleRegion;
3247 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003248 }
3249 }
3250
Robert Carre5f4f692018-01-12 13:12:28 -08003251 if (visibleRegion.isEmpty()) {
3252 layer->clearVisibilityRegions();
3253 return;
3254 }
3255
Mathias Agopianab028732010-03-16 16:41:46 -07003256 // Clip the covered region to the visible region
3257 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3258
3259 // Update aboveCoveredLayers for next (lower) layer
3260 aboveCoveredLayers.orSelf(visibleRegion);
3261
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003262 // subtract the opaque region covered by the layers above us
3263 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003264
3265 // compute this layer's dirty region
3266 if (layer->contentDirty) {
3267 // we need to invalidate the whole region
3268 dirty = visibleRegion;
3269 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003270 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003271 layer->contentDirty = false;
3272 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003273 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003274 * the exposed region consists of two components:
3275 * 1) what's VISIBLE now and was COVERED before
3276 * 2) what's EXPOSED now less what was EXPOSED before
3277 *
3278 * note that (1) is conservative, we start with the whole
3279 * visible region but only keep what used to be covered by
3280 * something -- which mean it may have been exposed.
3281 *
3282 * (2) handles areas that were not covered by anything but got
3283 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003284 */
Mathias Agopianab028732010-03-16 16:41:46 -07003285 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003286 const Region oldVisibleRegion = layer->visibleRegion;
3287 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003288 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3289 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003290 }
3291 dirty.subtractSelf(aboveOpaqueLayers);
3292
3293 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003294 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003295
Mathias Agopianab028732010-03-16 16:41:46 -07003296 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003297 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003298
Jesse Halla8026d22012-09-25 13:25:04 -07003299 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003300 layer->setVisibleRegion(visibleRegion);
3301 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003302 layer->setVisibleNonTransparentRegion(
3303 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003304 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003305
Mathias Agopian87baae12012-07-31 12:38:26 -07003306 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003307}
3308
Chia-I Wuab0c3192017-08-01 11:29:00 -07003309void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003310 for (const auto& [token, displayDevice] : mDisplays) {
3311 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003312 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003313 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003314 }
3315 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003316}
3317
Daniel Solomon42d04562019-01-20 21:03:19 -08003318void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3319 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3320 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3321 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3322 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3323 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3324 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3325 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3326 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3327 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3328 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3329 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3330 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3331}
3332
Dan Stoza6b9454d2014-11-07 16:00:59 -08003333bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003334{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003335 ALOGV("handlePageFlip");
3336
Brian Andersond6927fb2016-07-23 23:37:30 -07003337 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003338
Mathias Agopian4fec8732012-06-29 14:12:52 -07003339 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003340 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003341 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003342
3343 // Store the set of layers that need updates. This set must not change as
3344 // buffers are being latched, as this could result in a deadlock.
3345 // Example: Two producers share the same command stream and:
3346 // 1.) Layer 0 is latched
3347 // 2.) Layer 0 gets a new frame
3348 // 2.) Layer 1 gets a new frame
3349 // 3.) Layer 1 is latched.
3350 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3351 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003352 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003353 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003354 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003355 nsecs_t expectedPresentTime;
3356 if (mUseScheduler) {
3357 expectedPresentTime = mScheduler->expectedPresentTime();
3358 } else {
3359 expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3360 }
Ana Krulec010d2192018-10-08 06:29:54 -07003361 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003362 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003363 } else {
3364 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003365 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003366 } else {
3367 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003368 }
Robert Carr2047fae2016-11-28 14:09:09 -08003369 });
3370
Lloyd Piquef2c79392018-12-20 16:23:33 -08003371 if (!mLayersWithQueuedFrames.empty()) {
3372 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3373 // writes to Layer current state. See also b/119481871
3374 Mutex::Autolock lock(mStateLock);
3375
3376 for (auto& layer : mLayersWithQueuedFrames) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003377 if (layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence)) {
3378 mLayersPendingRefresh.push_back(layer);
3379 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003380 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003381 if (layer->isBufferLatched()) {
3382 newDataLatched = true;
3383 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003384 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003385 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003386
Alec Mouri86770e52018-09-24 22:40:58 +00003387 // Clear the renderengine fence here...
3388 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3389 // clear instead of sp::clear.
3390 getBE().flushFence = Fence::NO_FENCE;
3391
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003392 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003393
3394 // If we will need to wake up at some time in the future to deal with a
3395 // queued frame that shouldn't be displayed during this vsync period, wake
3396 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003397 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003398 signalLayerUpdate();
3399 }
3400
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003401 // enter boot animation on first buffer latch
3402 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3403 ALOGI("Enter boot animation");
3404 mBootStage = BootStage::BOOTANIMATION;
3405 }
3406
Dan Stoza6b9454d2014-11-07 16:00:59 -08003407 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003408 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003409}
3410
Mathias Agopianad456f92011-01-13 17:53:01 -08003411void SurfaceFlinger::invalidateHwcGeometry()
3412{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003413 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003414}
3415
Lloyd Pique32cbe282018-10-19 13:09:22 -07003416void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003417 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003418 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003419 // We only need to actually compose the display if:
3420 // 1) It is being handled by hardware composer, which may need this to
3421 // keep its virtual display state machine in sync, or
3422 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003423 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003424 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003425 return;
3426 }
3427
Dan Stoza9e56aa02015-11-02 13:00:03 -08003428 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003429 base::unique_fd readyFence;
3430 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003431
3432 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003433 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003434}
3435
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003436bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3437 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003438 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003439 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003440
Lloyd Pique32cbe282018-10-19 13:09:22 -07003441 auto display = displayDevice->getCompositionDisplay();
3442 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003443 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003444
3445 const Region bounds(displayState.bounds);
3446 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003447 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003448 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003449
Peiyong Lind3788632018-09-18 16:01:31 -07003450 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003451 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003452
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003453 renderengine::DisplaySettings clientCompositionDisplay;
3454 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3455 sp<GraphicBuffer> buf;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003456
Dan Stoza9e56aa02015-11-02 13:00:03 -08003457 if (hasClientComposition) {
3458 ALOGV("hasClientComposition");
3459
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003460 buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003461
3462 if (buf == nullptr) {
3463 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3464 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003465 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003466 return false;
3467 }
3468
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003469 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3470 clientCompositionDisplay.clip = displayState.scissor;
3471 const ui::Transform& displayTransform = displayState.transform;
3472 mat4 m;
3473 m[0][0] = displayTransform[0][0];
3474 m[0][1] = displayTransform[0][1];
3475 m[0][3] = displayTransform[0][2];
3476 m[1][0] = displayTransform[1][0];
3477 m[1][1] = displayTransform[1][1];
3478 m[1][3] = displayTransform[1][2];
3479 m[3][0] = displayTransform[2][0];
3480 m[3][1] = displayTransform[2][1];
3481 m[3][3] = displayTransform[2][2];
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003482
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003483 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003484
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003485 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003486 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003487 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003488 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003489 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003490 clientCompositionDisplay.outputDataspace = outputDataspace;
3491 clientCompositionDisplay.maxLuminance =
3492 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003493
Lloyd Pique441d5042018-10-18 16:49:51 -07003494 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003495 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003496 getHwComposer()
3497 .hasDisplayCapability(displayId,
3498 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003499
Peiyong Lind3788632018-09-18 16:01:31 -07003500 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003501 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3502 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003503 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003504 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003505 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003506
Mathias Agopian85d751c2012-08-29 16:59:24 -07003507 /*
3508 * and then, render the layers targeted at the framebuffer
3509 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003510
Dan Stoza9e56aa02015-11-02 13:00:03 -08003511 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003512 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003513 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003514 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003515 const Region viewportRegion(displayState.viewport);
3516 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003517 ALOGV("Layer: %s", layer->getName().string());
3518 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003519 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003520 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003521 case HWC2::Composition::Cursor:
3522 case HWC2::Composition::Device:
3523 case HWC2::Composition::Sideband:
3524 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003525 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003526 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003527 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003528 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003529 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003530 // never clear the very first layer since we're
3531 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003532 renderengine::LayerSettings layerSettings;
3533 Region dummyRegion;
3534 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3535 layerSettings);
3536
3537 if (prepared) {
3538 layerSettings.source.buffer.buffer = nullptr;
3539 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3540 layerSettings.alpha = half(0.0);
3541 layerSettings.disableBlending = true;
3542 clientCompositionLayers.push_back(layerSettings);
3543 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003544 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003545 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003546 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003547 case HWC2::Composition::Client: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003548 renderengine::LayerSettings layerSettings;
3549 bool prepared =
3550 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3551 if (prepared) {
3552 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003553 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003554 break;
3555 }
3556 default:
3557 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003558 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003559 } else {
3560 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003561 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003562 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003563 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003564
Alec Mouri820c7402019-01-23 13:02:39 -08003565 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003566 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003567 clientCompositionDisplay.clearRegion = clearRegion;
3568 if (!debugRegion.isEmpty()) {
3569 Region::const_iterator it = debugRegion.begin();
3570 Region::const_iterator end = debugRegion.end();
3571 while (it != end) {
3572 const Rect& rect = *it++;
3573 renderengine::LayerSettings layerSettings;
3574 layerSettings.source.buffer.buffer = nullptr;
3575 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3576 layerSettings.geometry.boundaries = rect.toFloatRect();
3577 layerSettings.alpha = half(1.0);
3578 clientCompositionLayers.push_back(layerSettings);
3579 }
3580 }
3581 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
3582 buf->getNativeBuffer(), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003583 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003584 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003585}
3586
Chia-I Wu28e3a252018-09-07 12:05:02 -07003587void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003588 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003589 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003590}
3591
Dan Stoza7d89d062015-04-30 13:29:25 -07003592status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003593 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003594 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003595 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003596 const sp<Layer>& parent,
3597 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003598{
Dan Stoza7d89d062015-04-30 13:29:25 -07003599 // add this layer to the current state list
3600 {
3601 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003602 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003603 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3604 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003605 return NO_MEMORY;
3606 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003607 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003608 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003609 } else if (parent == nullptr) {
3610 lbc->onRemovedFromCurrentState();
3611 } else if (parent->isRemovedFromCurrentState()) {
3612 parent->addChild(lbc);
3613 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003614 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003615 parent->addChild(lbc);
3616 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003617
Yiwei Zhang243b3782018-05-15 17:40:04 -07003618 if (gbc != nullptr) {
3619 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3620 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3621 mMaxGraphicBufferProducerListSize,
3622 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3623 mGraphicBufferProducerList.size(),
3624 mMaxGraphicBufferProducerListSize, mNumLayers);
3625 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003626 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003627 }
3628
Mathias Agopian96f08192010-06-02 23:28:45 -07003629 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003630 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003631
Dan Stoza7d89d062015-04-30 13:29:25 -07003632 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003633}
3634
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003635uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003636 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003637}
3638
Mathias Agopian3f844832013-08-07 21:24:32 -07003639uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003640 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003641}
3642
Mathias Agopian3f844832013-08-07 21:24:32 -07003643uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003644 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003645}
3646
3647uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003648 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003649 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003650 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003651 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003652 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003653 }
3654 return old;
3655}
3656
Marissa Wall713b63f2018-10-17 15:42:43 -07003657bool SurfaceFlinger::flushTransactionQueues() {
3658 Mutex::Autolock _l(mStateLock);
3659 auto it = mTransactionQueues.begin();
3660 while (it != mTransactionQueues.end()) {
3661 auto& [applyToken, transactionQueue] = *it;
3662
3663 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003664 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3665 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003666 break;
3667 }
chaviw273171b2018-12-26 11:46:30 -08003668 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003669 transactionQueue.pop();
3670 }
3671
3672 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3673 }
3674 return mTransactionQueues.empty();
3675}
3676
chaviwca27f252018-02-06 16:46:39 -08003677bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3678 for (const ComposerState& state : states) {
3679 // Here we need to check that the interface we're given is indeed
3680 // one of our own. A malicious client could give us a nullptr
3681 // IInterface, or one of its own or even one of our own but a
3682 // different type. All these situations would cause us to crash.
3683 if (state.client == nullptr) {
3684 return true;
3685 }
3686
3687 sp<IBinder> binder = IInterface::asBinder(state.client);
3688 if (binder == nullptr) {
3689 return true;
3690 }
3691
3692 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3693 return true;
3694 }
3695 }
3696 return false;
3697}
3698
Marissa Wall17b4e452018-12-26 16:32:34 -08003699bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3700 const Vector<ComposerState>& states) {
Ady Abrahamc3e21312019-02-07 14:30:23 -08003701 nsecs_t expectedPresentTime;
3702 if (mUseScheduler) {
3703 expectedPresentTime = mScheduler->expectedPresentTime();
3704 } else {
3705 expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3706 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003707 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3708 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3709 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3710 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3711 return false;
3712 }
3713
Marissa Wall713b63f2018-10-17 15:42:43 -07003714 for (const ComposerState& state : states) {
3715 const layer_state_t& s = state.state;
3716 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3717 continue;
3718 }
3719 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003720 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003721 }
3722 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003723 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003724}
3725
3726void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3727 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003728 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003729 const InputWindowCommands& inputWindowCommands,
3730 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003731 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003732 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003733
chaviwca27f252018-02-06 16:46:39 -08003734 if (containsAnyInvalidClientState(states)) {
3735 return;
3736 }
3737
Marissa Wall713b63f2018-10-17 15:42:43 -07003738 // If its TransactionQueue already has a pending TransactionState or if it is pending
3739 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003740 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3741 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003742 setTransactionFlags(eTransactionNeeded);
3743 return;
3744 }
3745
chaviw273171b2018-12-26 11:46:30 -08003746 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003747}
3748
3749void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003750 const Vector<DisplayState>& displays, uint32_t flags,
3751 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003752 uint32_t transactionFlags = 0;
3753
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003754 if (flags & eAnimation) {
3755 // For window updates that are part of an animation we must wait for
3756 // previous animation "frames" to be handled.
3757 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003758 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003759 if (CC_UNLIKELY(err != NO_ERROR)) {
3760 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003761 // caller after a few seconds.
3762 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3763 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003764 mAnimTransactionPending = false;
3765 break;
3766 }
3767 }
3768 }
3769
chaviwca27f252018-02-06 16:46:39 -08003770 for (const DisplayState& display : displays) {
3771 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003772 }
3773
Marissa Walle2ffb422018-10-12 11:33:52 -07003774 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003775 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003776 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003777 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003778 // If the state doesn't require a traversal and there are callbacks, send them now
3779 if (!(clientStateFlags & eTraversalNeeded)) {
3780 mTransactionCompletedThread.sendCallbacks();
3781 }
3782 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003783
chaviw273171b2018-12-26 11:46:30 -08003784 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3785
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003786 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3787 // anyway. This can be used as a flush mechanism for previous async transactions.
3788 // Empty animation transaction can be used to simulate back-pressure, so also force a
3789 // transaction for empty animation transactions.
3790 if (transactionFlags == 0 &&
3791 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003792 transactionFlags = eTransactionNeeded;
3793 }
3794
Mathias Agopian386aa982011-11-07 21:58:03 -08003795 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003796 if (mInterceptor->isEnabled()) {
3797 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003798 }
Irvel468051e2016-06-13 16:44:44 -07003799
Mathias Agopian386aa982011-11-07 21:58:03 -08003800 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003801 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3802 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003803 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003804
3805 // if this is a synchronous transaction, wait for it to take effect
3806 // before returning.
3807 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003808 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003809 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003810 if (flags & eAnimation) {
3811 mAnimTransactionPending = true;
3812 }
3813 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003814 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3815 if (CC_UNLIKELY(err != NO_ERROR)) {
3816 // just in case something goes wrong in SF, return to the
3817 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003818 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3819 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003820 break;
3821 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003822 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003823 }
3824}
3825
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003826uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3827 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3828 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003829
Mathias Agopiane57f2922012-08-09 16:29:12 -07003830 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003831 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3832
3833 const uint32_t what = s.what;
3834 if (what & DisplayState::eSurfaceChanged) {
3835 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3836 state.surface = s.surface;
3837 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003838 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003839 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003840 if (what & DisplayState::eLayerStackChanged) {
3841 if (state.layerStack != s.layerStack) {
3842 state.layerStack = s.layerStack;
3843 flags |= eDisplayTransactionNeeded;
3844 }
3845 }
3846 if (what & DisplayState::eDisplayProjectionChanged) {
3847 if (state.orientation != s.orientation) {
3848 state.orientation = s.orientation;
3849 flags |= eDisplayTransactionNeeded;
3850 }
3851 if (state.frame != s.frame) {
3852 state.frame = s.frame;
3853 flags |= eDisplayTransactionNeeded;
3854 }
3855 if (state.viewport != s.viewport) {
3856 state.viewport = s.viewport;
3857 flags |= eDisplayTransactionNeeded;
3858 }
3859 }
3860 if (what & DisplayState::eDisplaySizeChanged) {
3861 if (state.width != s.width) {
3862 state.width = s.width;
3863 flags |= eDisplayTransactionNeeded;
3864 }
3865 if (state.height != s.height) {
3866 state.height = s.height;
3867 flags |= eDisplayTransactionNeeded;
3868 }
3869 }
3870
Mathias Agopiane57f2922012-08-09 16:29:12 -07003871 return flags;
3872}
3873
Robert Carrd4ae7f32018-06-07 16:10:57 -07003874bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3875 IPCThreadState* ipc = IPCThreadState::self();
3876 const int pid = ipc->getCallingPid();
3877 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003878 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003879 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003880 return false;
3881 }
3882 return true;
3883}
3884
chaviwca27f252018-02-06 16:46:39 -08003885uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3886 const layer_state_t& s = composerState.state;
3887 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3888
Mathias Agopian13127d82013-03-05 17:47:11 -08003889 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003890 if (layer == nullptr) {
3891 return 0;
3892 }
3893
chaviw8b3871a2017-11-01 17:41:01 -07003894 uint32_t flags = 0;
3895
Garfield Tan8a3083e2018-12-03 13:21:07 -08003896 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003897 bool geometryAppliesWithResize =
3898 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003899
3900 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3901 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003902 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003903 layer->pushPendingState();
3904 }
3905
chaviw8b3871a2017-11-01 17:41:01 -07003906 if (what & layer_state_t::ePositionChanged) {
3907 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3908 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003909 }
chaviw8b3871a2017-11-01 17:41:01 -07003910 }
3911 if (what & layer_state_t::eLayerChanged) {
3912 // NOTE: index needs to be calculated before we update the state
3913 const auto& p = layer->getParent();
3914 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003915 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003916 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003917 mCurrentState.layersSortedByZ.removeAt(idx);
3918 mCurrentState.layersSortedByZ.add(layer);
3919 // we need traversal (state changed)
3920 // AND transaction (list changed)
3921 flags |= eTransactionNeeded|eTraversalNeeded;
3922 }
chaviw8b3871a2017-11-01 17:41:01 -07003923 } else {
3924 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003925 flags |= eTransactionNeeded|eTraversalNeeded;
3926 }
3927 }
chaviw8b3871a2017-11-01 17:41:01 -07003928 }
3929 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003930 // NOTE: index needs to be calculated before we update the state
3931 const auto& p = layer->getParent();
3932 if (p == nullptr) {
3933 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3934 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3935 mCurrentState.layersSortedByZ.removeAt(idx);
3936 mCurrentState.layersSortedByZ.add(layer);
3937 // we need traversal (state changed)
3938 // AND transaction (list changed)
3939 flags |= eTransactionNeeded|eTraversalNeeded;
3940 }
3941 } else {
3942 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3943 flags |= eTransactionNeeded|eTraversalNeeded;
3944 }
chaviw8b3871a2017-11-01 17:41:01 -07003945 }
3946 }
3947 if (what & layer_state_t::eSizeChanged) {
3948 if (layer->setSize(s.w, s.h)) {
3949 flags |= eTraversalNeeded;
3950 }
3951 }
3952 if (what & layer_state_t::eAlphaChanged) {
3953 if (layer->setAlpha(s.alpha))
3954 flags |= eTraversalNeeded;
3955 }
3956 if (what & layer_state_t::eColorChanged) {
3957 if (layer->setColor(s.color))
3958 flags |= eTraversalNeeded;
3959 }
Peiyong Lind3788632018-09-18 16:01:31 -07003960 if (what & layer_state_t::eColorTransformChanged) {
3961 if (layer->setColorTransform(s.colorTransform)) {
3962 flags |= eTraversalNeeded;
3963 }
3964 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003965 if (what & layer_state_t::eBackgroundColorChanged) {
3966 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3967 flags |= eTraversalNeeded;
3968 }
3969 }
chaviw8b3871a2017-11-01 17:41:01 -07003970 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003971 // TODO: b/109894387
3972 //
3973 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3974 // rotation. To see the problem observe that if we have a square parent, and a child
3975 // of the same size, then we rotate the child 45 degrees around it's center, the child
3976 // must now be cropped to a non rectangular 8 sided region.
3977 //
3978 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3979 // private API, and the WindowManager only uses rotation in one case, which is on a top
3980 // level layer in which cropping is not an issue.
3981 //
3982 // However given that abuse of rotation matrices could lead to surfaces extending outside
3983 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3984 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3985 // transformations.
3986 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003987 flags |= eTraversalNeeded;
3988 }
3989 if (what & layer_state_t::eTransparentRegionChanged) {
3990 if (layer->setTransparentRegionHint(s.transparentRegion))
3991 flags |= eTraversalNeeded;
3992 }
3993 if (what & layer_state_t::eFlagsChanged) {
3994 if (layer->setFlags(s.flags, s.mask))
3995 flags |= eTraversalNeeded;
3996 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003997 if (what & layer_state_t::eCropChanged_legacy) {
3998 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003999 flags |= eTraversalNeeded;
4000 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004001 if (what & layer_state_t::eCornerRadiusChanged) {
4002 if (layer->setCornerRadius(s.cornerRadius))
4003 flags |= eTraversalNeeded;
4004 }
chaviw8b3871a2017-11-01 17:41:01 -07004005 if (what & layer_state_t::eLayerStackChanged) {
4006 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4007 // We only allow setting layer stacks for top level layers,
4008 // everything else inherits layer stack from its parent.
4009 if (layer->hasParent()) {
4010 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
4011 layer->getName().string());
4012 } else if (idx < 0) {
4013 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
4014 "that also does not appear in the top level layer list. Something"
4015 " has gone wrong.", layer->getName().string());
4016 } else if (layer->setLayerStack(s.layerStack)) {
4017 mCurrentState.layersSortedByZ.removeAt(idx);
4018 mCurrentState.layersSortedByZ.add(layer);
4019 // we need traversal (state changed)
4020 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07004021 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07004022 }
4023 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004024 if (what & layer_state_t::eDeferTransaction_legacy) {
4025 if (s.barrierHandle_legacy != nullptr) {
4026 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
4027 } else if (s.barrierGbp_legacy != nullptr) {
4028 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07004029 if (authenticateSurfaceTextureLocked(gbp)) {
4030 const auto& otherLayer =
4031 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07004032 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07004033 } else {
4034 ALOGE("Attempt to defer transaction to to an"
4035 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08004036 }
4037 }
chaviw8b3871a2017-11-01 17:41:01 -07004038 // We don't trigger a traversal here because if no other state is
4039 // changed, we don't want this to cause any more work
4040 }
4041 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08004042 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07004043 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08004044 if (!hadParent) {
4045 mCurrentState.layersSortedByZ.remove(layer);
4046 }
chaviw8b3871a2017-11-01 17:41:01 -07004047 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08004048 }
chaviw8b3871a2017-11-01 17:41:01 -07004049 }
4050 if (what & layer_state_t::eReparentChildren) {
4051 if (layer->reparentChildren(s.reparentHandle)) {
4052 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07004053 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004054 }
chaviw8b3871a2017-11-01 17:41:01 -07004055 if (what & layer_state_t::eDetachChildren) {
4056 layer->detachChildren();
4057 }
4058 if (what & layer_state_t::eOverrideScalingModeChanged) {
4059 layer->setOverrideScalingMode(s.overrideScalingMode);
4060 // We don't trigger a traversal here because if no other state is
4061 // changed, we don't want this to cause any more work
4062 }
Marissa Wall61c58622018-07-18 10:12:20 -07004063 if (what & layer_state_t::eTransformChanged) {
4064 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4065 }
4066 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4067 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4068 flags |= eTraversalNeeded;
4069 }
4070 if (what & layer_state_t::eCropChanged) {
4071 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4072 }
Marissa Wall861616d2018-10-22 12:52:23 -07004073 if (what & layer_state_t::eFrameChanged) {
4074 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4075 }
Marissa Wall61c58622018-07-18 10:12:20 -07004076 if (what & layer_state_t::eAcquireFenceChanged) {
4077 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4078 }
4079 if (what & layer_state_t::eDataspaceChanged) {
4080 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4081 }
4082 if (what & layer_state_t::eHdrMetadataChanged) {
4083 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4084 }
4085 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4086 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4087 }
4088 if (what & layer_state_t::eApiChanged) {
4089 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4090 }
4091 if (what & layer_state_t::eSidebandStreamChanged) {
4092 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4093 }
Robert Carr720e5062018-07-30 17:45:14 -07004094 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004095 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
4096 layer->setInputInfo(s.inputInfo);
4097 flags |= eTraversalNeeded;
4098 } else {
4099 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4100 }
Robert Carr720e5062018-07-30 17:45:14 -07004101 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004102 if (what & layer_state_t::eMetadataChanged) {
4103 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4104 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004105 std::vector<sp<CallbackHandle>> callbackHandles;
4106 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
4107 mTransactionCompletedThread.run();
4108 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
4109 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4110 }
4111 }
Marissa Wall73411622019-01-25 10:45:41 -08004112
4113 if (what & layer_state_t::eBufferChanged) {
4114 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
4115 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
4116 s.buffer);
4117 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004118 if (what & layer_state_t::eCachedBufferChanged) {
4119 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08004120 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
4121 s.cachedBuffer.bufferId);
Marissa Wallebc2c052019-01-16 19:16:55 -08004122 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4123 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004124 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4125 // Do not put anything that updates layer state or modifies flags after
4126 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004127 return flags;
4128}
4129
chaviw273171b2018-12-26 11:46:30 -08004130uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4131 uint32_t flags = 0;
4132 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4133 flags |= eTraversalNeeded;
4134 }
4135
4136 mInputWindowCommands.merge(inputWindowCommands);
4137 return flags;
4138}
4139
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004140status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4141 uint32_t h, PixelFormat format, uint32_t flags,
4142 LayerMetadata metadata, sp<IBinder>* handle,
4143 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004144 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004145 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004146 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004147 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004148 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004149
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004150 status_t result = NO_ERROR;
4151
4152 sp<Layer> layer;
4153
Cody Northropbc755282017-03-31 12:00:08 -06004154 String8 uniqueName = getUniqueLayerName(name);
4155
Mathias Agopian3165cc22012-08-08 19:42:09 -07004156 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004157 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004158 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4159 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004160
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004161 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004162 case ISurfaceComposerClient::eFXSurfaceBufferState:
4163 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4164 break;
chaviw13fdc492017-06-27 12:40:18 -07004165 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004166 // check if buffer size is set for color layer.
4167 if (w > 0 || h > 0) {
4168 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4169 int(w), int(h));
4170 return BAD_VALUE;
4171 }
4172
chaviw13fdc492017-06-27 12:40:18 -07004173 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004174 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004175 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004176 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004177 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004178 // check if buffer size is set for container layer.
4179 if (w > 0 || h > 0) {
4180 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4181 int(w), int(h));
4182 return BAD_VALUE;
4183 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004184 result = createContainerLayer(client,
4185 uniqueName, w, h, flags,
4186 handle, &layer);
4187 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004188 default:
4189 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004190 break;
4191 }
4192
Dan Stoza7d89d062015-04-30 13:29:25 -07004193 if (result != NO_ERROR) {
4194 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004195 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004196
Chia-I Wuab0c3192017-08-01 11:29:00 -07004197 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4198 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004199 if (metadata.has(METADATA_WINDOW_TYPE)) {
4200 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4201 if (windowType == 441731) {
4202 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4203 layer->setPrimaryDisplayOnly();
4204 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004205 }
4206
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004207 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004208
Robert Carrb89ea9d2018-12-10 13:01:14 -08004209 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4210 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4211 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004212 if (result != NO_ERROR) {
4213 return result;
4214 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004215 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004216
4217 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004218 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004219}
4220
Cody Northropbc755282017-03-31 12:00:08 -06004221String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4222{
4223 bool matchFound = true;
4224 uint32_t dupeCounter = 0;
4225
4226 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4227 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4228
Dan Stoza436ccf32018-06-21 12:10:12 -07004229 // Grab the state lock since we're accessing mCurrentState
4230 Mutex::Autolock lock(mStateLock);
4231
Cody Northropbc755282017-03-31 12:00:08 -06004232 // Loop over layers until we're sure there is no matching name
4233 while (matchFound) {
4234 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004235 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004236 if (layer->getName() == uniqueName) {
4237 matchFound = true;
4238 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4239 }
4240 });
4241 }
4242
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004243 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4244 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004245
4246 return uniqueName;
4247}
4248
Marissa Wallfd668622018-05-10 10:21:13 -07004249status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4250 uint32_t w, uint32_t h, uint32_t flags,
4251 PixelFormat& format, sp<IBinder>* handle,
4252 sp<IGraphicBufferProducer>* gbp,
4253 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004254 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004255 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004256 case PIXEL_FORMAT_TRANSPARENT:
4257 case PIXEL_FORMAT_TRANSLUCENT:
4258 format = PIXEL_FORMAT_RGBA_8888;
4259 break;
4260 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004261 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004262 break;
4263 }
4264
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004265 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004266 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004267 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004268 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004269 *handle = layer->getHandle();
4270 *gbp = layer->getProducer();
4271 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004272 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004273
Marissa Wallfd668622018-05-10 10:21:13 -07004274 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004275 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004276}
4277
Marissa Wall61c58622018-07-18 10:12:20 -07004278status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4279 uint32_t w, uint32_t h, uint32_t flags,
4280 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004281 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004282 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004283 *handle = layer->getHandle();
4284 *outLayer = layer;
4285
4286 return NO_ERROR;
4287}
4288
chaviw13fdc492017-06-27 12:40:18 -07004289status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004290 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004291 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004292{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004293 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004294 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004295 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004296}
4297
Robert Carr6b3f6c52018-08-13 13:05:17 -07004298status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4299 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4300 sp<IBinder>* handle, sp<Layer>* outLayer)
4301{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004302 *outLayer =
4303 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004304 *handle = (*outLayer)->getHandle();
4305 return NO_ERROR;
4306}
4307
4308
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004309void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004310 mLayersPendingRemoval.add(layer);
4311 mLayersRemoved = true;
4312 setTransactionFlags(eTransactionNeeded);
4313}
4314
Robert Carr695d5282018-12-18 15:27:58 -08004315void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004316{
Robert Carr2e102c92018-10-23 12:11:15 -07004317 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004318 // If a layer has a parent, we allow it to out-live it's handle
4319 // with the idea that the parent holds a reference and will eventually
4320 // be cleaned up. However no one cleans up the top-level so we do so
4321 // here.
4322 if (layer->getParent() == nullptr) {
4323 mCurrentState.layersSortedByZ.remove(layer);
4324 }
4325 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004326 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004327}
4328
Mathias Agopianb60314a2012-04-10 22:09:54 -07004329// ---------------------------------------------------------------------------
4330
Andy McFadden13a082e2012-08-24 10:16:42 -07004331void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004332 const auto display = getDefaultDisplayDeviceLocked();
4333 if (!display) return;
4334
4335 const sp<IBinder> token = display->getDisplayToken().promote();
4336 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004337
Jesse Hall01e29052013-02-19 16:13:35 -08004338 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004339 Vector<ComposerState> state;
4340 Vector<DisplayState> displays;
4341 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004342 d.what = DisplayState::eDisplayProjectionChanged |
4343 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004344 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004345 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004346 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004347 d.frame.makeInvalid();
4348 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004349 d.width = 0;
4350 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004351 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004352 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004353
Dominik Laskowskie9774092018-12-11 10:04:24 -08004354 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004355
Dominik Laskowski83b88212018-12-11 13:34:06 -08004356 const nsecs_t vsyncPeriod = getVsyncPeriod();
4357 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004358
Brian Andersond0010582017-03-07 13:20:31 -08004359 // Use phase of 0 since phase is not known.
4360 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004361 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004362 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004363}
4364
4365void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004366 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004367 postMessageAsync(
4368 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004369}
4370
Dominik Laskowskie9774092018-12-11 10:04:24 -08004371void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004372 if (display->isVirtual()) {
4373 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004374 return;
4375 }
4376
Dominik Laskowski075d3172018-05-24 15:50:06 -07004377 const auto displayId = display->getId();
4378 LOG_ALWAYS_FATAL_IF(!displayId);
4379
Dominik Laskowski34157762018-10-31 13:07:19 -07004380 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004381
4382 int currentMode = display->getPowerMode();
4383 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004384 return;
4385 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004386
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004387 display->setPowerMode(mode);
4388
Lloyd Pique4dccc412018-01-22 17:21:36 -08004389 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004390 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004391 }
4392
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004393 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004394 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004395 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004396 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004397 if (mUseScheduler) {
4398 mScheduler->onScreenAcquired(mAppConnectionHandle);
4399 } else {
4400 mEventThread->onScreenAcquired();
4401 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004402 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004403 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004404
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004405 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004406 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004407 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004408
4409 struct sched_param param = {0};
4410 param.sched_priority = 1;
4411 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4412 ALOGW("Couldn't set SCHED_FIFO on display on");
4413 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004414 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004415 // Turn off the display
4416 struct sched_param param = {0};
4417 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4418 ALOGW("Couldn't set SCHED_OTHER on display off");
4419 }
4420
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004421 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004422 if (mUseScheduler) {
4423 mScheduler->disableHardwareVsync(true);
4424 } else {
4425 disableHardwareVsync(true); // also cancels any in-progress resync
4426 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004427 if (mUseScheduler) {
4428 mScheduler->onScreenReleased(mAppConnectionHandle);
4429 } else {
4430 mEventThread->onScreenReleased();
4431 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004432 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004433
Dominik Laskowski075d3172018-05-24 15:50:06 -07004434 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004435 mVisibleRegionsDirty = true;
4436 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004437 } else if (mode == HWC_POWER_MODE_DOZE ||
4438 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004439 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004440 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004441 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004442 if (mUseScheduler) {
4443 mScheduler->onScreenAcquired(mAppConnectionHandle);
4444 } else {
4445 mEventThread->onScreenAcquired();
4446 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004447 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004448 }
4449 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4450 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004451 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004452 if (mUseScheduler) {
4453 mScheduler->disableHardwareVsync(true);
4454 } else {
4455 disableHardwareVsync(true); // also cancels any in-progress resync
4456 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004457 if (mUseScheduler) {
4458 mScheduler->onScreenReleased(mAppConnectionHandle);
4459 } else {
4460 mEventThread->onScreenReleased();
4461 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004462 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004463 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004464 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004465 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004466 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004467 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004468
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004469 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004470 mTimeStats->setPowerMode(mode);
Ana Krulec4593b692019-01-11 22:07:25 -08004471 if (mUseScheduler && mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004472 // Update refresh rate stats.
4473 mRefreshRateStats->setPowerMode(mode);
4474 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004475 }
4476
Dominik Laskowski34157762018-10-31 13:07:19 -07004477 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004478}
4479
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004480void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004481 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004482 const auto display = getDisplayDevice(displayToken);
4483 if (!display) {
4484 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4485 displayToken.get());
4486 } else if (display->isVirtual()) {
4487 ALOGW("Attempt to set power mode %d for virtual display", mode);
4488 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004489 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004490 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004491 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004492}
4493
4494// ---------------------------------------------------------------------------
4495
Dominik Laskowskic2867142019-01-21 11:33:38 -08004496status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4497 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004498 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004499
Mathias Agopianbd115332013-04-18 16:41:04 -07004500 IPCThreadState* ipc = IPCThreadState::self();
4501 const int pid = ipc->getCallingPid();
4502 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004503
Mathias Agopianbd115332013-04-18 16:41:04 -07004504 if ((uid != AID_SHELL) &&
4505 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004506 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4507 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004508 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004509 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004510 // (this would indicate SF is stuck, but we want to be able to
4511 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004512 status_t err = mStateLock.timedLock(s2ns(1));
4513 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004514 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004515 StringAppendF(&result,
4516 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4517 "(no locks held)\n",
4518 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004519 }
4520
Dominik Laskowskic2867142019-01-21 11:33:38 -08004521 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004522
Dominik Laskowskic2867142019-01-21 11:33:38 -08004523 static const std::unordered_map<std::string, Dumper> dumpers = {
4524 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4525 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4526 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004527 {"--dispsync"s, dumper([this](std::string& s) {
4528 if (mUseScheduler) {
4529 mScheduler->dumpPrimaryDispSync(s);
4530 } else {
4531 mPrimaryDispSync->dump(s);
4532 }
4533 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004534 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4535 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
4536 {"--frame-composition"s, dumper(&SurfaceFlinger::dumpFrameCompositionInfo)},
4537 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4538 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4539 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4540 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4541 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4542 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004543 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004544 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4545 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004546
Dominik Laskowskic2867142019-01-21 11:33:38 -08004547 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004548
Dominik Laskowskic2867142019-01-21 11:33:38 -08004549 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4550 (it->second)(args, asProto, result);
4551 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004552 if (asProto) {
4553 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4554 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4555 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004556 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004557 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004558 }
4559
Mathias Agopian9795c422009-08-26 16:36:26 -07004560 if (locked) {
4561 mStateLock.unlock();
4562 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004563 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004564 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004565 return NO_ERROR;
4566}
4567
Dominik Laskowskic2867142019-01-21 11:33:38 -08004568void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004569 mCurrentState.traverseInZOrder(
4570 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004571}
4572
Dominik Laskowskic2867142019-01-21 11:33:38 -08004573void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004574 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004575
Dominik Laskowskic2867142019-01-21 11:33:38 -08004576 if (args.size() > 1) {
4577 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004578 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004579 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004580 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004581 }
Robert Carr2047fae2016-11-28 14:09:09 -08004582 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004583 } else {
4584 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004585 }
4586}
4587
Dominik Laskowskic2867142019-01-21 11:33:38 -08004588void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004589 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004590 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004591 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004592 }
Robert Carr2047fae2016-11-28 14:09:09 -08004593 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004594
Svetoslavd85084b2014-03-20 10:28:31 -07004595 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004596}
4597
Dominik Laskowskic2867142019-01-21 11:33:38 -08004598void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4599 mTimeStats->parseArgs(asProto, args, result);
4600}
4601
Jamie Gennis6547ff42013-07-16 20:12:42 -07004602// This should only be called from the main thread. Otherwise it would need
4603// the lock and should use mCurrentState rather than mDrawingState.
4604void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004605 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004606 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004607 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004608
4609 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4610}
4611
Yiwei Zhang5434a782018-12-05 18:06:32 -08004612void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004613 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004614
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004615 if (isLayerTripleBufferingDisabled())
4616 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004617
Yiwei Zhang5434a782018-12-05 18:06:32 -08004618 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4619 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4620 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4621 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4622 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4623 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004624 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004625}
4626
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004627void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004628 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004629 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004630 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004631 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004632
4633 StringAppendF(&result, "Scheduler: %s\n\n", mUseScheduler ? "enabled" : "disabled");
4634
4635 if (mUseScheduler) {
4636 mScheduler->dump(mAppConnectionHandle, result);
4637 } else {
4638 mEventThread->dump(result);
4639 }
4640}
4641
Yiwei Zhang5434a782018-12-05 18:06:32 -08004642void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4643 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004644 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4645 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004646 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004647 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004648 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004649 }
David Sodman4a36e932017-11-07 14:29:47 -08004650 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004651 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004652 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004653 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4654 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004655}
4656
Dan Stozae77c7662016-05-13 11:37:28 -07004657void SurfaceFlinger::recordBufferingStats(const char* layerName,
4658 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004659 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4660 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004661 for (const auto& segment : history) {
4662 if (!segment.usedThirdBuffer) {
4663 stats.twoBufferTime += segment.totalTime;
4664 }
4665 if (segment.occupancyAverage < 1.0f) {
4666 stats.doubleBufferedTime += segment.totalTime;
4667 } else if (segment.occupancyAverage < 2.0f) {
4668 stats.tripleBufferedTime += segment.totalTime;
4669 }
4670 ++stats.numSegments;
4671 stats.totalTime += segment.totalTime;
4672 }
4673}
4674
Yiwei Zhang5434a782018-12-05 18:06:32 -08004675void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4676 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004677
4678 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4679 const size_t count = currentLayers.size();
4680 for (size_t i=0 ; i<count ; i++) {
4681 currentLayers[i]->dumpFrameEvents(result);
4682 }
4683}
4684
Yiwei Zhang5434a782018-12-05 18:06:32 -08004685void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004686 result.append("Buffering stats:\n");
4687 result.append(" [Layer name] <Active time> <Two buffer> "
4688 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004689 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004690 typedef std::tuple<std::string, float, float, float> BufferTuple;
4691 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004692 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004693 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004694 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004695 if (stats.numSegments == 0) {
4696 continue;
4697 }
4698 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4699 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4700 stats.totalTime;
4701 float doubleBufferRatio = static_cast<float>(
4702 stats.doubleBufferedTime) / stats.totalTime;
4703 float tripleBufferRatio = static_cast<float>(
4704 stats.tripleBufferedTime) / stats.totalTime;
4705 sorted.insert({activeTime, {name, twoBufferRatio,
4706 doubleBufferRatio, tripleBufferRatio}});
4707 }
4708 for (const auto& sortedPair : sorted) {
4709 float activeTime = sortedPair.first;
4710 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004711 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4712 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004713 }
4714 result.append("\n");
4715}
4716
Yiwei Zhang5434a782018-12-05 18:06:32 -08004717void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004718 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004719 const auto displayId = display->getId();
4720 if (!displayId) {
4721 continue;
4722 }
4723 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004724 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004725 continue;
4726 }
4727
Yiwei Zhang5434a782018-12-05 18:06:32 -08004728 StringAppendF(&result,
4729 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4730 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004731 uint8_t port;
4732 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004733 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004734 result.append("no identification data\n");
4735 continue;
4736 }
4737
4738 if (!isEdid(data)) {
4739 result.append("unknown identification data: ");
4740 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004741 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004742 }
4743 result.append("\n");
4744 continue;
4745 }
4746
4747 const auto edid = parseEdid(data);
4748 if (!edid) {
4749 result.append("invalid EDID: ");
4750 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004751 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004752 }
4753 result.append("\n");
4754 continue;
4755 }
4756
Yiwei Zhang5434a782018-12-05 18:06:32 -08004757 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004758 result.append(edid->displayName.data(), edid->displayName.length());
4759 result.append("\"\n");
4760 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004761}
4762
Yiwei Zhang5434a782018-12-05 18:06:32 -08004763void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4764 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4765 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4766 StringAppendF(&result, "DisplayColorSetting: %s\n",
4767 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004768
4769 // TODO: print out if wide-color mode is active or not
4770
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004771 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004772 const auto displayId = display->getId();
4773 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004774 continue;
4775 }
4776
Yiwei Zhang5434a782018-12-05 18:06:32 -08004777 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004778 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004779 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004780 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004781 }
4782
Lloyd Pique32cbe282018-10-19 13:09:22 -07004783 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004784 StringAppendF(&result, " Current color mode: %s (%d)\n",
4785 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004786 }
4787 result.append("\n");
4788}
4789
Yiwei Zhang5434a782018-12-05 18:06:32 -08004790void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004791 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004792 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4793 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004794 continue;
4795 }
4796
Dominik Laskowski05275f12018-11-01 15:03:24 -07004797 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004798 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4799 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004800 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004801 compositionInfo.dump(result, nullptr);
4802 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004803 }
4804 }
David Sodman7e4ae112018-02-09 15:02:28 -08004805}
4806
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004807LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004808 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004809 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4810 const State& state = useDrawing ? mDrawingState : mCurrentState;
4811 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004812 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004813 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004814 });
4815
4816 return layersProto;
4817}
4818
Lloyd Pique32cbe282018-10-19 13:09:22 -07004819LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004820 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004821
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004822 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004823 resolution->set_w(displayDevice.getWidth());
4824 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004825
Lloyd Pique32cbe282018-10-19 13:09:22 -07004826 auto display = displayDevice.getCompositionDisplay();
4827 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004828
Lloyd Pique32cbe282018-10-19 13:09:22 -07004829 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4830 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4831 layersProto.set_global_transform(displayState.orientation);
4832
4833 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004834 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004835 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004836 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004837 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004838 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004839 }
4840 });
4841
4842 return layersProto;
4843}
4844
Dominik Laskowskic2867142019-01-21 11:33:38 -08004845void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4846 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004847 Colorizer colorizer(colorize);
4848
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004849 // figure out if we're stuck somewhere
4850 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004851 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004852 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4853
4854 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004855 * Dump library configuration.
4856 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004857
4858 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004859 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004860 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004861 appendSfConfigString(result);
4862 appendUiConfigString(result);
4863 appendGuiConfigString(result);
4864 result.append("\n");
4865
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004866 result.append("\nDisplay identification data:\n");
4867 dumpDisplayIdentificationData(result);
4868
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004869 result.append("\nWide-Color information:\n");
4870 dumpWideColorInfo(result);
4871
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004872 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004873 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004874 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004875 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004876 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004877
Andy McFadden41d67d72014-04-25 16:58:34 -07004878 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004879 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004880 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004881 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004882 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004883
Dan Stozab90cf072015-03-05 11:05:59 -08004884 dumpStaticScreenStats(result);
4885 result.append("\n");
4886
Yiwei Zhang5434a782018-12-05 18:06:32 -08004887 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004888
Dan Stozae77c7662016-05-13 11:37:28 -07004889 dumpBufferingStats(result);
4890
Andy McFadden4803b742012-09-24 19:07:20 -07004891 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004892 * Dump the visible layer list
4893 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004894 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004895 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4896 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4897 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004898 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004899
Chia-I Wu2f884132018-09-13 15:17:58 -07004900 {
4901 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4902 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004903 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004904 result.append("\n");
4905 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004906
David Sodman7e4ae112018-02-09 15:02:28 -08004907 result.append("\nFrame-Composition information:\n");
4908 dumpFrameCompositionInfo(result);
4909 result.append("\n");
4910
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004911 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004912 * Dump Display state
4913 */
4914
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004915 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004916 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004917 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004918 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004919 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004920 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004921 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004922
4923 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004924 * Dump SurfaceFlinger global state
4925 */
4926
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004927 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004928 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004929 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004930
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004931 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004932
Dominik Laskowski075d3172018-05-24 15:50:06 -07004933 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004934 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4935 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004936 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4937 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004938 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004939 StringAppendF(&result,
4940 " transaction-flags : %08x\n"
4941 " gpu_to_cpu_unsupported : %d\n",
4942 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004943
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004944 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004945 displayId && getHwComposer().isConnected(*displayId)) {
4946 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004947 StringAppendF(&result,
4948 " refresh-rate : %f fps\n"
4949 " x-dpi : %f\n"
4950 " y-dpi : %f\n",
4951 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4952 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004953 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004954
Yiwei Zhang5434a782018-12-05 18:06:32 -08004955 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004956
Dan Stozae22aec72016-08-01 13:20:59 -07004957 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004958 * Tracing state
4959 */
4960 mTracing.dump(result);
4961 result.append("\n");
4962
4963 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004964 * HWC layer minidump
4965 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004966 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004967 const auto displayId = display->getId();
4968 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004969 continue;
4970 }
4971
Yiwei Zhang5434a782018-12-05 18:06:32 -08004972 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004973 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004974 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004975 result.append("\n");
4976 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004977
4978 /*
4979 * Dump HWComposer state
4980 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004981 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004982 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004983 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004984 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004985 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004986 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004987
4988 /*
4989 * Dump gralloc state
4990 */
4991 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4992 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004993
4994 /*
4995 * Dump VrFlinger state if in use.
4996 */
4997 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4998 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004999 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005000 result.append("\n");
5001 }
Ana Krulecb43429d2019-01-09 14:28:51 -08005002
5003 /**
5004 * Scheduler dump state.
5005 */
5006 if (mUseScheduler) {
5007 result.append("\nScheduler state:\n");
5008 result.append(mScheduler->doDump() + "\n");
5009 result.append(mRefreshRateStats->doDump() + "\n");
5010 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005011}
5012
Dominik Laskowski075d3172018-05-24 15:50:06 -07005013const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07005014 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005015 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07005016 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005017 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07005018 }
5019 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005020
Dominik Laskowski34157762018-10-31 13:07:19 -07005021 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005022 static const Vector<sp<Layer>> empty;
5023 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07005024}
5025
Chia-I Wu28f320b2018-05-03 11:02:56 -07005026void SurfaceFlinger::updateColorMatrixLocked() {
5027 mat4 colorMatrix;
5028 if (mGlobalSaturationFactor != 1.0f) {
5029 // Rec.709 luma coefficients
5030 float3 luminance{0.213f, 0.715f, 0.072f};
5031 luminance *= 1.0f - mGlobalSaturationFactor;
5032 mat4 saturationMatrix = mat4(
5033 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
5034 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
5035 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
5036 vec4{0.0f, 0.0f, 0.0f, 1.0f}
5037 );
5038 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
5039 } else {
5040 colorMatrix = mClientColorMatrix * mDaltonizer();
5041 }
5042
5043 if (mCurrentState.colorMatrix != colorMatrix) {
5044 mCurrentState.colorMatrix = colorMatrix;
5045 mCurrentState.colorMatrixChanged = true;
5046 setTransactionFlags(eTransactionNeeded);
5047 }
5048}
5049
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005050status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005051#pragma clang diagnostic push
5052#pragma clang diagnostic error "-Wswitch-enum"
5053 switch (static_cast<ISurfaceComposerTag>(code)) {
5054 // These methods should at minimum make sure that the client requested
5055 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005056 case BOOT_FINISHED:
5057 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005058 case CREATE_DISPLAY:
5059 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005060 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005061 case GET_ACTIVE_COLOR_MODE:
5062 case GET_ANIMATION_FRAME_STATS:
5063 case GET_HDR_CAPABILITIES:
5064 case SET_ACTIVE_CONFIG:
5065 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005066 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005067 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005068 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005069 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
5070 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005071 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5072 IPCThreadState* ipc = IPCThreadState::self();
5073 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5074 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005075 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005076 }
Robert Carr1db73f62016-12-21 12:58:51 -08005077 return OK;
5078 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005079 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005080 IPCThreadState* ipc = IPCThreadState::self();
5081 const int pid = ipc->getCallingPid();
5082 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005083 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5084 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005085 return PERMISSION_DENIED;
5086 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005087 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005088 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005089 // Used by apps to hook Choreographer to SurfaceFlinger.
5090 case CREATE_DISPLAY_EVENT_CONNECTION:
5091 // The following calls are currently used by clients that do not
5092 // request necessary permissions. However, they do not expose any secret
5093 // information, so it is OK to pass them.
5094 case AUTHENTICATE_SURFACE:
5095 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005096 case GET_PHYSICAL_DISPLAY_IDS:
5097 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005098 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005099 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005100 case GET_DISPLAY_CONFIGS:
5101 case GET_DISPLAY_STATS:
5102 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5103 // Calling setTransactionState is safe, because you need to have been
5104 // granted a reference to Client* and Handle* to do anything with it.
5105 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005106 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005107 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005108 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005109 case GET_PROTECTED_CONTENT_SUPPORT:
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08005110 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005111 return OK;
5112 }
5113 case CAPTURE_LAYERS:
5114 case CAPTURE_SCREEN: {
5115 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005116 IPCThreadState* ipc = IPCThreadState::self();
5117 const int pid = ipc->getCallingPid();
5118 const int uid = ipc->getCallingUid();
5119 if ((uid != AID_GRAPHICS) &&
5120 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5121 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5122 return PERMISSION_DENIED;
5123 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005124 return OK;
5125 }
5126 // The following codes are deprecated and should never be allowed to access SF.
5127 case CONNECT_DISPLAY_UNUSED:
5128 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5129 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5130 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005131 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005132 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005133
5134 // These codes are used for the IBinder protocol to either interrogate the recipient
5135 // side of the transaction for its canonical interface descriptor or to dump its state.
5136 // We let them pass by default.
5137 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5138 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5139 code == IBinder::SYSPROPS_TRANSACTION) {
5140 return OK;
5141 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005142 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005143 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005144 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005145 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5146 return OK;
5147 }
5148 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5149 return PERMISSION_DENIED;
5150#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005151}
5152
Ana Krulec13be8ad2018-08-21 02:43:56 +00005153status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5154 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005155 status_t credentialCheck = CheckTransactCodeCredentials(code);
5156 if (credentialCheck != OK) {
5157 return credentialCheck;
5158 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005159
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005160 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5161 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005162 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005163 IPCThreadState* ipc = IPCThreadState::self();
5164 const int uid = ipc->getCallingUid();
5165 if (CC_UNLIKELY(uid != AID_SYSTEM
5166 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005167 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005168 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005169 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005170 return PERMISSION_DENIED;
5171 }
5172 int n;
5173 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005174 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005175 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005176 return NO_ERROR;
5177 case 1002: // SHOW_UPDATES
5178 n = data.readInt32();
5179 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005180 invalidateHwcGeometry();
5181 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005182 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005183 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005184 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005185 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005186 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005187 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005188 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005189 setTransactionFlags(
5190 eTransactionNeeded|
5191 eDisplayTransactionNeeded|
5192 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005193 return NO_ERROR;
5194 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005195 case 1006:{ // send empty update
5196 signalRefresh();
5197 return NO_ERROR;
5198 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005199 case 1008: // toggle use of hw composer
5200 n = data.readInt32();
5201 mDebugDisableHWC = n ? 1 : 0;
5202 invalidateHwcGeometry();
5203 repaintEverything();
5204 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005205 case 1009: // toggle use of transform hint
5206 n = data.readInt32();
5207 mDebugDisableTransformHint = n ? 1 : 0;
5208 invalidateHwcGeometry();
5209 repaintEverything();
5210 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005211 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005212 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005213 reply->writeInt32(0);
5214 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005215 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005216 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005217 return NO_ERROR;
5218 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005219 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005220 if (!display) {
5221 return NAME_NOT_FOUND;
5222 }
5223
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005224 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005225 return NO_ERROR;
5226 }
5227 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005228 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005229 // daltonize
5230 n = data.readInt32();
5231 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005232 case 1:
5233 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5234 break;
5235 case 2:
5236 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5237 break;
5238 case 3:
5239 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5240 break;
5241 default:
5242 mDaltonizer.setType(ColorBlindnessType::None);
5243 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005244 }
5245 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005246 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005247 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005248 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005249 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005250
5251 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005252 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005253 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005254 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005255 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005256 // apply a color matrix
5257 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005258 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005259 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005260 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005261 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005262 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005263 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005264 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005265 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005266 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005267 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005268
5269 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5270 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005271 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005272 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5273 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5274 }
5275
Chia-I Wu28f320b2018-05-03 11:02:56 -07005276 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005277 return NO_ERROR;
5278 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005279 // This is an experimental interface
5280 // Needs to be shifted to proper binder interface when we productize
5281 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005282 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005283 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005284 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005285 return NO_ERROR;
5286 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005287 case 1017: {
5288 n = data.readInt32();
5289 mForceFullDamage = static_cast<bool>(n);
5290 return NO_ERROR;
5291 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005292 case 1018: { // Modify Choreographer's phase offset
5293 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005294 if (mUseScheduler) {
5295 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5296 } else {
5297 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5298 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005299 return NO_ERROR;
5300 }
5301 case 1019: { // Modify SurfaceFlinger's phase offset
5302 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005303 if (mUseScheduler) {
5304 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5305 } else {
5306 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5307 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005308 return NO_ERROR;
5309 }
Irvel468051e2016-06-13 16:44:44 -07005310 case 1020: { // Layer updates interceptor
5311 n = data.readInt32();
5312 if (n) {
5313 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005314 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005315 }
5316 else{
5317 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005318 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005319 }
5320 return NO_ERROR;
5321 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005322 case 1021: { // Disable HWC virtual displays
5323 n = data.readInt32();
5324 mUseHwcVirtualDisplays = !n;
5325 return NO_ERROR;
5326 }
Romain Guy0147a172017-06-01 13:53:56 -07005327 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005328 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005329 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005330
Chia-I Wu28f320b2018-05-03 11:02:56 -07005331 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005332 return NO_ERROR;
5333 }
Romain Guy54f154a2017-10-24 21:40:32 +01005334 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005335 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005336 invalidateHwcGeometry();
5337 repaintEverything();
5338 return NO_ERROR;
5339 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005340 // Deprecate, use 1030 to check whether the device is color managed.
5341 case 1024: {
5342 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005343 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005344 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005345 n = data.readInt32();
5346 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005347 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005348 mTracing.enable();
5349 doTracing("tracing.enable");
5350 reply->writeInt32(NO_ERROR);
5351 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005352 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005353 status_t err = mTracing.disable();
5354 reply->writeInt32(err);
5355 }
5356 return NO_ERROR;
5357 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005358 case 1026: { // Get layer tracing status
5359 reply->writeBool(mTracing.isEnabled());
5360 return NO_ERROR;
5361 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005362 // Is a DisplayColorSetting supported?
5363 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005364 const auto display = getDefaultDisplayDevice();
5365 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005366 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005367 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005368
5369 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5370 switch (setting) {
5371 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005372 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005373 break;
5374 case DisplayColorSetting::UNMANAGED:
5375 reply->writeBool(true);
5376 break;
5377 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005378 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005379 break;
5380 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005381 reply->writeBool(
5382 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005383 break;
5384 }
5385 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005386 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005387 // Is VrFlinger active?
5388 case 1028: {
5389 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005390 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005391 return NO_ERROR;
5392 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005393 // Is device color managed?
5394 case 1030: {
5395 reply->writeBool(useColorManagement);
5396 return NO_ERROR;
5397 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005398 // Override default composition data space
5399 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5400 // && adb shell stop zygote && adb shell start zygote
5401 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5402 // adb shell stop zygote && adb shell start zygote
5403 case 1031: {
5404 Mutex::Autolock _l(mStateLock);
5405 n = data.readInt32();
5406 if (n) {
5407 n = data.readInt32();
5408 if (n) {
5409 Dataspace dataspace = static_cast<Dataspace>(n);
5410 if (!validateCompositionDataspace(dataspace)) {
5411 return BAD_VALUE;
5412 }
5413 mDefaultCompositionDataspace = dataspace;
5414 }
5415 n = data.readInt32();
5416 if (n) {
5417 Dataspace dataspace = static_cast<Dataspace>(n);
5418 if (!validateCompositionDataspace(dataspace)) {
5419 return BAD_VALUE;
5420 }
5421 mWideColorGamutCompositionDataspace = dataspace;
5422 }
5423 } else {
5424 // restore composition data space.
5425 mDefaultCompositionDataspace = defaultCompositionDataspace;
5426 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5427 }
5428 return NO_ERROR;
5429 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005430 }
5431 }
5432 return err;
5433}
5434
Steven Thomas6d8110b2017-08-31 18:24:21 -07005435void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005436 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005437 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005438}
5439
Ana Krulec7d1d6832018-12-27 11:10:09 -08005440void SurfaceFlinger::repaintEverythingForHWC() {
5441 mRepaintEverything = true;
5442 mEventQueue->invalidateForHWC();
5443}
5444
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005445// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5446class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005447public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005448 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5449 ~WindowDisconnector() {
5450 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005451 }
5452
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005453private:
5454 ANativeWindow* mWindow;
5455 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005456};
5457
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005458status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005459 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5460 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005461 uint32_t reqWidth, uint32_t reqHeight,
5462 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005463 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005464 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005465
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005466 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005467
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005468 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5469
Chia-I Wu20261cb2018-08-23 12:55:44 -07005470 sp<DisplayDevice> display;
5471 {
5472 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005473
Chia-I Wu20261cb2018-08-23 12:55:44 -07005474 display = getDisplayDeviceLocked(displayToken);
5475 if (!display) return BAD_VALUE;
5476
Chia-I Wucb023152018-08-28 12:57:23 -07005477 // set the requested width/height to the logical display viewport size
5478 // by default
5479 if (reqWidth == 0 || reqHeight == 0) {
5480 reqWidth = uint32_t(display->getViewport().width());
5481 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005482 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005483 }
5484
Peiyong Lin0e003c92018-09-17 11:09:51 -07005485 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5486 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005487
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005488 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5489 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005490 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5491 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005492}
5493
5494status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005495 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5496 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005497 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005498 ATRACE_CALL();
5499
5500 class LayerRenderArea : public RenderArea {
5501 public:
Robert Carr578038f2018-03-09 12:25:24 -08005502 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005503 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5504 bool childrenOnly)
5505 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005506 mLayer(layer),
5507 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005508 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005509 mFlinger(flinger),
5510 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005511 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005512 Rect getBounds() const override {
5513 const Layer::State& layerState(mLayer->getDrawingState());
5514 return mLayer->getBufferSize(layerState);
5515 }
Marissa Wall61c58622018-07-18 10:12:20 -07005516 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005517 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005518 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005519 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005520 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005521 }
chaviwa76b2712017-09-20 12:02:26 -07005522 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005523 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005524 Rect getSourceCrop() const override {
5525 if (mCrop.isEmpty()) {
5526 return getBounds();
5527 } else {
5528 return mCrop;
5529 }
5530 }
Robert Carr578038f2018-03-09 12:25:24 -08005531 class ReparentForDrawing {
5532 public:
5533 const sp<Layer>& oldParent;
5534 const sp<Layer>& newParent;
5535
5536 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5537 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005538 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005539 }
Robert Carr15eae092018-03-23 13:43:53 -07005540 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005541 };
5542
5543 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005544 const Rect sourceCrop = getSourceCrop();
5545 // no need to check rotation because there is none
5546 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5547 sourceCrop.height() != getReqHeight();
5548
Robert Carr578038f2018-03-09 12:25:24 -08005549 if (!mChildrenOnly) {
5550 mTransform = mLayer->getTransform().inverse();
5551 drawLayers();
5552 } else {
5553 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005554 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005555 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5556 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005557
5558 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5559 drawLayers();
5560 }
5561 }
chaviwa76b2712017-09-20 12:02:26 -07005562
chaviwa76b2712017-09-20 12:02:26 -07005563 private:
chaviw7206d492017-11-10 16:16:12 -08005564 const sp<Layer> mLayer;
5565 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005566
5567 // In the "childrenOnly" case we reparent the children to a screenshot
5568 // layer which has no properties set and which does not draw.
5569 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005570 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005571 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005572
5573 SurfaceFlinger* mFlinger;
5574 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005575 };
5576
5577 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5578 auto parent = layerHandle->owner.promote();
5579
Robert Carr2e102c92018-10-23 12:11:15 -07005580 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005581 ALOGE("captureLayers called with a removed parent");
5582 return NAME_NOT_FOUND;
5583 }
5584
Robert Carr578038f2018-03-09 12:25:24 -08005585 const int uid = IPCThreadState::self()->getCallingUid();
5586 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005587 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005588 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5589 return PERMISSION_DENIED;
5590 }
5591
chaviw7206d492017-11-10 16:16:12 -08005592 Rect crop(sourceCrop);
5593 if (sourceCrop.width() <= 0) {
5594 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005595 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005596 }
5597
5598 if (sourceCrop.height() <= 0) {
5599 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005600 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005601 }
5602
5603 int32_t reqWidth = crop.width() * frameScale;
5604 int32_t reqHeight = crop.height() * frameScale;
5605
Chia-I Wu20261cb2018-08-23 12:55:44 -07005606 // really small crop or frameScale
5607 if (reqWidth <= 0) {
5608 reqWidth = 1;
5609 }
5610 if (reqHeight <= 0) {
5611 reqHeight = 1;
5612 }
5613
Peiyong Lin0e003c92018-09-17 11:09:51 -07005614 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005615
Robert Carr578038f2018-03-09 12:25:24 -08005616 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005617 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5618 if (!layer->isVisible()) {
5619 return;
Robert Carr578038f2018-03-09 12:25:24 -08005620 } else if (childrenOnly && layer == parent.get()) {
5621 return;
chaviwa76b2712017-09-20 12:02:26 -07005622 }
5623 visitor(layer);
5624 });
5625 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005626 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005627}
5628
5629status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5630 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005631 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005632 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005633 bool useIdentityTransform) {
5634 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005635
Peiyong Lin0e003c92018-09-17 11:09:51 -07005636 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005637 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5638 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005639 *outBuffer =
5640 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5641 static_cast<android_pixel_format>(reqPixelFormat), 1,
5642 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005643
5644 // This mutex protects syncFd and captureResult for communication of the return values from the
5645 // main thread back to this Binder thread
5646 std::mutex captureMutex;
5647 std::condition_variable captureCondition;
5648 std::unique_lock<std::mutex> captureLock(captureMutex);
5649 int syncFd = -1;
5650 std::optional<status_t> captureResult;
5651
Robert Carr03480e22018-01-04 16:02:06 -08005652 const int uid = IPCThreadState::self()->getCallingUid();
5653 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5654
Dominik Laskowski8c001672018-05-30 16:52:06 -07005655 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005656 // If there is a refresh pending, bug out early and tell the binder thread to try again
5657 // after the refresh.
5658 if (mRefreshPending) {
5659 ATRACE_NAME("Skipping screenshot for now");
5660 std::unique_lock<std::mutex> captureLock(captureMutex);
5661 captureResult = std::make_optional<status_t>(EAGAIN);
5662 captureCondition.notify_one();
5663 return;
5664 }
5665
5666 status_t result = NO_ERROR;
5667 int fd = -1;
5668 {
5669 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005670 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005671 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5672 useIdentityTransform, forSystem, &fd);
5673 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005674 }
5675
5676 {
5677 std::unique_lock<std::mutex> captureLock(captureMutex);
5678 syncFd = fd;
5679 captureResult = std::make_optional<status_t>(result);
5680 captureCondition.notify_one();
5681 }
5682 });
5683
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005684 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005685 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005686 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005687 while (*captureResult == EAGAIN) {
5688 captureResult.reset();
5689 result = postMessageAsync(message);
5690 if (result != NO_ERROR) {
5691 return result;
5692 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005693 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005694 }
5695 result = *captureResult;
5696 }
5697
5698 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005699 sync_wait(syncFd, -1);
5700 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005701 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005702
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005703 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005704}
5705
chaviwa76b2712017-09-20 12:02:26 -07005706void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005707 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005708 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5709 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005710 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005711
chaviwa76b2712017-09-20 12:02:26 -07005712 const auto reqWidth = renderArea.getReqWidth();
5713 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005714 const auto sourceCrop = renderArea.getSourceCrop();
5715 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005716
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005717 renderengine::DisplaySettings clientCompositionDisplay;
5718 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005719
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005720 // assume that bounds are never offset, and that they are the same as the
5721 // buffer bounds.
5722 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5723 ui::Transform transform = renderArea.getTransform();
5724 mat4 m;
5725 m[0][0] = transform[0][0];
5726 m[0][1] = transform[0][1];
5727 m[0][3] = transform[0][2];
5728 m[1][0] = transform[1][0];
5729 m[1][1] = transform[1][1];
5730 m[1][3] = transform[1][2];
5731 m[3][0] = transform[2][0];
5732 m[3][1] = transform[2][1];
5733 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005734
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005735 clientCompositionDisplay.globalTransform = m;
5736 mat4 rotMatrix;
5737 // Displacement for repositioning the clipping rectangle after rotating it
5738 // with the rotation hint.
5739 int displacementX = 0;
5740 int displacementY = 0;
5741 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5742 switch (rotation) {
5743 case ui::Transform::ROT_90:
5744 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5745 displacementX = reqWidth;
5746 break;
5747 case ui::Transform::ROT_180:
5748 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5749 displacementX = reqWidth;
5750 displacementY = reqHeight;
5751 break;
5752 case ui::Transform::ROT_270:
5753 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5754 displacementY = reqHeight;
5755 break;
5756 default:
5757 break;
5758 }
5759 // We need to transform the clipping window into the right spot.
5760 // First, rotate the clipping rectangle by the rotation hint to get the
5761 // right orientation
5762 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5763 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5764 const vec4 rotClipTL = rotMatrix * clipTL;
5765 const vec4 rotClipBR = rotMatrix * clipBR;
5766 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5767 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5768 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5769 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5770
5771 // Now reposition the clipping rectangle with the displacement vector
5772 // computed above.
5773 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5774
5775 clientCompositionDisplay.clip =
5776 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5777 newClipRight + displacementX, newClipBottom + displacementY);
5778
5779 // We need to perform the same transformation in layer space, so propagate
5780 // it to the global transform.
5781 mat4 clipTransform = displacementMat * rotMatrix;
5782 clientCompositionDisplay.globalTransform *= clipTransform;
5783 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5784 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005785
chaviw50da5042018-04-09 13:49:37 -07005786 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005787
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005788 renderengine::LayerSettings fillLayer;
5789 fillLayer.source.buffer.buffer = nullptr;
5790 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5791 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5792 fillLayer.alpha = half(alpha);
5793 clientCompositionLayers.push_back(fillLayer);
5794
5795 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005796 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005797 renderengine::LayerSettings layerSettings;
5798 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5799 layerSettings);
5800 if (prepared) {
5801 clientCompositionLayers.push_back(layerSettings);
5802 }
chaviwa76b2712017-09-20 12:02:26 -07005803 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005804
5805 clientCompositionDisplay.clearRegion = clearRegion;
5806 base::unique_fd drawFence;
5807 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
5808 &drawFence);
5809
5810 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005811}
5812
chaviwa76b2712017-09-20 12:02:26 -07005813status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5814 TraverseLayersFunction traverseLayers,
5815 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005816 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005817 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005818 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005819 ATRACE_CALL();
5820
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005821 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005822
5823 traverseLayers([&](Layer* layer) {
5824 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5825 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005826
Robert Carr03480e22018-01-04 16:02:06 -08005827 // We allow the system server to take screenshots of secure layers for
5828 // use in situations like the Screen-rotation animation and place
5829 // the impetus on WindowManager to not persist them.
5830 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005831 ALOGW("FB is protected: PERMISSION_DENIED");
5832 return PERMISSION_DENIED;
5833 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005834 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005835 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005836}
5837
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005838// ---------------------------------------------------------------------------
5839
Dan Stoza412903f2017-04-27 13:42:17 -07005840void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5841 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005842}
5843
Dan Stoza412903f2017-04-27 13:42:17 -07005844void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5845 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005846}
5847
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005848void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005849 const LayerVector::Visitor& visitor) {
5850 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005851 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005852 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005853 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005854 continue;
5855 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005856 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005857 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005858 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005859 return;
5860 }
chaviwa76b2712017-09-20 12:02:26 -07005861 if (!layer->isVisible()) {
5862 return;
5863 }
5864 visitor(layer);
5865 });
5866 }
5867}
5868
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005869}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005870
Lloyd Pique074e8122018-07-26 12:57:23 -07005871
Mathias Agopian3f844832013-08-07 21:24:32 -07005872#if defined(__gl_h_)
5873#error "don't include gl/gl.h in this file"
5874#endif
5875
5876#if defined(__gl2_h_)
5877#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005878#endif