blob: 85411b68d47413651a1baa3b145698b644c6f7ca [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
Dan Stoza84ab9372018-12-17 15:27:57 -08001327status_t SurfaceFlinger::addRegionSamplingListener(
1328 const Rect& /*samplingArea*/, const sp<IBinder>& /*stopLayerHandle*/,
1329 const sp<IRegionSamplingListener>& /*listener*/) {
1330 return NO_ERROR;
1331}
1332
1333status_t SurfaceFlinger::removeRegionSamplingListener(
1334 const sp<IRegionSamplingListener>& /*listener*/) {
1335 return NO_ERROR;
1336}
1337
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001338// ----------------------------------------------------------------------------
1339
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001340sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1341 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001342 auto resyncCallback = makeResyncCallback([this] {
1343 Mutex::Autolock lock(mStateLock);
1344 return getVsyncPeriod();
1345 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001346
Ana Krulec98b5b242018-08-10 15:03:23 -07001347 if (mUseScheduler) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001348 const auto& handle = vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle
1349 : mAppConnectionHandle;
1350
Ady Abrahama1a49af2019-02-07 14:36:55 -08001351 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001352 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001353 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001354 return mSFEventThread->createEventConnection(resyncCallback, ResetIdleTimerCallback());
Ana Krulec98b5b242018-08-10 15:03:23 -07001355 } else {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001356 return mEventThread->createEventConnection(resyncCallback, ResetIdleTimerCallback());
Ana Krulec98b5b242018-08-10 15:03:23 -07001357 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001358 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001359}
1360
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001361// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001362
1363void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001364 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001365}
1366
1367void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001368 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001369}
1370
1371void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001372 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001373}
1374
1375void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001376 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001377 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001378}
1379
1380status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001381 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001382 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001383}
1384
1385status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001386 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001387 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001388 if (res == NO_ERROR) {
1389 msg->wait();
1390 }
1391 return res;
1392}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001393
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001394void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001395 do {
1396 waitForEvent();
1397 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001398}
1399
Dominik Laskowski83b88212018-12-11 13:34:06 -08001400nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001401 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001402 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1403 return 0;
1404 }
1405
1406 const auto config = getHwComposer().getActiveConfig(*displayId);
1407 return config ? config->getVsyncPeriod() : 0;
1408}
1409
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001410void SurfaceFlinger::enableHardwareVsync() {
Ady Abrahamc3e21312019-02-07 14:30:23 -08001411 assert(!mUseScheduler);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001412 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001413 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001414 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001415 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001416 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001417 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001418}
1419
Dominik Laskowski83b88212018-12-11 13:34:06 -08001420void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001421 Mutex::Autolock _l(mHWVsyncLock);
Ady Abraham3aff9172019-02-07 19:10:26 -08001422 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1423 if (mUseScheduler) {
1424 if (makeAvailable) {
Ana Krulec7ab56032018-11-02 20:51:06 +01001425 mScheduler->makeHWSyncAvailable(true);
Ady Abraham3aff9172019-02-07 19:10:26 -08001426 } else if (!mScheduler->getHWSyncAvailable()) {
1427 // Hardware vsync is not currently available, so abort the resync
1428 // attempt for now
1429 return;
Ana Krulec7ab56032018-11-02 20:51:06 +01001430 }
Ady Abraham3aff9172019-02-07 19:10:26 -08001431 } else {
1432 if (makeAvailable) {
1433 mHWVsyncAvailable = true;
1434 } else if (!mHWVsyncAvailable) {
1435 // Hardware vsync is not currently available, so abort the resync
1436 // attempt for now
1437 return;
1438 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001439 }
1440
Dominik Laskowski83b88212018-12-11 13:34:06 -08001441 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001442 return;
1443 }
1444
Ana Krulece588e312018-09-18 12:32:24 -07001445 if (mUseScheduler) {
1446 mScheduler->setVsyncPeriod(period);
1447 } else {
1448 mPrimaryDispSync->reset();
1449 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001450
Ana Krulece588e312018-09-18 12:32:24 -07001451 if (!mPrimaryHWVsyncEnabled) {
1452 mPrimaryDispSync->beginResync();
1453 mEventControlThread->setVsyncEnabled(true);
1454 mPrimaryHWVsyncEnabled = true;
1455 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001456 }
1457}
1458
Jesse Hall948fe0c2013-10-14 12:56:09 -07001459void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Ady Abrahamc3e21312019-02-07 14:30:23 -08001460 assert(!mUseScheduler);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001461 Mutex::Autolock _l(mHWVsyncLock);
1462 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001463 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001464 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001465 mPrimaryHWVsyncEnabled = false;
1466 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001467 if (makeUnavailable) {
1468 mHWVsyncAvailable = false;
1469 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001470}
1471
Dominik Laskowski83b88212018-12-11 13:34:06 -08001472void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001473 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001474
Dan Stoza57164302017-05-08 14:03:54 -07001475 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001476 const nsecs_t last = lastResyncTime.exchange(now);
1477
1478 if (now - last > kIgnoreDelay) {
1479 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001480 }
1481}
1482
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001483void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1484 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001485 ATRACE_NAME("SF onVsync");
1486
Steven Thomas3cfac282017-02-06 12:29:30 -08001487 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001488 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001489 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001490 return;
1491 }
1492
Dominik Laskowski075d3172018-05-24 15:50:06 -07001493 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001494 return;
1495 }
1496
Dominik Laskowski075d3172018-05-24 15:50:06 -07001497 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001498 // For now, we don't do anything with external display vsyncs.
1499 return;
1500 }
1501
Ana Krulece588e312018-09-18 12:32:24 -07001502 if (mUseScheduler) {
1503 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001504 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001505 bool needsHwVsync = false;
1506 { // Scope for the lock
1507 Mutex::Autolock _l(mHWVsyncLock);
1508 if (mPrimaryHWVsyncEnabled) {
1509 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1510 }
1511 }
1512
1513 if (needsHwVsync) {
1514 enableHardwareVsync();
1515 } else {
1516 disableHardwareVsync(false);
1517 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001518 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001519}
1520
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001521void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001522 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1523 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001524}
1525
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001526void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate) {
1527 mPhaseOffsets->setRefreshRateType(refreshRate);
1528
1529 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1530 mVsyncModulator.setPhaseOffsets(early, gl, late);
1531
1532 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001533 return;
1534 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001535
Ana Krulec7d1d6832018-12-27 11:10:09 -08001536 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1537 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1538 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1539 // refresh cycle.
1540
1541 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001542 const nsecs_t currentVsyncPeriod = getVsyncPeriod();
Ana Krulec7d1d6832018-12-27 11:10:09 -08001543 if (currentVsyncPeriod == 0) {
1544 return;
1545 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001546
Ana Krulec7d1d6832018-12-27 11:10:09 -08001547 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1548 // floating numbers.
1549 const float currentFps = 1e9 / currentVsyncPeriod;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001550 const float newFps = refreshRate == RefreshRateType::PERFORMANCE ? kPerformanceRefreshRate
1551 : kDefaultRefreshRate;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001552 if (std::abs(currentFps - newFps) <= 1) {
1553 return;
1554 }
1555
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001556 const auto displayId = getInternalDisplayIdLocked();
1557 LOG_ALWAYS_FATAL_IF(!displayId);
1558
1559 auto configs = getHwComposer().getConfigs(*displayId);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001560 for (int i = 0; i < configs.size(); i++) {
1561 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1562 if (vsyncPeriod == 0) {
1563 continue;
1564 }
1565 const float fps = 1e9 / vsyncPeriod;
1566 // TODO(b/113612090): There should be a better way at determining which config
1567 // has the right refresh rate.
1568 if (std::abs(fps - newFps) <= 1) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001569 setDesiredActiveConfig(getInternalDisplayTokenLocked(), i);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001570 }
1571 }
1572}
1573
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001574void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001575 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001576 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001577 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001578
Lloyd Piqueba04e622017-12-14 17:11:26 -08001579 // Ignore events that do not have the right sequenceId.
1580 if (sequenceId != getBE().mComposerSequenceId) {
1581 return;
1582 }
1583
Steven Thomasb02664d2017-07-26 18:48:28 -07001584 // Only lock if we're not on the main thread. This function is normally
1585 // called on a hwbinder thread, but for the primary display it's called on
1586 // the main thread with the state lock already held, so don't attempt to
1587 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001588 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001589
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001590 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001591
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001592 if (std::this_thread::get_id() == mMainThreadId) {
1593 // Process all pending hot plug events immediately if we are on the main thread.
1594 processDisplayHotplugEventsLocked();
1595 }
1596
Lloyd Piqueba04e622017-12-14 17:11:26 -08001597 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001598}
1599
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001600void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001601 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001602 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001603 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001604 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001605 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001606}
1607
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001608void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001609 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001610 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001611 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001612 getHwComposer().setVsyncEnabled(*displayId,
1613 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1614 }
Mathias Agopian86303202012-07-24 22:46:10 -07001615}
1616
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001617// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001618void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001619 if (mUseScheduler) {
1620 mScheduler->disableHardwareVsync(true);
1621 } else {
1622 disableHardwareVsync(true);
1623 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001624 // Clear the drawing state so that the logic inside of
1625 // handleTransactionLocked will fire. It will determine the delta between
1626 // mCurrentState and mDrawingState and re-apply all changes when we make the
1627 // transition.
1628 mDrawingState.displays.clear();
1629 mDisplays.clear();
1630}
1631
Steven Thomas050b2c82017-03-06 11:45:16 -08001632void SurfaceFlinger::updateVrFlinger() {
1633 if (!mVrFlinger)
1634 return;
1635 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001636 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001637 return;
1638 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001639
Lloyd Pique441d5042018-10-18 16:49:51 -07001640 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001641 ALOGE("Vr flinger is only supported for remote hardware composer"
1642 " service connections. Ignoring request to transition to vr"
1643 " flinger.");
1644 mVrFlingerRequestsDisplay = false;
1645 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001646 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001647
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001648 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001649
Steven Thomas0123ac62018-07-12 11:32:34 -07001650 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001651 LOG_ALWAYS_FATAL_IF(!display);
1652 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001653 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1654 // called below. Clear the reference now so we don't accidentally use it
1655 // later.
1656 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001657
Steven Thomasb02664d2017-07-26 18:48:28 -07001658 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001659 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001660 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001661
Steven Thomasb02664d2017-07-26 18:48:28 -07001662 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001663 // Delete the current instance before creating the new one
1664 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1665 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1666 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1667 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001668
Lloyd Pique441d5042018-10-18 16:49:51 -07001669 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001670 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001671
1672 if (vrFlingerRequestsDisplay) {
1673 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001674 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001675
1676 mVisibleRegionsDirty = true;
1677 invalidateHwcGeometry();
1678
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001679 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001680 display = getDefaultDisplayDeviceLocked();
1681 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001682 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001683
Steven Thomasb02664d2017-07-26 18:48:28 -07001684 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001685 const nsecs_t vsyncPeriod = getVsyncPeriod();
1686 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001687
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001688 // The present fences returned from vr_hwc are not an accurate
1689 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001690 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001691 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1692 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001693 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001694 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001695 !hasSyncFramework);
1696 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001697
Steven Thomasb02664d2017-07-26 18:48:28 -07001698 // Use phase of 0 since phase is not known.
1699 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001700 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001701 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001702
Dominik Laskowski83b88212018-12-11 13:34:06 -08001703 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001704
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001705 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001706 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001707}
1708
Mathias Agopian4fec8732012-06-29 14:12:52 -07001709void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001710 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001711 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001712 case MessageQueue::INVALIDATE: {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001713 if (!updateSetActiveConfigStateMachine()) {
1714 break;
1715 }
1716
Ana Krulec3084c052018-11-21 20:27:17 +01001717 if (mUseScheduler) {
1718 // This call is made each time SF wakes up and creates a new frame.
1719 mScheduler->incrementFrameCounter();
1720 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001721 bool frameMissed = !mHadClientComposition && mPreviousPresentFence != Fence::NO_FENCE &&
1722 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001723 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001724 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001725 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001726 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001727 if (mPropagateBackpressure) {
1728 signalLayerUpdate();
1729 break;
1730 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001731 }
Dan Stoza50182882016-07-08 12:02:20 -07001732
Steven Thomas050b2c82017-03-06 11:45:16 -08001733 // Now that we're going to make it to the handleMessageTransaction()
1734 // call below it's safe to call updateVrFlinger(), which will
1735 // potentially trigger a display handoff.
1736 updateVrFlinger();
1737
Dan Stoza6b9454d2014-11-07 16:00:59 -08001738 bool refreshNeeded = handleMessageTransaction();
1739 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001740
1741 updateCursorAsync();
1742 updateInputFlinger();
1743
Dan Stoza58784442014-12-02 16:58:17 -08001744 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001745 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001746 // Signal a refresh if a transaction modified the window state,
1747 // a new buffer was latched, or if HWC has requested a full
1748 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001749 signalRefresh();
1750 }
1751 break;
1752 }
1753 case MessageQueue::REFRESH: {
1754 handleMessageRefresh();
1755 break;
1756 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001757 }
1758}
1759
Dan Stoza6b9454d2014-11-07 16:00:59 -08001760bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001761 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001762
1763 // Apply any ready transactions in the queues if there are still transactions that have not been
1764 // applied, wake up during the next vsync period and check again
1765 bool transactionNeeded = false;
1766 if (!flushTransactionQueues()) {
1767 transactionNeeded = true;
1768 }
1769
Mathias Agopian4fec8732012-06-29 14:12:52 -07001770 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001771 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001772 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001773
1774 if (transactionNeeded) {
1775 setTransactionFlags(eTransactionNeeded);
1776 }
1777
1778 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001779}
1780
Mathias Agopian4fec8732012-06-29 14:12:52 -07001781void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001782 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001783
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001784 mRefreshPending = false;
1785
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001786 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001787 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001788 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001789 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001790 for (const auto& [token, display] : mDisplays) {
1791 beginFrame(display);
1792 prepareFrame(display);
1793 doDebugFlashRegions(display, repaintEverything);
1794 doComposition(display, repaintEverything);
1795 }
1796
Adrian Roos1e1a1282017-11-01 19:05:31 +01001797 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001798 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001799
1800 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001801 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001802
Dan Stozabfbffeb2016-07-21 14:49:33 -07001803 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001804 for (const auto& [token, displayDevice] : mDisplays) {
1805 auto display = displayDevice->getCompositionDisplay();
1806 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001807 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001808 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001809 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001810
Alec Mouri86770e52018-09-24 22:40:58 +00001811 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001812 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001813 if (mHadClientComposition) {
1814 base::unique_fd flushFence(getRenderEngine().flush());
1815 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1816 getBE().flushFence = new Fence(std::move(flushFence));
1817 } else {
1818 // Cleanup for hygiene.
1819 getBE().flushFence = Fence::NO_FENCE;
1820 }
1821 }
1822
Jorim Jaggi90535212018-05-23 23:44:06 +02001823 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001824
David Sodman7e4ae112018-02-09 15:02:28 -08001825 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001826 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001827 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001828 compositionInfo.hwc.hwcLayer = nullptr;
1829 }
David Sodmanba340492018-08-05 21:51:33 -07001830 }
David Sodman7e4ae112018-02-09 15:02:28 -08001831
1832 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001833}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001834
David Sodmanfa9b2af2017-12-24 13:28:59 -08001835
1836bool SurfaceFlinger::handleMessageInvalidate() {
1837 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001838 bool refreshNeeded = handlePageFlip();
1839
Vishnu Nair4351ad52019-02-11 14:13:02 -08001840 if (mVisibleRegionsDirty) {
1841 computeLayerBounds();
1842 }
1843
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001844 for (auto& layer : mLayersPendingRefresh) {
1845 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001846 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001847 invalidateLayerStack(layer, visibleReg);
1848 }
1849 mLayersPendingRefresh.clear();
1850 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001851}
1852
David Sodman79bba0e2018-08-05 18:07:49 -07001853void SurfaceFlinger::calculateWorkingSet() {
1854 ATRACE_CALL();
1855 ALOGV(__FUNCTION__);
1856
David Sodman79bba0e2018-08-05 18:07:49 -07001857 // build the h/w work list
1858 if (CC_UNLIKELY(mGeometryInvalid)) {
1859 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001860 for (const auto& [token, displayDevice] : mDisplays) {
1861 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001862 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001863 if (!displayId) {
1864 continue;
1865 }
David Sodman79bba0e2018-08-05 18:07:49 -07001866
Lloyd Pique32cbe282018-10-19 13:09:22 -07001867 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001868 for (size_t i = 0; i < currentLayers.size(); i++) {
1869 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001870
Dominik Laskowski075d3172018-05-24 15:50:06 -07001871 if (!layer->hasHwcLayer(*displayId)) {
1872 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1873 layer->forceClientComposition(*displayId);
1874 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001875 }
1876 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001877
Lloyd Pique32cbe282018-10-19 13:09:22 -07001878 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001879 if (mDebugDisableHWC || mDebugRegion) {
1880 layer->forceClientComposition(*displayId);
1881 }
David Sodman79bba0e2018-08-05 18:07:49 -07001882 }
1883 }
1884 }
1885
1886 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001887 for (const auto& [token, displayDevice] : mDisplays) {
1888 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001889 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001890 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001891 continue;
1892 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001893 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001894
1895 if (mDrawingState.colorMatrixChanged) {
1896 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001897 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001898 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001899 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001900 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001901 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1902 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001903 !profile->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001904 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001905 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1906 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001907 !profile->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001908 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001909 }
1910
Peiyong Lind3788632018-09-18 16:01:31 -07001911 // TODO(b/111562338) remove when composer 2.3 is shipped.
1912 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001913 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001914 }
1915
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001916 if (layer->getRoundedCornerState().radius > 0.0f) {
1917 layer->forceClientComposition(*displayId);
1918 }
1919
Dominik Laskowski075d3172018-05-24 15:50:06 -07001920 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001921 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001922 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001923 continue;
1924 }
1925
Lloyd Pique32cbe282018-10-19 13:09:22 -07001926 const auto& displayState = display->getState();
1927 layer->setPerFrameData(*displayId, displayState.transform, displayState.viewport,
1928 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001929 }
1930
Peiyong Lin13effd12018-07-24 17:01:47 -07001931 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001932 ColorMode colorMode;
1933 Dataspace dataSpace;
1934 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001935 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001936 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001937 }
1938 }
1939
1940 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001941
1942 for (const auto& [token, display] : mDisplays) {
1943 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001944 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001945 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001946
1947 if (displayId) {
1948 if (!layer->setHwcLayer(*displayId)) {
1949 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1950 }
1951 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001952 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001953
Dominik Laskowski05275f12018-11-01 15:03:24 -07001954 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001955 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1956 }
1957 }
David Sodman79bba0e2018-08-05 18:07:49 -07001958}
1959
Lloyd Pique32cbe282018-10-19 13:09:22 -07001960void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1961 bool repaintEverything) {
1962 auto display = displayDevice->getCompositionDisplay();
1963 const auto& displayState = display->getState();
1964
Mathias Agopiancd60f992012-08-16 16:28:27 -07001965 // is debugging enabled
1966 if (CC_LIKELY(!mDebugRegion))
1967 return;
1968
Lloyd Pique32cbe282018-10-19 13:09:22 -07001969 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001970 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001971 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001972 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001973 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001974 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001975 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001976
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001977 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001978 }
1979 }
1980
Lloyd Pique32cbe282018-10-19 13:09:22 -07001981 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001982
1983 if (mDebugRegion > 1) {
1984 usleep(mDebugRegion * 1000);
1985 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001986
Lloyd Pique32cbe282018-10-19 13:09:22 -07001987 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001988}
1989
Adrian Roos1e1a1282017-11-01 19:05:31 +01001990void SurfaceFlinger::doTracing(const char* where) {
1991 ATRACE_CALL();
1992 ATRACE_NAME(where);
1993 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001994 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001995 }
1996}
1997
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001998void SurfaceFlinger::logLayerStats() {
1999 ATRACE_CALL();
2000 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002001 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002002 if (display->isPrimary()) {
2003 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07002004 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08002005 }
2006 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07002007
2008 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08002009 }
2010}
2011
David Sodman2b406362017-12-15 13:33:47 -08002012void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002013{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002014 ATRACE_CALL();
2015 ALOGV("preComposition");
2016
David Sodman2b406362017-12-15 13:33:47 -08002017 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
2018
Mathias Agopiancd60f992012-08-16 16:28:27 -07002019 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08002020 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08002021 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002022 needExtraInvalidate = true;
2023 }
Robert Carr2047fae2016-11-28 14:09:09 -08002024 });
2025
Mathias Agopiancd60f992012-08-16 16:28:27 -07002026 if (needExtraInvalidate) {
2027 signalLayerUpdate();
2028 }
2029}
2030
Ana Krulece588e312018-09-18 12:32:24 -07002031void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2032 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002033 // Update queue of past composite+present times and determine the
2034 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002035 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002036 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002037 while (!getBE().mCompositePresentTimes.empty()) {
2038 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002039 // Cached values should have been updated before calling this method,
2040 // which helps avoid duplicate syscalls.
2041 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2042 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2043 break;
2044 }
2045 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002046 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002047 }
2048
2049 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002050 while (getBE().mCompositePresentTimes.size() > 16) {
2051 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002052 }
2053
Ana Krulece588e312018-09-18 12:32:24 -07002054 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002055}
2056
Ana Krulece588e312018-09-18 12:32:24 -07002057void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2058 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002059 // Integer division and modulo round toward 0 not -inf, so we need to
2060 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08002061 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
2062 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
2063 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002064
Ana Krulec757f63a2019-01-25 10:46:18 -08002065 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002066 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002067 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002068 }
2069
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002070 // Snap the latency to a value that removes scheduling jitter from the
2071 // composition and present times, which often have >1ms of jitter.
2072 // Reducing jitter is important if an app attempts to extrapolate
2073 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08002074 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002075 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002076 nsecs_t bias = stats.vsyncPeriod / 2;
2077 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2078 nsecs_t snappedCompositeToPresentLatency =
2079 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002080
David Sodman99974d22017-11-28 12:04:33 -08002081 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002082 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2083 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002084 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002085}
2086
Ady Abraham8164d482019-01-11 14:47:59 -08002087// debug patch for b/119477596 - add stack guards to catch stack
2088// corruptions and disable clang optimizations.
2089// The code below is temporary and planned to be removed once stack
2090// corruptions are found.
2091#pragma clang optimize off
2092class StackGuard {
2093public:
2094 StackGuard(const char* name, const char* func, int line) {
2095 guarders.reserve(MIN_CAPACITY);
2096 guarders.push_back({this, name, func, line});
2097 validate();
2098 }
2099 ~StackGuard() {
2100 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
2101 if (i->guard == this) {
2102 guarders.erase(i);
2103 break;
2104 }
2105 }
2106 }
2107
2108 static void validate() {
2109 for (const auto& guard : guarders) {
2110 if (guard.guard->cookie != COOKIE_VALUE) {
2111 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
2112 CallStack stack(LOG_TAG);
2113 abort();
2114 }
2115 }
2116 }
2117
2118private:
2119 uint64_t cookie = COOKIE_VALUE;
2120 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
2121 static constexpr size_t MIN_CAPACITY = 16;
2122
2123 struct GuarderElement {
2124 StackGuard* guard;
2125 const char* name;
2126 const char* func;
2127 int line;
2128 };
2129
2130 static std::vector<GuarderElement> guarders;
2131};
2132std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2133
2134#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2135
2136#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002137void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002138{
Ady Abraham8164d482019-01-11 14:47:59 -08002139 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002140 ATRACE_CALL();
2141 ALOGV("postComposition");
2142
Brian Anderson3546a3f2016-07-14 11:51:14 -07002143 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002144 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002145 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002146 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002147 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002148 }
Ady Abraham8164d482019-01-11 14:47:59 -08002149 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002150
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002151 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002152 const auto displayDevice = getDefaultDisplayDeviceLocked();
2153 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002154
David Sodman73beded2017-11-15 11:56:06 -08002155 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002156 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002157 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2158
Lloyd Pique32cbe282018-10-19 13:09:22 -07002159 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002160 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002161 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2162 ->getRenderSurface()
2163 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002164 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002165 } else {
2166 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2167 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002168
Ady Abraham8164d482019-01-11 14:47:59 -08002169 ASSERT_ON_STACK_GUARD();
2170
David Sodman73beded2017-11-15 11:56:06 -08002171 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002172 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2173 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002174 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002175 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002176 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002177
Ana Krulece588e312018-09-18 12:32:24 -07002178 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002179 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002180 if (mUseScheduler) {
2181 mScheduler->getDisplayStatInfo(&stats);
2182 } else {
2183 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2184 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2185 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002186
Ady Abraham8164d482019-01-11 14:47:59 -08002187 ASSERT_ON_STACK_GUARD();
2188
David Sodman2b406362017-12-15 13:33:47 -08002189 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002190 // when we started doing work for this frame, but that should be okay
2191 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002192 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002193 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002194 DEFINE_STACK_GUARD(compositorTiming);
2195
Brian Andersond0010582017-03-07 13:20:31 -08002196 {
David Sodman99974d22017-11-28 12:04:33 -08002197 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002198 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002199 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002200
2201 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002202 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002203
Robert Carr2047fae2016-11-28 14:09:09 -08002204 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002205 bool frameLatched =
2206 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2207 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002208 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002209 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002210 recordBufferingStats(layer->getName().string(),
2211 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002212 }
Ady Abraham8164d482019-01-11 14:47:59 -08002213 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002214 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002215
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002216 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002217 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002218 if (mUseScheduler) {
2219 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002220 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002221 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002222 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2223 enableHardwareVsync();
2224 } else {
2225 disableHardwareVsync(false);
2226 }
Ady Abraham8164d482019-01-11 14:47:59 -08002227 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002228 }
2229 }
2230
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002231 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002232 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2233 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002234 if (mUseScheduler) {
2235 mScheduler->enableHardwareVsync();
2236 } else {
2237 enableHardwareVsync();
2238 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002239 }
2240 }
2241
Ady Abraham8164d482019-01-11 14:47:59 -08002242 ASSERT_ON_STACK_GUARD();
2243
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002244 if (mAnimCompositionPending) {
2245 mAnimCompositionPending = false;
2246
Brian Anderson4e606e32017-03-16 15:34:57 -07002247 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002248 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002249 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002250
2251 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002252 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002253 // The HWC doesn't support present fences, so use the refresh
2254 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002255 const nsecs_t presentTime =
2256 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002257 DEFINE_STACK_GUARD(presentTime);
2258
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002259 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002260 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002261 }
2262 mAnimFrameTracker.advanceFrame();
2263 }
Dan Stozab90cf072015-03-05 11:05:59 -08002264
Ady Abraham8164d482019-01-11 14:47:59 -08002265 ASSERT_ON_STACK_GUARD();
2266
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002267 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002268 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002269 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002270 }
2271
Ady Abraham8164d482019-01-11 14:47:59 -08002272 ASSERT_ON_STACK_GUARD();
2273
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002274 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002275
Ady Abraham8164d482019-01-11 14:47:59 -08002276 ASSERT_ON_STACK_GUARD();
2277
Lloyd Pique32cbe282018-10-19 13:09:22 -07002278 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2279 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002280 return;
2281 }
2282
2283 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002284 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002285 if (mHasPoweredOff) {
2286 mHasPoweredOff = false;
2287 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002288 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002289 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002290 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002291 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002292 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2293 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002294 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002295 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002296 }
David Sodman4a36e932017-11-07 14:29:47 -08002297 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002298
2299 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002300 }
David Sodman4a36e932017-11-07 14:29:47 -08002301 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002302 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002303
2304 {
2305 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002306 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002307 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002308 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002309 if (refillCount > 0) {
2310 const size_t offset = mTexturePool.size();
2311 mTexturePool.resize(mTexturePoolSize);
2312 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2313 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2314 }
Ady Abraham8164d482019-01-11 14:47:59 -08002315 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002316 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002317
Marissa Wallfda30bb2018-10-12 11:34:28 -07002318 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002319 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002320
2321 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002322}
Ady Abraham8164d482019-01-11 14:47:59 -08002323#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002324
Vishnu Nair4351ad52019-02-11 14:13:02 -08002325void SurfaceFlinger::computeLayerBounds() {
2326 for (const auto& pair : mDisplays) {
2327 const auto& displayDevice = pair.second;
2328 const auto display = displayDevice->getCompositionDisplay();
2329 for (const auto& layer : mDrawingState.layersSortedByZ) {
2330 // only consider the layers on the given layer stack
2331 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002332 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002333 }
2334
2335 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2336 }
2337 }
2338}
2339
Mathias Agopiancd60f992012-08-16 16:28:27 -07002340void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002341 ATRACE_CALL();
2342 ALOGV("rebuildLayerStacks");
2343
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002344 // We need to clear these out now as these may be holding on to a
2345 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2346 // also holds a reference. When the set of visible layers is recomputed,
2347 // some layers may be destroyed if the only thing keeping them alive was
2348 // that list of visible layers associated with each display. The layer
2349 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2350 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2351 for (const auto& [token, display] : mDisplays) {
2352 getBE().mCompositionInfo[token].clear();
2353 }
2354
Mathias Agopiancd60f992012-08-16 16:28:27 -07002355 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002356 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002357 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002358 mVisibleRegionsDirty = false;
2359 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002360
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002361 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002362 const auto& displayDevice = pair.second;
2363 auto display = displayDevice->getCompositionDisplay();
2364 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002365 Region opaqueRegion;
2366 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002367 compositionengine::Output::OutputLayers layersSortedByZ;
2368 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002369 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002370 const ui::Transform& tr = displayState.transform;
2371 const Rect bounds = displayState.bounds;
2372 if (displayState.isEnabled) {
2373 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002374
Jeff Sharkey76488112017-02-27 14:15:18 -07002375 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002376 auto compositionLayer = layer->getCompositionLayer();
2377 if (compositionLayer == nullptr) {
2378 return;
2379 }
2380
Chia-I Wu83806892017-11-16 10:50:20 -08002381 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002382 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002383 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2384 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2385
Lloyd Piqueef36b002019-01-23 17:52:04 -08002386 if (display->belongsInOutput(layer->getLayerStack(),
2387 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002388 Region drawRegion(tr.transform(
2389 layer->visibleNonTransparentRegion));
2390 drawRegion.andSelf(bounds);
2391 if (!drawRegion.isEmpty()) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002392 layersSortedByZ.emplace_back(
2393 display->getOrCreateOutputLayer(layer->getCompositionLayer(),
2394 layerFE));
2395
2396 deprecated_layersSortedByZ.add(layer);
Jeff Sharkey76488112017-02-27 14:15:18 -07002397 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002398 // Clear out the HWC layer if this layer was
2399 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002400 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002401 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002402 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002403 // WM changes display->layerStack upon sleep/awake.
2404 // Here we make sure we delete the HWC layers even if
2405 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002406 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002407 }
2408
2409 // If a layer is not going to get a release fence because
2410 // it is invisible, but it is also going to release its
2411 // old buffer, add it to the list of layers needing
2412 // fences.
2413 if (hwcLayerDestroyed) {
2414 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2415 mLayersWithQueuedFrames.cend(), layer);
2416 if (found != mLayersWithQueuedFrames.cend()) {
2417 layersNeedingFences.add(layer);
2418 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002419 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002420 });
2421 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002422
2423 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2424
2425 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002426 displayDevice->setLayersNeedingFences(layersNeedingFences);
2427
2428 Region undefinedRegion{bounds};
2429 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2430
2431 display->editState().undefinedRegion = undefinedRegion;
2432 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002433 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002434 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002435}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002436
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002437// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002438// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002439// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002440// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002441// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002442// The returned HDR data space is one of
2443// - Dataspace::UNKNOWN
2444// - Dataspace::BT2020_HLG
2445// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002446Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2447 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002448 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002449 *outHdrDataSpace = Dataspace::UNKNOWN;
2450
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002451 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002452 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002453 case Dataspace::V0_SCRGB:
2454 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002455 case Dataspace::BT2020:
2456 case Dataspace::BT2020_ITU:
2457 case Dataspace::BT2020_LINEAR:
2458 case Dataspace::DISPLAY_BT2020:
2459 bestDataSpace = Dataspace::DISPLAY_BT2020;
2460 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002461 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002462 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002463 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002464 case Dataspace::BT2020_PQ:
2465 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002466 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002467 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002468 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002469 case Dataspace::BT2020_HLG:
2470 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002471 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002472 // When there's mixed PQ content and HLG content, we set the HDR
2473 // data space to be BT2020_PQ and convert HLG to PQ.
2474 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2475 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002476 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002477 break;
2478 default:
2479 break;
2480 }
Romain Guy54f154a2017-10-24 21:40:32 +01002481 }
2482
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002483 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002484}
2485
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002486// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002487void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2488 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002489 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2490 *outMode = ColorMode::NATIVE;
2491 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002492 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002493 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002494 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002495
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002496 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002497 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002498
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002499 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2500
Peiyong Lindfde5112018-06-05 10:58:41 -07002501 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002502 const bool isHdr =
2503 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002504 if (isHdr) {
2505 bestDataSpace = hdrDataSpace;
2506 }
2507
Chia-I Wu0d711262018-05-21 15:19:35 -07002508 RenderIntent intent;
2509 switch (mDisplayColorSetting) {
2510 case DisplayColorSetting::MANAGED:
2511 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002512 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002513 break;
2514 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002515 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002516 break;
2517 default: // vendor display color setting
2518 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2519 break;
2520 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002521
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002522 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002523}
2524
Lloyd Pique32cbe282018-10-19 13:09:22 -07002525void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2526 auto display = displayDevice->getCompositionDisplay();
2527 const auto& displayState = display->getState();
2528
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002529 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002530 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2531 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002532
David Sodmanfa9b2af2017-12-24 13:28:59 -08002533 // If nothing has changed (!dirty), don't recompose.
2534 // If something changed, but we don't currently have any visible layers,
2535 // and didn't when we last did a composition, then skip it this time.
2536 // The second rule does two things:
2537 // - When all layers are removed from a display, we'll emit one black
2538 // frame, then nothing more until we get new layers.
2539 // - When a display is created with a private layer stack, we won't
2540 // emit any black frames until a layer is added to the layer stack.
2541 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002542
Dominik Laskowski075d3172018-05-24 15:50:06 -07002543 const char flagPrefix[] = {'-', '+'};
2544 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002545 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2546 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2547 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2548 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002549
Lloyd Pique31cb2942018-10-19 17:23:03 -07002550 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002551
David Sodmanfa9b2af2017-12-24 13:28:59 -08002552 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002553 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002554 }
2555}
2556
Lloyd Pique32cbe282018-10-19 13:09:22 -07002557void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2558 auto display = displayDevice->getCompositionDisplay();
2559 const auto& displayState = display->getState();
2560
2561 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002562 return;
David Sodman2b406362017-12-15 13:33:47 -08002563 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002564
Lloyd Pique31cb2942018-10-19 17:23:03 -07002565 status_t result = display->getRenderSurface()->prepareFrame(
2566 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002567 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002568 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002569}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002570
Lloyd Pique32cbe282018-10-19 13:09:22 -07002571void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002572 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002573 ALOGV("doComposition");
2574
Lloyd Pique32cbe282018-10-19 13:09:22 -07002575 auto display = displayDevice->getCompositionDisplay();
2576 const auto& displayState = display->getState();
2577
2578 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002579 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002580 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002581
David Sodmanfa9b2af2017-12-24 13:28:59 -08002582 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002583 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002584
Lloyd Pique32cbe282018-10-19 13:09:22 -07002585 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002586 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002587 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002588 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002589}
2590
David Sodmanfa9b2af2017-12-24 13:28:59 -08002591void SurfaceFlinger::postFrame()
2592{
2593 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002594 const auto display = getDefaultDisplayDeviceLocked();
2595 if (display && getHwComposer().isConnected(*display->getId())) {
2596 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002597 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2598 logFrameStats();
2599 }
2600 }
2601}
2602
Lloyd Pique32cbe282018-10-19 13:09:22 -07002603void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002604 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002605 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002606
Lloyd Pique32cbe282018-10-19 13:09:22 -07002607 auto display = displayDevice->getCompositionDisplay();
2608 const auto& displayState = display->getState();
2609 const auto displayId = display->getId();
2610
David Sodmanfa9b2af2017-12-24 13:28:59 -08002611 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002612
Lloyd Pique32cbe282018-10-19 13:09:22 -07002613 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002614 if (displayId) {
2615 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002616 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002617 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002618 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002619 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002620
Chia-I Wu7b549592017-11-15 09:14:57 -08002621 // The layer buffer from the previous frame (if any) is released
2622 // by HWC only when the release fence from this frame (if any) is
2623 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002624 if (displayId && layer->hasHwcLayer(*displayId)) {
2625 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2626 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002627 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002628
2629 // If the layer was client composited in the previous frame, we
2630 // need to merge with the previous client target acquire fence.
2631 // Since we do not track that, always merge with the current
2632 // client target acquire fence when it is available, even though
2633 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002634 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002635 releaseFence =
2636 Fence::merge("LayerRelease", releaseFence,
2637 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002638 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002639
David Sodman15094112018-10-11 09:39:37 -07002640 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002641 }
Chia-I Wu83806892017-11-16 10:50:20 -08002642
2643 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002644 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002645 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002646 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002647 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002648 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002649 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002650 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002651 }
2652 }
2653
Dominik Laskowski075d3172018-05-24 15:50:06 -07002654 if (displayId) {
2655 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002656 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002657 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002658}
2659
Mathias Agopian87baae12012-07-31 12:38:26 -07002660void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002661{
Mathias Agopian841cde52012-03-01 15:44:37 -08002662 ATRACE_CALL();
2663
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002664 // here we keep a copy of the drawing state (that is the state that's
2665 // going to be overwritten by handleTransactionLocked()) outside of
2666 // mStateLock so that the side-effects of the State assignment
2667 // don't happen with mStateLock held (which can cause deadlocks).
2668 State drawingState(mDrawingState);
2669
Mathias Agopianca4d3602011-05-19 15:38:14 -07002670 Mutex::Autolock _l(mStateLock);
2671 const nsecs_t now = systemTime();
2672 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002673
Mathias Agopianca4d3602011-05-19 15:38:14 -07002674 // Here we're guaranteed that some transaction flags are set
2675 // so we can call handleTransactionLocked() unconditionally.
2676 // We call getTransactionFlags(), which will also clear the flags,
2677 // with mStateLock held to guarantee that mCurrentState won't change
2678 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002679
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002680 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002681 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002682 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002683
Mathias Agopianca4d3602011-05-19 15:38:14 -07002684 mLastTransactionTime = systemTime() - now;
2685 mDebugInTransaction = 0;
2686 invalidateHwcGeometry();
2687 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002688}
2689
Lloyd Piqueba04e622017-12-14 17:11:26 -08002690void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2691 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002692 const std::optional<DisplayIdentificationInfo> info =
2693 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002694
Dominik Laskowski075d3172018-05-24 15:50:06 -07002695 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002696 continue;
2697 }
2698
Lloyd Piqueba04e622017-12-14 17:11:26 -08002699 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002700 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002701 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002702 mPhysicalDisplayTokens[info->id] = new BBinder();
2703 DisplayDeviceState state;
2704 state.displayId = info->id;
2705 state.isSecure = true; // All physical displays are currently considered secure.
2706 state.displayName = info->name;
2707 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2708 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002709 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002710 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002711 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002712
Dominik Laskowski075d3172018-05-24 15:50:06 -07002713 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2714 if (index >= 0) {
2715 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2716 mInterceptor->saveDisplayDeletion(state.sequenceId);
2717 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002718 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002719 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002720 }
2721
2722 processDisplayChangesLocked();
2723 }
2724
2725 mPendingHotplugEvents.clear();
2726}
2727
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002728void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002729 if (mUseScheduler) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002730 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2731 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002732 } else {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002733 mEventThread->onHotplugReceived(displayId, connected);
2734 mSFEventThread->onHotplugReceived(displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002735 }
2736}
2737
Lloyd Pique99d3da52018-01-22 17:48:03 -08002738sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002739 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002740 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002741 const sp<IGraphicBufferProducer>& producer) {
2742 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002743 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002744 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002745 creationArgs.isSecure = state.isSecure;
2746 creationArgs.displaySurface = dispSurface;
2747 creationArgs.hasWideColorGamut = false;
2748 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002749
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002750 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002751 creationArgs.isPrimary = isInternalDisplay;
2752
2753 if (useColorManagement && displayId) {
2754 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002755 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002756 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002757 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002758 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002759
Dominik Laskowski7e045462018-05-30 13:02:02 -07002760 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002761 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002762 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002763 }
tangrobin6753a022018-08-10 10:58:54 +08002764 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002765
Dominik Laskowski075d3172018-05-24 15:50:06 -07002766 if (displayId) {
2767 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002768 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002769 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002770 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002771
Lloyd Pique90c115d2018-09-18 21:39:42 -07002772 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002773 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002774 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002775
Lloyd Pique99d3da52018-01-22 17:48:03 -08002776 // Make sure that composition can never be stalled by a virtual display
2777 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002778 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002779 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002780 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2781 }
2782
Dominik Laskowski075d3172018-05-24 15:50:06 -07002783 creationArgs.displayInstallOrientation =
2784 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002785
Lloyd Pique99d3da52018-01-22 17:48:03 -08002786 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002787 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002788
Lloyd Pique90c115d2018-09-18 21:39:42 -07002789 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002790
2791 if (maxFrameBufferAcquiredBuffers >= 3) {
2792 nativeWindowSurface->preallocateBuffers();
2793 }
2794
2795 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002796 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002797 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002798 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002799 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002800 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002801 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2802 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002803 if (!state.isVirtual()) {
2804 LOG_ALWAYS_FATAL_IF(!displayId);
2805 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002806 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002807
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002808 display->setLayerStack(state.layerStack);
2809 display->setProjection(state.orientation, state.viewport, state.frame);
2810 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002811
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002812 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002813}
2814
Lloyd Pique347200f2017-12-14 17:00:15 -08002815void SurfaceFlinger::processDisplayChangesLocked() {
2816 // here we take advantage of Vector's copy-on-write semantics to
2817 // improve performance by skipping the transaction entirely when
2818 // know that the lists are identical
2819 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2820 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2821 if (!curr.isIdenticalTo(draw)) {
2822 mVisibleRegionsDirty = true;
2823 const size_t cc = curr.size();
2824 size_t dc = draw.size();
2825
2826 // find the displays that were removed
2827 // (ie: in drawing state but not in current state)
2828 // also handle displays that changed
2829 // (ie: displays that are in both lists)
2830 for (size_t i = 0; i < dc;) {
2831 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2832 if (j < 0) {
2833 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002834 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002835 // Save display ID before disconnecting.
2836 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002837 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002838
2839 if (!display->isVirtual()) {
2840 LOG_ALWAYS_FATAL_IF(!displayId);
2841 dispatchDisplayHotplugEvent(displayId->value, false);
2842 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002843 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002844
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002845 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002846 } else {
2847 // this display is in both lists. see if something changed.
2848 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002849 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002850 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2851 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2852 if (state_binder != draw_binder) {
2853 // changing the surface is like destroying and
2854 // recreating the DisplayDevice, so we just remove it
2855 // from the drawing state, so that it get re-added
2856 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002857 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002858 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002859 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002860 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002861 mDrawingState.displays.removeItemsAt(i);
2862 dc--;
2863 // at this point we must loop to the next item
2864 continue;
2865 }
2866
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002867 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002868 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002869 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002870 }
2871 if ((state.orientation != draw[i].orientation) ||
2872 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002873 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002874 }
2875 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002876 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002877 }
2878 }
2879 }
2880 ++i;
2881 }
2882
2883 // find displays that were added
2884 // (ie: in current state but not in drawing state)
2885 for (size_t i = 0; i < cc; i++) {
2886 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2887 const DisplayDeviceState& state(curr[i]);
2888
Lloyd Pique542307f2018-10-19 13:24:08 -07002889 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002890 sp<IGraphicBufferProducer> producer;
2891 sp<IGraphicBufferProducer> bqProducer;
2892 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002893 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002894
Dominik Laskowski075d3172018-05-24 15:50:06 -07002895 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002896 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002897 // Virtual displays without a surface are dormant:
2898 // they have external state (layer stack, projection,
2899 // etc.) but no internal state (i.e. a DisplayDevice).
2900 if (state.surface != nullptr) {
2901 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002902 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002903 int width = 0;
2904 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2905 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2906 int height = 0;
2907 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2908 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2909 int intFormat = 0;
2910 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2911 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002912 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002913
Dominik Laskowski075d3172018-05-24 15:50:06 -07002914 displayId =
2915 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002916 }
2917
2918 // TODO: Plumb requested format back up to consumer
2919
2920 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002921 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002922 bqProducer, bqConsumer,
2923 state.displayName);
2924
2925 dispSurface = vds;
2926 producer = vds;
2927 }
2928 } else {
2929 ALOGE_IF(state.surface != nullptr,
2930 "adding a supported display, but rendering "
2931 "surface is provided (%p), ignoring it",
2932 state.surface.get());
2933
Dominik Laskowski075d3172018-05-24 15:50:06 -07002934 displayId = state.displayId;
2935 LOG_ALWAYS_FATAL_IF(!displayId);
2936 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002937 producer = bqProducer;
2938 }
2939
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002940 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002941 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002942 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002943 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002944 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002945 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002946 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002947 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002948 }
2949 }
2950 }
2951 }
2952 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002953
2954 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002955}
2956
Mathias Agopian87baae12012-07-31 12:38:26 -07002957void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002958{
Dan Stoza7dde5992015-05-22 09:51:44 -07002959 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002960 mCurrentState.traverseInZOrder([](Layer* layer) {
2961 layer->notifyAvailableFrames();
2962 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002963
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002964 /*
2965 * Traversal of the children
2966 * (perform the transaction for each of them if needed)
2967 */
2968
Mathias Agopian3559b072012-08-15 13:46:03 -07002969 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002970 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002971 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002972 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002973
2974 const uint32_t flags = layer->doTransaction(0);
2975 if (flags & Layer::eVisibleRegion)
2976 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002977
2978 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002979 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002980 }
Robert Carr2047fae2016-11-28 14:09:09 -08002981 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002982 }
2983
2984 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002985 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002986 */
2987
Mathias Agopiane57f2922012-08-09 16:29:12 -07002988 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002989 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002990 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002991 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002992
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002993 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002994 // The transform hint might have changed for some layers
2995 // (either because a display has changed, or because a layer
2996 // as changed).
2997 //
2998 // Walk through all the layers in currentLayers,
2999 // and update their transform hint.
3000 //
3001 // If a layer is visible only on a single display, then that
3002 // display is used to calculate the hint, otherwise we use the
3003 // default display.
3004 //
3005 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
3006 // the hint is set before we acquire a buffer from the surface texture.
3007 //
3008 // NOTE: layer transactions have taken place already, so we use their
3009 // drawing state. However, SurfaceFlinger's own transaction has not
3010 // happened yet, so we must use the current state layer list
3011 // (soon to become the drawing state list).
3012 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003013 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08003014 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08003015 bool first = true;
3016 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08003017 // NOTE: we rely on the fact that layers are sorted by
3018 // layerStack first (so we don't have to traverse the list
3019 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07003020 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08003021 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08003022 currentlayerStack = layerStack;
3023 // figure out if this layerstack is mirrored
3024 // (more than one display) if so, pick the default display,
3025 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003026 hintDisplay = nullptr;
3027 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08003028 if (display->getCompositionDisplay()
3029 ->belongsInOutput(layer->getLayerStack(),
3030 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003031 if (hintDisplay) {
3032 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08003033 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003034 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003035 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08003036 }
3037 }
3038 }
3039 }
Chet Haase91d25932013-04-11 15:24:55 -07003040
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003041 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003042 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
3043 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08003044
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003045 // could be null when this layer is using a layerStack
3046 // that is not visible on any display. Also can occur at
3047 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003048 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08003049 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003050
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003051 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003052 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003053 if (hintDisplay) {
3054 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08003055 }
Robert Carr2047fae2016-11-28 14:09:09 -08003056
3057 first = false;
3058 });
Mathias Agopian84300952012-11-21 16:02:13 -08003059 }
3060
3061
Mathias Agopian3559b072012-08-15 13:46:03 -07003062 /*
3063 * Perform our own transaction if needed
3064 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07003065
3066 if (mLayersAdded) {
3067 mLayersAdded = false;
3068 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07003069 mVisibleRegionsDirty = true;
3070 }
3071
3072 // some layers might have been removed, so
3073 // we need to update the regions they're exposing.
3074 if (mLayersRemoved) {
3075 mLayersRemoved = false;
3076 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08003077 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003078 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07003079 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07003080 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08003081 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07003082 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07003083 }
Robert Carr2047fae2016-11-28 14:09:09 -08003084 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003085 }
3086
3087 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07003088}
3089
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003090void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003091 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003092 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08003093 return;
3094 }
3095
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003096 if (mVisibleRegionsDirty || mInputInfoChanged) {
3097 mInputInfoChanged = false;
3098 updateInputWindowInfo();
3099 }
3100
3101 executeInputWindowCommands();
3102}
3103
3104void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07003105 Vector<InputWindowInfo> inputHandles;
3106
3107 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
3108 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08003109 // When calculating the screen bounds we ignore the transparent region since it may
3110 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08003111 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07003112 }
3113 });
3114 mInputFlinger->setInputWindows(inputHandles);
3115}
3116
chaviwfbe5d9c2018-12-26 12:23:37 -08003117void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08003118 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3119 if (transferTouchFocusCommand.fromToken != nullptr &&
3120 transferTouchFocusCommand.toToken != nullptr &&
3121 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3122 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3123 transferTouchFocusCommand.toToken);
3124 }
3125 }
3126
3127 mInputWindowCommands.clear();
3128}
3129
Riley Andrews03414a12014-07-01 14:22:59 -07003130void SurfaceFlinger::updateCursorAsync()
3131{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003132 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003133 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003134 continue;
3135 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003136
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003137 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3138 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003139 }
3140 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003141}
3142
chaviw61626f22018-11-15 16:26:27 -08003143void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3144 if (layer->hasReadyFrame()) {
Ady Abrahamc3e21312019-02-07 14:30:23 -08003145 nsecs_t expectedPresentTime;
3146 if (mUseScheduler) {
3147 expectedPresentTime = mScheduler->expectedPresentTime();
3148 } else {
3149 expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3150 }
chaviw61626f22018-11-15 16:26:27 -08003151 if (layer->shouldPresentNow(expectedPresentTime)) {
3152 bool ignored = false;
3153 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3154 }
3155 }
3156 layer->releasePendingBuffer(systemTime());
3157}
3158
Mathias Agopian4fec8732012-06-29 14:12:52 -07003159void SurfaceFlinger::commitTransaction()
3160{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003161 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003162 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003163 for (const auto& l : mLayersPendingRemoval) {
3164 recordBufferingStats(l->getName().string(),
3165 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003166
3167 // We need to release the HWC layers when the Layer is removed
3168 // from the current state otherwise the HWC layer just continues
3169 // showing at its last configured state until we eventually
3170 // abandon the buffer queue.
3171 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003172 l->destroyHwcLayersForAllDisplays();
3173 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003174 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003175 }
3176 mLayersPendingRemoval.clear();
3177 }
3178
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003179 // If this transaction is part of a window animation then the next frame
3180 // we composite should be considered an animation as well.
3181 mAnimCompositionPending = mAnimTransactionPending;
3182
Mathias Agopian4fec8732012-06-29 14:12:52 -07003183 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003184 // clear the "changed" flags in current state
3185 mCurrentState.colorMatrixChanged = false;
3186
Robert Carr1f0a16a2016-10-24 16:27:39 -07003187 mDrawingState.traverseInZOrder([](Layer* layer) {
3188 layer->commitChildList();
3189 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003190 mTransactionPending = false;
3191 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003192 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003193}
3194
Lloyd Pique32cbe282018-10-19 13:09:22 -07003195void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003196 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003197 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003198 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003199
Lloyd Pique32cbe282018-10-19 13:09:22 -07003200 auto display = displayDevice->getCompositionDisplay();
3201
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003202 Region aboveOpaqueLayers;
3203 Region aboveCoveredLayers;
3204 Region dirty;
3205
Mathias Agopian87baae12012-07-31 12:38:26 -07003206 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003207
Robert Carr2047fae2016-11-28 14:09:09 -08003208 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003209 // start with the whole surface at its current location
3210 const Layer::State& s(layer->getDrawingState());
3211
Jesse Hall01e29052013-02-19 16:13:35 -08003212 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003213 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003214 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003215 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003216
Mathias Agopianab028732010-03-16 16:41:46 -07003217 /*
3218 * opaqueRegion: area of a surface that is fully opaque.
3219 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003220 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003221
3222 /*
3223 * visibleRegion: area of a surface that is visible on screen
3224 * and not fully transparent. This is essentially the layer's
3225 * footprint minus the opaque regions above it.
3226 * Areas covered by a translucent surface are considered visible.
3227 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003228 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003229
3230 /*
3231 * coveredRegion: area of a surface that is covered by all
3232 * visible regions above it (which includes the translucent areas).
3233 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003234 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003235
Jesse Halla8026d22012-09-25 13:25:04 -07003236 /*
3237 * transparentRegion: area of a surface that is hinted to be completely
3238 * transparent. This is only used to tell when the layer has no visible
3239 * non-transparent regions and can be removed from the layer list. It
3240 * does not affect the visibleRegion of this layer or any layers
3241 * beneath it. The hint may not be correct if apps don't respect the
3242 * SurfaceView restrictions (which, sadly, some don't).
3243 */
3244 Region transparentRegion;
3245
Mathias Agopianab028732010-03-16 16:41:46 -07003246
3247 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003248 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003249 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003250 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003251
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003252 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003253 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003254 if (!visibleRegion.isEmpty()) {
3255 // Remove the transparent area from the visible region
3256 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003257 if (tr.preserveRects()) {
3258 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003259 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003260 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003261 // transformation too complex, can't do the
3262 // transparent region optimization.
3263 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003264 }
Mathias Agopianab028732010-03-16 16:41:46 -07003265 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003266
Mathias Agopianab028732010-03-16 16:41:46 -07003267 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003268 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003269 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003270 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003271 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003272 // the opaque region is the layer's footprint
3273 opaqueRegion = visibleRegion;
3274 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003275 }
3276 }
3277
Robert Carre5f4f692018-01-12 13:12:28 -08003278 if (visibleRegion.isEmpty()) {
3279 layer->clearVisibilityRegions();
3280 return;
3281 }
3282
Mathias Agopianab028732010-03-16 16:41:46 -07003283 // Clip the covered region to the visible region
3284 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3285
3286 // Update aboveCoveredLayers for next (lower) layer
3287 aboveCoveredLayers.orSelf(visibleRegion);
3288
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003289 // subtract the opaque region covered by the layers above us
3290 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003291
3292 // compute this layer's dirty region
3293 if (layer->contentDirty) {
3294 // we need to invalidate the whole region
3295 dirty = visibleRegion;
3296 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003297 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003298 layer->contentDirty = false;
3299 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003300 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003301 * the exposed region consists of two components:
3302 * 1) what's VISIBLE now and was COVERED before
3303 * 2) what's EXPOSED now less what was EXPOSED before
3304 *
3305 * note that (1) is conservative, we start with the whole
3306 * visible region but only keep what used to be covered by
3307 * something -- which mean it may have been exposed.
3308 *
3309 * (2) handles areas that were not covered by anything but got
3310 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003311 */
Mathias Agopianab028732010-03-16 16:41:46 -07003312 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003313 const Region oldVisibleRegion = layer->visibleRegion;
3314 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003315 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3316 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003317 }
3318 dirty.subtractSelf(aboveOpaqueLayers);
3319
3320 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003321 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003322
Mathias Agopianab028732010-03-16 16:41:46 -07003323 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003324 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003325
Jesse Halla8026d22012-09-25 13:25:04 -07003326 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003327 layer->setVisibleRegion(visibleRegion);
3328 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003329 layer->setVisibleNonTransparentRegion(
3330 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003331 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003332
Mathias Agopian87baae12012-07-31 12:38:26 -07003333 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003334}
3335
Chia-I Wuab0c3192017-08-01 11:29:00 -07003336void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003337 for (const auto& [token, displayDevice] : mDisplays) {
3338 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003339 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003340 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003341 }
3342 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003343}
3344
Daniel Solomon42d04562019-01-20 21:03:19 -08003345void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3346 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3347 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3348 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3349 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3350 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3351 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3352 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3353 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3354 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3355 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3356 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3357 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3358}
3359
Dan Stoza6b9454d2014-11-07 16:00:59 -08003360bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003361{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003362 ALOGV("handlePageFlip");
3363
Brian Andersond6927fb2016-07-23 23:37:30 -07003364 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003365
Mathias Agopian4fec8732012-06-29 14:12:52 -07003366 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003367 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003368 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003369
3370 // Store the set of layers that need updates. This set must not change as
3371 // buffers are being latched, as this could result in a deadlock.
3372 // Example: Two producers share the same command stream and:
3373 // 1.) Layer 0 is latched
3374 // 2.) Layer 0 gets a new frame
3375 // 2.) Layer 1 gets a new frame
3376 // 3.) Layer 1 is latched.
3377 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3378 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003379 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003380 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003381 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003382 nsecs_t expectedPresentTime;
3383 if (mUseScheduler) {
3384 expectedPresentTime = mScheduler->expectedPresentTime();
3385 } else {
3386 expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3387 }
Ana Krulec010d2192018-10-08 06:29:54 -07003388 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003389 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003390 } else {
3391 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003392 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003393 } else {
3394 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003395 }
Robert Carr2047fae2016-11-28 14:09:09 -08003396 });
3397
Lloyd Piquef2c79392018-12-20 16:23:33 -08003398 if (!mLayersWithQueuedFrames.empty()) {
3399 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3400 // writes to Layer current state. See also b/119481871
3401 Mutex::Autolock lock(mStateLock);
3402
3403 for (auto& layer : mLayersWithQueuedFrames) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003404 if (layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence)) {
3405 mLayersPendingRefresh.push_back(layer);
3406 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003407 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003408 if (layer->isBufferLatched()) {
3409 newDataLatched = true;
3410 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003411 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003412 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003413
Alec Mouri86770e52018-09-24 22:40:58 +00003414 // Clear the renderengine fence here...
3415 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3416 // clear instead of sp::clear.
3417 getBE().flushFence = Fence::NO_FENCE;
3418
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003419 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003420
3421 // If we will need to wake up at some time in the future to deal with a
3422 // queued frame that shouldn't be displayed during this vsync period, wake
3423 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003424 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003425 signalLayerUpdate();
3426 }
3427
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003428 // enter boot animation on first buffer latch
3429 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3430 ALOGI("Enter boot animation");
3431 mBootStage = BootStage::BOOTANIMATION;
3432 }
3433
Dan Stoza6b9454d2014-11-07 16:00:59 -08003434 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003435 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003436}
3437
Mathias Agopianad456f92011-01-13 17:53:01 -08003438void SurfaceFlinger::invalidateHwcGeometry()
3439{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003440 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003441}
3442
Lloyd Pique32cbe282018-10-19 13:09:22 -07003443void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003444 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003445 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003446 // We only need to actually compose the display if:
3447 // 1) It is being handled by hardware composer, which may need this to
3448 // keep its virtual display state machine in sync, or
3449 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003450 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003451 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003452 return;
3453 }
3454
Dan Stoza9e56aa02015-11-02 13:00:03 -08003455 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003456 base::unique_fd readyFence;
3457 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003458
3459 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003460 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003461}
3462
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003463bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3464 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003465 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003466 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003467
Lloyd Pique32cbe282018-10-19 13:09:22 -07003468 auto display = displayDevice->getCompositionDisplay();
3469 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003470 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003471
3472 const Region bounds(displayState.bounds);
3473 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003474 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003475 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003476
Peiyong Lind3788632018-09-18 16:01:31 -07003477 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003478 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003479
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003480 renderengine::DisplaySettings clientCompositionDisplay;
3481 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3482 sp<GraphicBuffer> buf;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003483
Dan Stoza9e56aa02015-11-02 13:00:03 -08003484 if (hasClientComposition) {
3485 ALOGV("hasClientComposition");
3486
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003487 buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003488
3489 if (buf == nullptr) {
3490 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3491 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003492 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003493 return false;
3494 }
3495
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003496 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3497 clientCompositionDisplay.clip = displayState.scissor;
3498 const ui::Transform& displayTransform = displayState.transform;
3499 mat4 m;
3500 m[0][0] = displayTransform[0][0];
3501 m[0][1] = displayTransform[0][1];
3502 m[0][3] = displayTransform[0][2];
3503 m[1][0] = displayTransform[1][0];
3504 m[1][1] = displayTransform[1][1];
3505 m[1][3] = displayTransform[1][2];
3506 m[3][0] = displayTransform[2][0];
3507 m[3][1] = displayTransform[2][1];
3508 m[3][3] = displayTransform[2][2];
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003509
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003510 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003511
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003512 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003513 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003514 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003515 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003516 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003517 clientCompositionDisplay.outputDataspace = outputDataspace;
3518 clientCompositionDisplay.maxLuminance =
3519 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003520
Lloyd Pique441d5042018-10-18 16:49:51 -07003521 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003522 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003523 getHwComposer()
3524 .hasDisplayCapability(displayId,
3525 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003526
Peiyong Lind3788632018-09-18 16:01:31 -07003527 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003528 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3529 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003530 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003531 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003532 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003533
Mathias Agopian85d751c2012-08-29 16:59:24 -07003534 /*
3535 * and then, render the layers targeted at the framebuffer
3536 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003537
Dan Stoza9e56aa02015-11-02 13:00:03 -08003538 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003539 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003540 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003541 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003542 const Region viewportRegion(displayState.viewport);
3543 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003544 ALOGV("Layer: %s", layer->getName().string());
3545 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003546 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003547 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003548 case HWC2::Composition::Cursor:
3549 case HWC2::Composition::Device:
3550 case HWC2::Composition::Sideband:
3551 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003552 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003553 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003554 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003555 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003556 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003557 // never clear the very first layer since we're
3558 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003559 renderengine::LayerSettings layerSettings;
3560 Region dummyRegion;
3561 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3562 layerSettings);
3563
3564 if (prepared) {
3565 layerSettings.source.buffer.buffer = nullptr;
3566 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3567 layerSettings.alpha = half(0.0);
3568 layerSettings.disableBlending = true;
3569 clientCompositionLayers.push_back(layerSettings);
3570 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003571 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003572 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003573 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003574 case HWC2::Composition::Client: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003575 renderengine::LayerSettings layerSettings;
3576 bool prepared =
3577 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3578 if (prepared) {
3579 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003580 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003581 break;
3582 }
3583 default:
3584 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003585 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003586 } else {
3587 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003588 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003589 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003590 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003591
Alec Mouri820c7402019-01-23 13:02:39 -08003592 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003593 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003594 clientCompositionDisplay.clearRegion = clearRegion;
3595 if (!debugRegion.isEmpty()) {
3596 Region::const_iterator it = debugRegion.begin();
3597 Region::const_iterator end = debugRegion.end();
3598 while (it != end) {
3599 const Rect& rect = *it++;
3600 renderengine::LayerSettings layerSettings;
3601 layerSettings.source.buffer.buffer = nullptr;
3602 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3603 layerSettings.geometry.boundaries = rect.toFloatRect();
3604 layerSettings.alpha = half(1.0);
3605 clientCompositionLayers.push_back(layerSettings);
3606 }
3607 }
3608 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
3609 buf->getNativeBuffer(), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003610 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003611 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003612}
3613
Chia-I Wu28e3a252018-09-07 12:05:02 -07003614void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003615 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003616 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003617}
3618
Dan Stoza7d89d062015-04-30 13:29:25 -07003619status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003620 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003621 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003622 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003623 const sp<Layer>& parent,
3624 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003625{
Dan Stoza7d89d062015-04-30 13:29:25 -07003626 // add this layer to the current state list
3627 {
3628 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003629 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003630 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3631 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003632 return NO_MEMORY;
3633 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003634 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003635 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003636 } else if (parent == nullptr) {
3637 lbc->onRemovedFromCurrentState();
3638 } else if (parent->isRemovedFromCurrentState()) {
3639 parent->addChild(lbc);
3640 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003641 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003642 parent->addChild(lbc);
3643 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003644
Yiwei Zhang243b3782018-05-15 17:40:04 -07003645 if (gbc != nullptr) {
3646 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3647 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3648 mMaxGraphicBufferProducerListSize,
3649 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3650 mGraphicBufferProducerList.size(),
3651 mMaxGraphicBufferProducerListSize, mNumLayers);
3652 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003653 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003654 }
3655
Mathias Agopian96f08192010-06-02 23:28:45 -07003656 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003657 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003658
Dan Stoza7d89d062015-04-30 13:29:25 -07003659 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003660}
3661
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003662uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003663 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003664}
3665
Mathias Agopian3f844832013-08-07 21:24:32 -07003666uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003667 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003668}
3669
Mathias Agopian3f844832013-08-07 21:24:32 -07003670uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003671 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003672}
3673
3674uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003675 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003676 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003677 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003678 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003679 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003680 }
3681 return old;
3682}
3683
Marissa Wall713b63f2018-10-17 15:42:43 -07003684bool SurfaceFlinger::flushTransactionQueues() {
3685 Mutex::Autolock _l(mStateLock);
3686 auto it = mTransactionQueues.begin();
3687 while (it != mTransactionQueues.end()) {
3688 auto& [applyToken, transactionQueue] = *it;
3689
3690 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003691 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3692 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003693 break;
3694 }
chaviw273171b2018-12-26 11:46:30 -08003695 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003696 transactionQueue.pop();
3697 }
3698
3699 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3700 }
3701 return mTransactionQueues.empty();
3702}
3703
chaviwca27f252018-02-06 16:46:39 -08003704bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3705 for (const ComposerState& state : states) {
3706 // Here we need to check that the interface we're given is indeed
3707 // one of our own. A malicious client could give us a nullptr
3708 // IInterface, or one of its own or even one of our own but a
3709 // different type. All these situations would cause us to crash.
3710 if (state.client == nullptr) {
3711 return true;
3712 }
3713
3714 sp<IBinder> binder = IInterface::asBinder(state.client);
3715 if (binder == nullptr) {
3716 return true;
3717 }
3718
3719 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3720 return true;
3721 }
3722 }
3723 return false;
3724}
3725
Marissa Wall17b4e452018-12-26 16:32:34 -08003726bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3727 const Vector<ComposerState>& states) {
Ady Abrahamc3e21312019-02-07 14:30:23 -08003728 nsecs_t expectedPresentTime;
3729 if (mUseScheduler) {
3730 expectedPresentTime = mScheduler->expectedPresentTime();
3731 } else {
3732 expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3733 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003734 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3735 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3736 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3737 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3738 return false;
3739 }
3740
Marissa Wall713b63f2018-10-17 15:42:43 -07003741 for (const ComposerState& state : states) {
3742 const layer_state_t& s = state.state;
3743 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3744 continue;
3745 }
3746 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003747 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003748 }
3749 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003750 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003751}
3752
3753void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3754 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003755 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003756 const InputWindowCommands& inputWindowCommands,
3757 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003758 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003759 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003760
chaviwca27f252018-02-06 16:46:39 -08003761 if (containsAnyInvalidClientState(states)) {
3762 return;
3763 }
3764
Marissa Wall713b63f2018-10-17 15:42:43 -07003765 // If its TransactionQueue already has a pending TransactionState or if it is pending
3766 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003767 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3768 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003769 setTransactionFlags(eTransactionNeeded);
3770 return;
3771 }
3772
chaviw273171b2018-12-26 11:46:30 -08003773 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003774}
3775
3776void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003777 const Vector<DisplayState>& displays, uint32_t flags,
3778 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003779 uint32_t transactionFlags = 0;
3780
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003781 if (flags & eAnimation) {
3782 // For window updates that are part of an animation we must wait for
3783 // previous animation "frames" to be handled.
3784 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003785 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003786 if (CC_UNLIKELY(err != NO_ERROR)) {
3787 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003788 // caller after a few seconds.
3789 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3790 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003791 mAnimTransactionPending = false;
3792 break;
3793 }
3794 }
3795 }
3796
chaviwca27f252018-02-06 16:46:39 -08003797 for (const DisplayState& display : displays) {
3798 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003799 }
3800
Marissa Walle2ffb422018-10-12 11:33:52 -07003801 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003802 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003803 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003804 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003805 // If the state doesn't require a traversal and there are callbacks, send them now
3806 if (!(clientStateFlags & eTraversalNeeded)) {
3807 mTransactionCompletedThread.sendCallbacks();
3808 }
3809 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003810
chaviw273171b2018-12-26 11:46:30 -08003811 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3812
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003813 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3814 // anyway. This can be used as a flush mechanism for previous async transactions.
3815 // Empty animation transaction can be used to simulate back-pressure, so also force a
3816 // transaction for empty animation transactions.
3817 if (transactionFlags == 0 &&
3818 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003819 transactionFlags = eTransactionNeeded;
3820 }
3821
Mathias Agopian386aa982011-11-07 21:58:03 -08003822 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003823 if (mInterceptor->isEnabled()) {
3824 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003825 }
Irvel468051e2016-06-13 16:44:44 -07003826
Mathias Agopian386aa982011-11-07 21:58:03 -08003827 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003828 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3829 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003830 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003831
3832 // if this is a synchronous transaction, wait for it to take effect
3833 // before returning.
3834 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003835 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003836 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003837 if (flags & eAnimation) {
3838 mAnimTransactionPending = true;
3839 }
3840 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003841 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3842 if (CC_UNLIKELY(err != NO_ERROR)) {
3843 // just in case something goes wrong in SF, return to the
3844 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003845 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3846 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003847 break;
3848 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003849 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003850 }
3851}
3852
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003853uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3854 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3855 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003856
Mathias Agopiane57f2922012-08-09 16:29:12 -07003857 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003858 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3859
3860 const uint32_t what = s.what;
3861 if (what & DisplayState::eSurfaceChanged) {
3862 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3863 state.surface = s.surface;
3864 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003865 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003866 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003867 if (what & DisplayState::eLayerStackChanged) {
3868 if (state.layerStack != s.layerStack) {
3869 state.layerStack = s.layerStack;
3870 flags |= eDisplayTransactionNeeded;
3871 }
3872 }
3873 if (what & DisplayState::eDisplayProjectionChanged) {
3874 if (state.orientation != s.orientation) {
3875 state.orientation = s.orientation;
3876 flags |= eDisplayTransactionNeeded;
3877 }
3878 if (state.frame != s.frame) {
3879 state.frame = s.frame;
3880 flags |= eDisplayTransactionNeeded;
3881 }
3882 if (state.viewport != s.viewport) {
3883 state.viewport = s.viewport;
3884 flags |= eDisplayTransactionNeeded;
3885 }
3886 }
3887 if (what & DisplayState::eDisplaySizeChanged) {
3888 if (state.width != s.width) {
3889 state.width = s.width;
3890 flags |= eDisplayTransactionNeeded;
3891 }
3892 if (state.height != s.height) {
3893 state.height = s.height;
3894 flags |= eDisplayTransactionNeeded;
3895 }
3896 }
3897
Mathias Agopiane57f2922012-08-09 16:29:12 -07003898 return flags;
3899}
3900
Robert Carrd4ae7f32018-06-07 16:10:57 -07003901bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3902 IPCThreadState* ipc = IPCThreadState::self();
3903 const int pid = ipc->getCallingPid();
3904 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003905 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003906 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003907 return false;
3908 }
3909 return true;
3910}
3911
chaviwca27f252018-02-06 16:46:39 -08003912uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3913 const layer_state_t& s = composerState.state;
3914 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3915
Mathias Agopian13127d82013-03-05 17:47:11 -08003916 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003917 if (layer == nullptr) {
3918 return 0;
3919 }
3920
chaviw8b3871a2017-11-01 17:41:01 -07003921 uint32_t flags = 0;
3922
Garfield Tan8a3083e2018-12-03 13:21:07 -08003923 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003924 bool geometryAppliesWithResize =
3925 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003926
3927 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3928 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003929 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003930 layer->pushPendingState();
3931 }
3932
chaviw8b3871a2017-11-01 17:41:01 -07003933 if (what & layer_state_t::ePositionChanged) {
3934 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3935 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003936 }
chaviw8b3871a2017-11-01 17:41:01 -07003937 }
3938 if (what & layer_state_t::eLayerChanged) {
3939 // NOTE: index needs to be calculated before we update the state
3940 const auto& p = layer->getParent();
3941 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003942 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003943 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003944 mCurrentState.layersSortedByZ.removeAt(idx);
3945 mCurrentState.layersSortedByZ.add(layer);
3946 // we need traversal (state changed)
3947 // AND transaction (list changed)
3948 flags |= eTransactionNeeded|eTraversalNeeded;
3949 }
chaviw8b3871a2017-11-01 17:41:01 -07003950 } else {
3951 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003952 flags |= eTransactionNeeded|eTraversalNeeded;
3953 }
3954 }
chaviw8b3871a2017-11-01 17:41:01 -07003955 }
3956 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003957 // NOTE: index needs to be calculated before we update the state
3958 const auto& p = layer->getParent();
3959 if (p == nullptr) {
3960 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3961 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3962 mCurrentState.layersSortedByZ.removeAt(idx);
3963 mCurrentState.layersSortedByZ.add(layer);
3964 // we need traversal (state changed)
3965 // AND transaction (list changed)
3966 flags |= eTransactionNeeded|eTraversalNeeded;
3967 }
3968 } else {
3969 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3970 flags |= eTransactionNeeded|eTraversalNeeded;
3971 }
chaviw8b3871a2017-11-01 17:41:01 -07003972 }
3973 }
3974 if (what & layer_state_t::eSizeChanged) {
3975 if (layer->setSize(s.w, s.h)) {
3976 flags |= eTraversalNeeded;
3977 }
3978 }
3979 if (what & layer_state_t::eAlphaChanged) {
3980 if (layer->setAlpha(s.alpha))
3981 flags |= eTraversalNeeded;
3982 }
3983 if (what & layer_state_t::eColorChanged) {
3984 if (layer->setColor(s.color))
3985 flags |= eTraversalNeeded;
3986 }
Peiyong Lind3788632018-09-18 16:01:31 -07003987 if (what & layer_state_t::eColorTransformChanged) {
3988 if (layer->setColorTransform(s.colorTransform)) {
3989 flags |= eTraversalNeeded;
3990 }
3991 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003992 if (what & layer_state_t::eBackgroundColorChanged) {
3993 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3994 flags |= eTraversalNeeded;
3995 }
3996 }
chaviw8b3871a2017-11-01 17:41:01 -07003997 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003998 // TODO: b/109894387
3999 //
4000 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
4001 // rotation. To see the problem observe that if we have a square parent, and a child
4002 // of the same size, then we rotate the child 45 degrees around it's center, the child
4003 // must now be cropped to a non rectangular 8 sided region.
4004 //
4005 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
4006 // private API, and the WindowManager only uses rotation in one case, which is on a top
4007 // level layer in which cropping is not an issue.
4008 //
4009 // However given that abuse of rotation matrices could lead to surfaces extending outside
4010 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
4011 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
4012 // transformations.
4013 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07004014 flags |= eTraversalNeeded;
4015 }
4016 if (what & layer_state_t::eTransparentRegionChanged) {
4017 if (layer->setTransparentRegionHint(s.transparentRegion))
4018 flags |= eTraversalNeeded;
4019 }
4020 if (what & layer_state_t::eFlagsChanged) {
4021 if (layer->setFlags(s.flags, s.mask))
4022 flags |= eTraversalNeeded;
4023 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004024 if (what & layer_state_t::eCropChanged_legacy) {
4025 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07004026 flags |= eTraversalNeeded;
4027 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004028 if (what & layer_state_t::eCornerRadiusChanged) {
4029 if (layer->setCornerRadius(s.cornerRadius))
4030 flags |= eTraversalNeeded;
4031 }
chaviw8b3871a2017-11-01 17:41:01 -07004032 if (what & layer_state_t::eLayerStackChanged) {
4033 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4034 // We only allow setting layer stacks for top level layers,
4035 // everything else inherits layer stack from its parent.
4036 if (layer->hasParent()) {
4037 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
4038 layer->getName().string());
4039 } else if (idx < 0) {
4040 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
4041 "that also does not appear in the top level layer list. Something"
4042 " has gone wrong.", layer->getName().string());
4043 } else if (layer->setLayerStack(s.layerStack)) {
4044 mCurrentState.layersSortedByZ.removeAt(idx);
4045 mCurrentState.layersSortedByZ.add(layer);
4046 // we need traversal (state changed)
4047 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07004048 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07004049 }
4050 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004051 if (what & layer_state_t::eDeferTransaction_legacy) {
4052 if (s.barrierHandle_legacy != nullptr) {
4053 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
4054 } else if (s.barrierGbp_legacy != nullptr) {
4055 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07004056 if (authenticateSurfaceTextureLocked(gbp)) {
4057 const auto& otherLayer =
4058 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07004059 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07004060 } else {
4061 ALOGE("Attempt to defer transaction to to an"
4062 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08004063 }
4064 }
chaviw8b3871a2017-11-01 17:41:01 -07004065 // We don't trigger a traversal here because if no other state is
4066 // changed, we don't want this to cause any more work
4067 }
4068 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08004069 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07004070 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08004071 if (!hadParent) {
4072 mCurrentState.layersSortedByZ.remove(layer);
4073 }
chaviw8b3871a2017-11-01 17:41:01 -07004074 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08004075 }
chaviw8b3871a2017-11-01 17:41:01 -07004076 }
4077 if (what & layer_state_t::eReparentChildren) {
4078 if (layer->reparentChildren(s.reparentHandle)) {
4079 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07004080 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004081 }
chaviw8b3871a2017-11-01 17:41:01 -07004082 if (what & layer_state_t::eDetachChildren) {
4083 layer->detachChildren();
4084 }
4085 if (what & layer_state_t::eOverrideScalingModeChanged) {
4086 layer->setOverrideScalingMode(s.overrideScalingMode);
4087 // We don't trigger a traversal here because if no other state is
4088 // changed, we don't want this to cause any more work
4089 }
Marissa Wall61c58622018-07-18 10:12:20 -07004090 if (what & layer_state_t::eTransformChanged) {
4091 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4092 }
4093 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4094 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4095 flags |= eTraversalNeeded;
4096 }
4097 if (what & layer_state_t::eCropChanged) {
4098 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4099 }
Marissa Wall861616d2018-10-22 12:52:23 -07004100 if (what & layer_state_t::eFrameChanged) {
4101 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4102 }
Marissa Wall61c58622018-07-18 10:12:20 -07004103 if (what & layer_state_t::eAcquireFenceChanged) {
4104 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4105 }
4106 if (what & layer_state_t::eDataspaceChanged) {
4107 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4108 }
4109 if (what & layer_state_t::eHdrMetadataChanged) {
4110 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4111 }
4112 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4113 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4114 }
4115 if (what & layer_state_t::eApiChanged) {
4116 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4117 }
4118 if (what & layer_state_t::eSidebandStreamChanged) {
4119 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4120 }
Robert Carr720e5062018-07-30 17:45:14 -07004121 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004122 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
4123 layer->setInputInfo(s.inputInfo);
4124 flags |= eTraversalNeeded;
4125 } else {
4126 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4127 }
Robert Carr720e5062018-07-30 17:45:14 -07004128 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004129 if (what & layer_state_t::eMetadataChanged) {
4130 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4131 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004132 std::vector<sp<CallbackHandle>> callbackHandles;
4133 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
4134 mTransactionCompletedThread.run();
4135 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
4136 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4137 }
4138 }
Marissa Wall73411622019-01-25 10:45:41 -08004139
4140 if (what & layer_state_t::eBufferChanged) {
4141 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
4142 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
4143 s.buffer);
4144 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004145 if (what & layer_state_t::eCachedBufferChanged) {
4146 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08004147 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
4148 s.cachedBuffer.bufferId);
Marissa Wallebc2c052019-01-16 19:16:55 -08004149 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4150 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004151 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4152 // Do not put anything that updates layer state or modifies flags after
4153 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004154 return flags;
4155}
4156
chaviw273171b2018-12-26 11:46:30 -08004157uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4158 uint32_t flags = 0;
4159 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4160 flags |= eTraversalNeeded;
4161 }
4162
4163 mInputWindowCommands.merge(inputWindowCommands);
4164 return flags;
4165}
4166
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004167status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4168 uint32_t h, PixelFormat format, uint32_t flags,
4169 LayerMetadata metadata, sp<IBinder>* handle,
4170 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004171 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004172 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004173 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004174 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004175 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004176
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004177 status_t result = NO_ERROR;
4178
4179 sp<Layer> layer;
4180
Cody Northropbc755282017-03-31 12:00:08 -06004181 String8 uniqueName = getUniqueLayerName(name);
4182
Mathias Agopian3165cc22012-08-08 19:42:09 -07004183 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004184 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004185 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4186 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004187
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004188 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004189 case ISurfaceComposerClient::eFXSurfaceBufferState:
4190 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4191 break;
chaviw13fdc492017-06-27 12:40:18 -07004192 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004193 // check if buffer size is set for color layer.
4194 if (w > 0 || h > 0) {
4195 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4196 int(w), int(h));
4197 return BAD_VALUE;
4198 }
4199
chaviw13fdc492017-06-27 12:40:18 -07004200 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004201 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004202 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004203 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004204 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004205 // check if buffer size is set for container layer.
4206 if (w > 0 || h > 0) {
4207 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4208 int(w), int(h));
4209 return BAD_VALUE;
4210 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004211 result = createContainerLayer(client,
4212 uniqueName, w, h, flags,
4213 handle, &layer);
4214 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004215 default:
4216 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004217 break;
4218 }
4219
Dan Stoza7d89d062015-04-30 13:29:25 -07004220 if (result != NO_ERROR) {
4221 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004222 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004223
Chia-I Wuab0c3192017-08-01 11:29:00 -07004224 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4225 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004226 if (metadata.has(METADATA_WINDOW_TYPE)) {
4227 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4228 if (windowType == 441731) {
4229 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4230 layer->setPrimaryDisplayOnly();
4231 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004232 }
4233
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004234 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004235
Robert Carrb89ea9d2018-12-10 13:01:14 -08004236 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4237 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4238 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004239 if (result != NO_ERROR) {
4240 return result;
4241 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004242 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004243
4244 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004245 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004246}
4247
Cody Northropbc755282017-03-31 12:00:08 -06004248String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4249{
4250 bool matchFound = true;
4251 uint32_t dupeCounter = 0;
4252
4253 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4254 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4255
Dan Stoza436ccf32018-06-21 12:10:12 -07004256 // Grab the state lock since we're accessing mCurrentState
4257 Mutex::Autolock lock(mStateLock);
4258
Cody Northropbc755282017-03-31 12:00:08 -06004259 // Loop over layers until we're sure there is no matching name
4260 while (matchFound) {
4261 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004262 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004263 if (layer->getName() == uniqueName) {
4264 matchFound = true;
4265 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4266 }
4267 });
4268 }
4269
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004270 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4271 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004272
4273 return uniqueName;
4274}
4275
Marissa Wallfd668622018-05-10 10:21:13 -07004276status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4277 uint32_t w, uint32_t h, uint32_t flags,
4278 PixelFormat& format, sp<IBinder>* handle,
4279 sp<IGraphicBufferProducer>* gbp,
4280 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004281 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004282 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004283 case PIXEL_FORMAT_TRANSPARENT:
4284 case PIXEL_FORMAT_TRANSLUCENT:
4285 format = PIXEL_FORMAT_RGBA_8888;
4286 break;
4287 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004288 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004289 break;
4290 }
4291
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004292 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004293 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004294 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004295 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004296 *handle = layer->getHandle();
4297 *gbp = layer->getProducer();
4298 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004299 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004300
Marissa Wallfd668622018-05-10 10:21:13 -07004301 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004302 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004303}
4304
Marissa Wall61c58622018-07-18 10:12:20 -07004305status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4306 uint32_t w, uint32_t h, uint32_t flags,
4307 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004308 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004309 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004310 *handle = layer->getHandle();
4311 *outLayer = layer;
4312
4313 return NO_ERROR;
4314}
4315
chaviw13fdc492017-06-27 12:40:18 -07004316status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004317 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004318 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004319{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004320 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004321 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004322 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004323}
4324
Robert Carr6b3f6c52018-08-13 13:05:17 -07004325status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4326 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4327 sp<IBinder>* handle, sp<Layer>* outLayer)
4328{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004329 *outLayer =
4330 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004331 *handle = (*outLayer)->getHandle();
4332 return NO_ERROR;
4333}
4334
4335
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004336void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004337 mLayersPendingRemoval.add(layer);
4338 mLayersRemoved = true;
4339 setTransactionFlags(eTransactionNeeded);
4340}
4341
Robert Carr695d5282018-12-18 15:27:58 -08004342void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004343{
Robert Carr2e102c92018-10-23 12:11:15 -07004344 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004345 // If a layer has a parent, we allow it to out-live it's handle
4346 // with the idea that the parent holds a reference and will eventually
4347 // be cleaned up. However no one cleans up the top-level so we do so
4348 // here.
4349 if (layer->getParent() == nullptr) {
4350 mCurrentState.layersSortedByZ.remove(layer);
4351 }
4352 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004353 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004354}
4355
Mathias Agopianb60314a2012-04-10 22:09:54 -07004356// ---------------------------------------------------------------------------
4357
Andy McFadden13a082e2012-08-24 10:16:42 -07004358void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004359 const auto display = getDefaultDisplayDeviceLocked();
4360 if (!display) return;
4361
4362 const sp<IBinder> token = display->getDisplayToken().promote();
4363 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004364
Jesse Hall01e29052013-02-19 16:13:35 -08004365 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004366 Vector<ComposerState> state;
4367 Vector<DisplayState> displays;
4368 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004369 d.what = DisplayState::eDisplayProjectionChanged |
4370 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004371 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004372 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004373 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004374 d.frame.makeInvalid();
4375 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004376 d.width = 0;
4377 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004378 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004379 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004380
Dominik Laskowskie9774092018-12-11 10:04:24 -08004381 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004382
Dominik Laskowski83b88212018-12-11 13:34:06 -08004383 const nsecs_t vsyncPeriod = getVsyncPeriod();
4384 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004385
Brian Andersond0010582017-03-07 13:20:31 -08004386 // Use phase of 0 since phase is not known.
4387 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004388 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004389 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004390}
4391
4392void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004393 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004394 postMessageAsync(
4395 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004396}
4397
Dominik Laskowskie9774092018-12-11 10:04:24 -08004398void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004399 if (display->isVirtual()) {
4400 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004401 return;
4402 }
4403
Dominik Laskowski075d3172018-05-24 15:50:06 -07004404 const auto displayId = display->getId();
4405 LOG_ALWAYS_FATAL_IF(!displayId);
4406
Dominik Laskowski34157762018-10-31 13:07:19 -07004407 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004408
4409 int currentMode = display->getPowerMode();
4410 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004411 return;
4412 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004413
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004414 display->setPowerMode(mode);
4415
Lloyd Pique4dccc412018-01-22 17:21:36 -08004416 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004417 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004418 }
4419
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004420 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004421 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004422 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004423 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004424 if (mUseScheduler) {
4425 mScheduler->onScreenAcquired(mAppConnectionHandle);
4426 } else {
4427 mEventThread->onScreenAcquired();
4428 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004429 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004430 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004431
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004432 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004433 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004434 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004435
4436 struct sched_param param = {0};
4437 param.sched_priority = 1;
4438 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4439 ALOGW("Couldn't set SCHED_FIFO on display on");
4440 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004441 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004442 // Turn off the display
4443 struct sched_param param = {0};
4444 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4445 ALOGW("Couldn't set SCHED_OTHER on display off");
4446 }
4447
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004448 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004449 if (mUseScheduler) {
4450 mScheduler->disableHardwareVsync(true);
4451 } else {
4452 disableHardwareVsync(true); // also cancels any in-progress resync
4453 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004454 if (mUseScheduler) {
4455 mScheduler->onScreenReleased(mAppConnectionHandle);
4456 } else {
4457 mEventThread->onScreenReleased();
4458 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004459 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004460
Dominik Laskowski075d3172018-05-24 15:50:06 -07004461 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004462 mVisibleRegionsDirty = true;
4463 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004464 } else if (mode == HWC_POWER_MODE_DOZE ||
4465 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004466 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004467 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004468 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004469 if (mUseScheduler) {
4470 mScheduler->onScreenAcquired(mAppConnectionHandle);
4471 } else {
4472 mEventThread->onScreenAcquired();
4473 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004474 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004475 }
4476 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4477 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004478 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004479 if (mUseScheduler) {
4480 mScheduler->disableHardwareVsync(true);
4481 } else {
4482 disableHardwareVsync(true); // also cancels any in-progress resync
4483 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004484 if (mUseScheduler) {
4485 mScheduler->onScreenReleased(mAppConnectionHandle);
4486 } else {
4487 mEventThread->onScreenReleased();
4488 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004489 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004490 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004491 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004492 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004493 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004494 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004495
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004496 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004497 mTimeStats->setPowerMode(mode);
Ana Krulec4593b692019-01-11 22:07:25 -08004498 if (mUseScheduler && mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004499 // Update refresh rate stats.
4500 mRefreshRateStats->setPowerMode(mode);
4501 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004502 }
4503
Dominik Laskowski34157762018-10-31 13:07:19 -07004504 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004505}
4506
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004507void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004508 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004509 const auto display = getDisplayDevice(displayToken);
4510 if (!display) {
4511 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4512 displayToken.get());
4513 } else if (display->isVirtual()) {
4514 ALOGW("Attempt to set power mode %d for virtual display", mode);
4515 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004516 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004517 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004518 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004519}
4520
4521// ---------------------------------------------------------------------------
4522
Dominik Laskowskic2867142019-01-21 11:33:38 -08004523status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4524 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004525 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004526
Mathias Agopianbd115332013-04-18 16:41:04 -07004527 IPCThreadState* ipc = IPCThreadState::self();
4528 const int pid = ipc->getCallingPid();
4529 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004530
Mathias Agopianbd115332013-04-18 16:41:04 -07004531 if ((uid != AID_SHELL) &&
4532 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004533 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4534 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004535 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004536 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004537 // (this would indicate SF is stuck, but we want to be able to
4538 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004539 status_t err = mStateLock.timedLock(s2ns(1));
4540 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004541 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004542 StringAppendF(&result,
4543 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4544 "(no locks held)\n",
4545 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004546 }
4547
Dominik Laskowskic2867142019-01-21 11:33:38 -08004548 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004549
Dominik Laskowskic2867142019-01-21 11:33:38 -08004550 static const std::unordered_map<std::string, Dumper> dumpers = {
4551 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4552 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4553 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004554 {"--dispsync"s, dumper([this](std::string& s) {
4555 if (mUseScheduler) {
4556 mScheduler->dumpPrimaryDispSync(s);
4557 } else {
4558 mPrimaryDispSync->dump(s);
4559 }
4560 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004561 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4562 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
4563 {"--frame-composition"s, dumper(&SurfaceFlinger::dumpFrameCompositionInfo)},
4564 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4565 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4566 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4567 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4568 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4569 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004570 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004571 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4572 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004573
Dominik Laskowskic2867142019-01-21 11:33:38 -08004574 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004575
Dominik Laskowskic2867142019-01-21 11:33:38 -08004576 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4577 (it->second)(args, asProto, result);
4578 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004579 if (asProto) {
4580 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4581 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4582 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004583 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004584 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004585 }
4586
Mathias Agopian9795c422009-08-26 16:36:26 -07004587 if (locked) {
4588 mStateLock.unlock();
4589 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004590 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004591 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004592 return NO_ERROR;
4593}
4594
Dominik Laskowskic2867142019-01-21 11:33:38 -08004595void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004596 mCurrentState.traverseInZOrder(
4597 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004598}
4599
Dominik Laskowskic2867142019-01-21 11:33:38 -08004600void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004601 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004602
Dominik Laskowskic2867142019-01-21 11:33:38 -08004603 if (args.size() > 1) {
4604 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004605 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004606 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004607 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004608 }
Robert Carr2047fae2016-11-28 14:09:09 -08004609 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004610 } else {
4611 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004612 }
4613}
4614
Dominik Laskowskic2867142019-01-21 11:33:38 -08004615void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004616 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004617 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004618 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004619 }
Robert Carr2047fae2016-11-28 14:09:09 -08004620 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004621
Svetoslavd85084b2014-03-20 10:28:31 -07004622 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004623}
4624
Dominik Laskowskic2867142019-01-21 11:33:38 -08004625void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4626 mTimeStats->parseArgs(asProto, args, result);
4627}
4628
Jamie Gennis6547ff42013-07-16 20:12:42 -07004629// This should only be called from the main thread. Otherwise it would need
4630// the lock and should use mCurrentState rather than mDrawingState.
4631void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004632 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004633 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004634 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004635
4636 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4637}
4638
Yiwei Zhang5434a782018-12-05 18:06:32 -08004639void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004640 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004641
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004642 if (isLayerTripleBufferingDisabled())
4643 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004644
Yiwei Zhang5434a782018-12-05 18:06:32 -08004645 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4646 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4647 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4648 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4649 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4650 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004651 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004652}
4653
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004654void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004655 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004656 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004657 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004658 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004659
4660 StringAppendF(&result, "Scheduler: %s\n\n", mUseScheduler ? "enabled" : "disabled");
4661
4662 if (mUseScheduler) {
4663 mScheduler->dump(mAppConnectionHandle, result);
4664 } else {
4665 mEventThread->dump(result);
4666 }
4667}
4668
Yiwei Zhang5434a782018-12-05 18:06:32 -08004669void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4670 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004671 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4672 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004673 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004674 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004675 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004676 }
David Sodman4a36e932017-11-07 14:29:47 -08004677 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004678 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004679 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004680 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4681 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004682}
4683
Dan Stozae77c7662016-05-13 11:37:28 -07004684void SurfaceFlinger::recordBufferingStats(const char* layerName,
4685 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004686 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4687 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004688 for (const auto& segment : history) {
4689 if (!segment.usedThirdBuffer) {
4690 stats.twoBufferTime += segment.totalTime;
4691 }
4692 if (segment.occupancyAverage < 1.0f) {
4693 stats.doubleBufferedTime += segment.totalTime;
4694 } else if (segment.occupancyAverage < 2.0f) {
4695 stats.tripleBufferedTime += segment.totalTime;
4696 }
4697 ++stats.numSegments;
4698 stats.totalTime += segment.totalTime;
4699 }
4700}
4701
Yiwei Zhang5434a782018-12-05 18:06:32 -08004702void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4703 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004704
4705 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4706 const size_t count = currentLayers.size();
4707 for (size_t i=0 ; i<count ; i++) {
4708 currentLayers[i]->dumpFrameEvents(result);
4709 }
4710}
4711
Yiwei Zhang5434a782018-12-05 18:06:32 -08004712void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004713 result.append("Buffering stats:\n");
4714 result.append(" [Layer name] <Active time> <Two buffer> "
4715 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004716 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004717 typedef std::tuple<std::string, float, float, float> BufferTuple;
4718 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004719 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004720 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004721 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004722 if (stats.numSegments == 0) {
4723 continue;
4724 }
4725 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4726 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4727 stats.totalTime;
4728 float doubleBufferRatio = static_cast<float>(
4729 stats.doubleBufferedTime) / stats.totalTime;
4730 float tripleBufferRatio = static_cast<float>(
4731 stats.tripleBufferedTime) / stats.totalTime;
4732 sorted.insert({activeTime, {name, twoBufferRatio,
4733 doubleBufferRatio, tripleBufferRatio}});
4734 }
4735 for (const auto& sortedPair : sorted) {
4736 float activeTime = sortedPair.first;
4737 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004738 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4739 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004740 }
4741 result.append("\n");
4742}
4743
Yiwei Zhang5434a782018-12-05 18:06:32 -08004744void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004745 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004746 const auto displayId = display->getId();
4747 if (!displayId) {
4748 continue;
4749 }
4750 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004751 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004752 continue;
4753 }
4754
Yiwei Zhang5434a782018-12-05 18:06:32 -08004755 StringAppendF(&result,
4756 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4757 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004758 uint8_t port;
4759 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004760 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004761 result.append("no identification data\n");
4762 continue;
4763 }
4764
4765 if (!isEdid(data)) {
4766 result.append("unknown identification data: ");
4767 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004768 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004769 }
4770 result.append("\n");
4771 continue;
4772 }
4773
4774 const auto edid = parseEdid(data);
4775 if (!edid) {
4776 result.append("invalid EDID: ");
4777 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004778 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004779 }
4780 result.append("\n");
4781 continue;
4782 }
4783
Yiwei Zhang5434a782018-12-05 18:06:32 -08004784 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004785 result.append(edid->displayName.data(), edid->displayName.length());
4786 result.append("\"\n");
4787 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004788}
4789
Yiwei Zhang5434a782018-12-05 18:06:32 -08004790void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4791 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4792 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4793 StringAppendF(&result, "DisplayColorSetting: %s\n",
4794 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004795
4796 // TODO: print out if wide-color mode is active or not
4797
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004798 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004799 const auto displayId = display->getId();
4800 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004801 continue;
4802 }
4803
Yiwei Zhang5434a782018-12-05 18:06:32 -08004804 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004805 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004806 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004807 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004808 }
4809
Lloyd Pique32cbe282018-10-19 13:09:22 -07004810 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004811 StringAppendF(&result, " Current color mode: %s (%d)\n",
4812 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004813 }
4814 result.append("\n");
4815}
4816
Yiwei Zhang5434a782018-12-05 18:06:32 -08004817void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004818 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004819 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4820 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004821 continue;
4822 }
4823
Dominik Laskowski05275f12018-11-01 15:03:24 -07004824 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004825 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4826 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004827 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004828 compositionInfo.dump(result, nullptr);
4829 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004830 }
4831 }
David Sodman7e4ae112018-02-09 15:02:28 -08004832}
4833
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004834LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004835 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004836 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4837 const State& state = useDrawing ? mDrawingState : mCurrentState;
4838 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004839 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004840 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004841 });
4842
4843 return layersProto;
4844}
4845
Lloyd Pique32cbe282018-10-19 13:09:22 -07004846LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004847 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004848
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004849 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004850 resolution->set_w(displayDevice.getWidth());
4851 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004852
Lloyd Pique32cbe282018-10-19 13:09:22 -07004853 auto display = displayDevice.getCompositionDisplay();
4854 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004855
Lloyd Pique32cbe282018-10-19 13:09:22 -07004856 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4857 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4858 layersProto.set_global_transform(displayState.orientation);
4859
4860 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004861 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004862 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004863 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004864 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004865 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004866 }
4867 });
4868
4869 return layersProto;
4870}
4871
Dominik Laskowskic2867142019-01-21 11:33:38 -08004872void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4873 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004874 Colorizer colorizer(colorize);
4875
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004876 // figure out if we're stuck somewhere
4877 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004878 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004879 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4880
4881 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004882 * Dump library configuration.
4883 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004884
4885 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004886 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004887 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004888 appendSfConfigString(result);
4889 appendUiConfigString(result);
4890 appendGuiConfigString(result);
4891 result.append("\n");
4892
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004893 result.append("\nDisplay identification data:\n");
4894 dumpDisplayIdentificationData(result);
4895
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004896 result.append("\nWide-Color information:\n");
4897 dumpWideColorInfo(result);
4898
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004899 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004900 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004901 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004902 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004903 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004904
Andy McFadden41d67d72014-04-25 16:58:34 -07004905 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004906 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004907 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004908 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004909 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004910
Dan Stozab90cf072015-03-05 11:05:59 -08004911 dumpStaticScreenStats(result);
4912 result.append("\n");
4913
Yiwei Zhang5434a782018-12-05 18:06:32 -08004914 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004915
Dan Stozae77c7662016-05-13 11:37:28 -07004916 dumpBufferingStats(result);
4917
Andy McFadden4803b742012-09-24 19:07:20 -07004918 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004919 * Dump the visible layer list
4920 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004921 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004922 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4923 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4924 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004925 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004926
Chia-I Wu2f884132018-09-13 15:17:58 -07004927 {
4928 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4929 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004930 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004931 result.append("\n");
4932 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004933
David Sodman7e4ae112018-02-09 15:02:28 -08004934 result.append("\nFrame-Composition information:\n");
4935 dumpFrameCompositionInfo(result);
4936 result.append("\n");
4937
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004938 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004939 * Dump Display state
4940 */
4941
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004942 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004943 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004944 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004945 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004946 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004947 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004948 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004949
4950 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004951 * Dump SurfaceFlinger global state
4952 */
4953
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004954 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004955 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004956 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004957
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004958 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004959
Dominik Laskowski075d3172018-05-24 15:50:06 -07004960 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004961 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4962 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004963 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4964 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004965 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004966 StringAppendF(&result,
4967 " transaction-flags : %08x\n"
4968 " gpu_to_cpu_unsupported : %d\n",
4969 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004970
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004971 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004972 displayId && getHwComposer().isConnected(*displayId)) {
4973 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004974 StringAppendF(&result,
4975 " refresh-rate : %f fps\n"
4976 " x-dpi : %f\n"
4977 " y-dpi : %f\n",
4978 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4979 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004980 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004981
Yiwei Zhang5434a782018-12-05 18:06:32 -08004982 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004983
Dan Stozae22aec72016-08-01 13:20:59 -07004984 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004985 * Tracing state
4986 */
4987 mTracing.dump(result);
4988 result.append("\n");
4989
4990 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004991 * HWC layer minidump
4992 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004993 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004994 const auto displayId = display->getId();
4995 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004996 continue;
4997 }
4998
Yiwei Zhang5434a782018-12-05 18:06:32 -08004999 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07005000 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07005001 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07005002 result.append("\n");
5003 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005004
5005 /*
5006 * Dump HWComposer state
5007 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005008 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005009 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005010 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005011 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005012 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07005013 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005014
5015 /*
5016 * Dump gralloc state
5017 */
5018 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5019 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005020
5021 /*
5022 * Dump VrFlinger state if in use.
5023 */
5024 if (mVrFlingerRequestsDisplay && mVrFlinger) {
5025 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08005026 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005027 result.append("\n");
5028 }
Ana Krulecb43429d2019-01-09 14:28:51 -08005029
5030 /**
5031 * Scheduler dump state.
5032 */
5033 if (mUseScheduler) {
5034 result.append("\nScheduler state:\n");
5035 result.append(mScheduler->doDump() + "\n");
5036 result.append(mRefreshRateStats->doDump() + "\n");
5037 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005038}
5039
Dominik Laskowski075d3172018-05-24 15:50:06 -07005040const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07005041 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005042 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07005043 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005044 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07005045 }
5046 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005047
Dominik Laskowski34157762018-10-31 13:07:19 -07005048 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005049 static const Vector<sp<Layer>> empty;
5050 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07005051}
5052
Chia-I Wu28f320b2018-05-03 11:02:56 -07005053void SurfaceFlinger::updateColorMatrixLocked() {
5054 mat4 colorMatrix;
5055 if (mGlobalSaturationFactor != 1.0f) {
5056 // Rec.709 luma coefficients
5057 float3 luminance{0.213f, 0.715f, 0.072f};
5058 luminance *= 1.0f - mGlobalSaturationFactor;
5059 mat4 saturationMatrix = mat4(
5060 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
5061 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
5062 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
5063 vec4{0.0f, 0.0f, 0.0f, 1.0f}
5064 );
5065 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
5066 } else {
5067 colorMatrix = mClientColorMatrix * mDaltonizer();
5068 }
5069
5070 if (mCurrentState.colorMatrix != colorMatrix) {
5071 mCurrentState.colorMatrix = colorMatrix;
5072 mCurrentState.colorMatrixChanged = true;
5073 setTransactionFlags(eTransactionNeeded);
5074 }
5075}
5076
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005077status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005078#pragma clang diagnostic push
5079#pragma clang diagnostic error "-Wswitch-enum"
5080 switch (static_cast<ISurfaceComposerTag>(code)) {
5081 // These methods should at minimum make sure that the client requested
5082 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005083 case BOOT_FINISHED:
5084 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005085 case CREATE_DISPLAY:
5086 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005087 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005088 case GET_ACTIVE_COLOR_MODE:
5089 case GET_ANIMATION_FRAME_STATS:
5090 case GET_HDR_CAPABILITIES:
5091 case SET_ACTIVE_CONFIG:
5092 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005093 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005094 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005095 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005096 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
5097 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005098 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5099 IPCThreadState* ipc = IPCThreadState::self();
5100 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5101 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005102 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005103 }
Robert Carr1db73f62016-12-21 12:58:51 -08005104 return OK;
5105 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005106 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005107 IPCThreadState* ipc = IPCThreadState::self();
5108 const int pid = ipc->getCallingPid();
5109 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005110 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5111 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005112 return PERMISSION_DENIED;
5113 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005114 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005115 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005116 // Used by apps to hook Choreographer to SurfaceFlinger.
5117 case CREATE_DISPLAY_EVENT_CONNECTION:
5118 // The following calls are currently used by clients that do not
5119 // request necessary permissions. However, they do not expose any secret
5120 // information, so it is OK to pass them.
5121 case AUTHENTICATE_SURFACE:
5122 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005123 case GET_PHYSICAL_DISPLAY_IDS:
5124 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005125 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005126 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005127 case GET_DISPLAY_CONFIGS:
5128 case GET_DISPLAY_STATS:
5129 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5130 // Calling setTransactionState is safe, because you need to have been
5131 // granted a reference to Client* and Handle* to do anything with it.
5132 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005133 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005134 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005135 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005136 case GET_PROTECTED_CONTENT_SUPPORT:
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08005137 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005138 return OK;
5139 }
5140 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08005141 case CAPTURE_SCREEN:
5142 case ADD_REGION_SAMPLING_LISTENER:
5143 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005144 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005145 IPCThreadState* ipc = IPCThreadState::self();
5146 const int pid = ipc->getCallingPid();
5147 const int uid = ipc->getCallingUid();
5148 if ((uid != AID_GRAPHICS) &&
5149 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5150 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5151 return PERMISSION_DENIED;
5152 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005153 return OK;
5154 }
5155 // The following codes are deprecated and should never be allowed to access SF.
5156 case CONNECT_DISPLAY_UNUSED:
5157 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5158 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5159 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005160 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005161 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005162
5163 // These codes are used for the IBinder protocol to either interrogate the recipient
5164 // side of the transaction for its canonical interface descriptor or to dump its state.
5165 // We let them pass by default.
5166 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5167 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5168 code == IBinder::SYSPROPS_TRANSACTION) {
5169 return OK;
5170 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005171 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005172 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005173 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005174 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5175 return OK;
5176 }
5177 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5178 return PERMISSION_DENIED;
5179#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005180}
5181
Ana Krulec13be8ad2018-08-21 02:43:56 +00005182status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5183 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005184 status_t credentialCheck = CheckTransactCodeCredentials(code);
5185 if (credentialCheck != OK) {
5186 return credentialCheck;
5187 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005188
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005189 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5190 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005191 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005192 IPCThreadState* ipc = IPCThreadState::self();
5193 const int uid = ipc->getCallingUid();
5194 if (CC_UNLIKELY(uid != AID_SYSTEM
5195 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005196 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005197 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005198 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005199 return PERMISSION_DENIED;
5200 }
5201 int n;
5202 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005203 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005204 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005205 return NO_ERROR;
5206 case 1002: // SHOW_UPDATES
5207 n = data.readInt32();
5208 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005209 invalidateHwcGeometry();
5210 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005211 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005212 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005213 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005214 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005215 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005216 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005217 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005218 setTransactionFlags(
5219 eTransactionNeeded|
5220 eDisplayTransactionNeeded|
5221 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005222 return NO_ERROR;
5223 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005224 case 1006:{ // send empty update
5225 signalRefresh();
5226 return NO_ERROR;
5227 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005228 case 1008: // toggle use of hw composer
5229 n = data.readInt32();
5230 mDebugDisableHWC = n ? 1 : 0;
5231 invalidateHwcGeometry();
5232 repaintEverything();
5233 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005234 case 1009: // toggle use of transform hint
5235 n = data.readInt32();
5236 mDebugDisableTransformHint = n ? 1 : 0;
5237 invalidateHwcGeometry();
5238 repaintEverything();
5239 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005240 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005241 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005242 reply->writeInt32(0);
5243 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005244 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005245 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005246 return NO_ERROR;
5247 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005248 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005249 if (!display) {
5250 return NAME_NOT_FOUND;
5251 }
5252
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005253 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005254 return NO_ERROR;
5255 }
5256 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005257 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005258 // daltonize
5259 n = data.readInt32();
5260 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005261 case 1:
5262 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5263 break;
5264 case 2:
5265 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5266 break;
5267 case 3:
5268 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5269 break;
5270 default:
5271 mDaltonizer.setType(ColorBlindnessType::None);
5272 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005273 }
5274 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005275 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005276 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005277 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005278 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005279
5280 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005281 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005282 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005283 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005284 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005285 // apply a color matrix
5286 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005287 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005288 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005289 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005290 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005291 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005292 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005293 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005294 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005295 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005296 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005297
5298 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5299 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005300 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005301 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5302 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5303 }
5304
Chia-I Wu28f320b2018-05-03 11:02:56 -07005305 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005306 return NO_ERROR;
5307 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005308 // This is an experimental interface
5309 // Needs to be shifted to proper binder interface when we productize
5310 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005311 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005312 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005313 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005314 return NO_ERROR;
5315 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005316 case 1017: {
5317 n = data.readInt32();
5318 mForceFullDamage = static_cast<bool>(n);
5319 return NO_ERROR;
5320 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005321 case 1018: { // Modify Choreographer's phase offset
5322 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005323 if (mUseScheduler) {
5324 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5325 } else {
5326 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5327 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005328 return NO_ERROR;
5329 }
5330 case 1019: { // Modify SurfaceFlinger's phase offset
5331 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005332 if (mUseScheduler) {
5333 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5334 } else {
5335 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5336 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005337 return NO_ERROR;
5338 }
Irvel468051e2016-06-13 16:44:44 -07005339 case 1020: { // Layer updates interceptor
5340 n = data.readInt32();
5341 if (n) {
5342 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005343 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005344 }
5345 else{
5346 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005347 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005348 }
5349 return NO_ERROR;
5350 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005351 case 1021: { // Disable HWC virtual displays
5352 n = data.readInt32();
5353 mUseHwcVirtualDisplays = !n;
5354 return NO_ERROR;
5355 }
Romain Guy0147a172017-06-01 13:53:56 -07005356 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005357 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005358 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005359
Chia-I Wu28f320b2018-05-03 11:02:56 -07005360 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005361 return NO_ERROR;
5362 }
Romain Guy54f154a2017-10-24 21:40:32 +01005363 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005364 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005365 invalidateHwcGeometry();
5366 repaintEverything();
5367 return NO_ERROR;
5368 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005369 // Deprecate, use 1030 to check whether the device is color managed.
5370 case 1024: {
5371 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005372 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005373 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005374 n = data.readInt32();
5375 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005376 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005377 mTracing.enable();
5378 doTracing("tracing.enable");
5379 reply->writeInt32(NO_ERROR);
5380 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005381 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005382 status_t err = mTracing.disable();
5383 reply->writeInt32(err);
5384 }
5385 return NO_ERROR;
5386 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005387 case 1026: { // Get layer tracing status
5388 reply->writeBool(mTracing.isEnabled());
5389 return NO_ERROR;
5390 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005391 // Is a DisplayColorSetting supported?
5392 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005393 const auto display = getDefaultDisplayDevice();
5394 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005395 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005396 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005397
5398 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5399 switch (setting) {
5400 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005401 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005402 break;
5403 case DisplayColorSetting::UNMANAGED:
5404 reply->writeBool(true);
5405 break;
5406 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005407 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005408 break;
5409 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005410 reply->writeBool(
5411 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005412 break;
5413 }
5414 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005415 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005416 // Is VrFlinger active?
5417 case 1028: {
5418 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005419 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005420 return NO_ERROR;
5421 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005422 // Is device color managed?
5423 case 1030: {
5424 reply->writeBool(useColorManagement);
5425 return NO_ERROR;
5426 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005427 // Override default composition data space
5428 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5429 // && adb shell stop zygote && adb shell start zygote
5430 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5431 // adb shell stop zygote && adb shell start zygote
5432 case 1031: {
5433 Mutex::Autolock _l(mStateLock);
5434 n = data.readInt32();
5435 if (n) {
5436 n = data.readInt32();
5437 if (n) {
5438 Dataspace dataspace = static_cast<Dataspace>(n);
5439 if (!validateCompositionDataspace(dataspace)) {
5440 return BAD_VALUE;
5441 }
5442 mDefaultCompositionDataspace = dataspace;
5443 }
5444 n = data.readInt32();
5445 if (n) {
5446 Dataspace dataspace = static_cast<Dataspace>(n);
5447 if (!validateCompositionDataspace(dataspace)) {
5448 return BAD_VALUE;
5449 }
5450 mWideColorGamutCompositionDataspace = dataspace;
5451 }
5452 } else {
5453 // restore composition data space.
5454 mDefaultCompositionDataspace = defaultCompositionDataspace;
5455 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5456 }
5457 return NO_ERROR;
5458 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005459 }
5460 }
5461 return err;
5462}
5463
Steven Thomas6d8110b2017-08-31 18:24:21 -07005464void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005465 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005466 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005467}
5468
Ana Krulec7d1d6832018-12-27 11:10:09 -08005469void SurfaceFlinger::repaintEverythingForHWC() {
5470 mRepaintEverything = true;
5471 mEventQueue->invalidateForHWC();
5472}
5473
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005474// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5475class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005476public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005477 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5478 ~WindowDisconnector() {
5479 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005480 }
5481
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005482private:
5483 ANativeWindow* mWindow;
5484 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005485};
5486
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005487status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005488 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5489 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005490 uint32_t reqWidth, uint32_t reqHeight,
5491 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005492 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005493 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005494
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005495 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005496
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005497 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5498
Chia-I Wu20261cb2018-08-23 12:55:44 -07005499 sp<DisplayDevice> display;
5500 {
5501 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005502
Chia-I Wu20261cb2018-08-23 12:55:44 -07005503 display = getDisplayDeviceLocked(displayToken);
5504 if (!display) return BAD_VALUE;
5505
Chia-I Wucb023152018-08-28 12:57:23 -07005506 // set the requested width/height to the logical display viewport size
5507 // by default
5508 if (reqWidth == 0 || reqHeight == 0) {
5509 reqWidth = uint32_t(display->getViewport().width());
5510 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005511 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005512 }
5513
Peiyong Lin0e003c92018-09-17 11:09:51 -07005514 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5515 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005516
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005517 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5518 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005519 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5520 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005521}
5522
5523status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005524 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5525 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005526 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005527 ATRACE_CALL();
5528
5529 class LayerRenderArea : public RenderArea {
5530 public:
Robert Carr578038f2018-03-09 12:25:24 -08005531 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005532 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5533 bool childrenOnly)
5534 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005535 mLayer(layer),
5536 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005537 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005538 mFlinger(flinger),
5539 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005540 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005541 Rect getBounds() const override {
5542 const Layer::State& layerState(mLayer->getDrawingState());
5543 return mLayer->getBufferSize(layerState);
5544 }
Marissa Wall61c58622018-07-18 10:12:20 -07005545 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005546 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005547 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005548 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005549 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005550 }
chaviwa76b2712017-09-20 12:02:26 -07005551 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005552 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005553 Rect getSourceCrop() const override {
5554 if (mCrop.isEmpty()) {
5555 return getBounds();
5556 } else {
5557 return mCrop;
5558 }
5559 }
Robert Carr578038f2018-03-09 12:25:24 -08005560 class ReparentForDrawing {
5561 public:
5562 const sp<Layer>& oldParent;
5563 const sp<Layer>& newParent;
5564
Vishnu Nair4351ad52019-02-11 14:13:02 -08005565 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5566 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005567 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005568 // Compute and cache the bounds for the new parent layer.
5569 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005570 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005571 }
Vishnu Nair4351ad52019-02-11 14:13:02 -08005572 ~ReparentForDrawing() { newParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005573 };
5574
5575 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005576 const Rect sourceCrop = getSourceCrop();
5577 // no need to check rotation because there is none
5578 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5579 sourceCrop.height() != getReqHeight();
5580
Robert Carr578038f2018-03-09 12:25:24 -08005581 if (!mChildrenOnly) {
5582 mTransform = mLayer->getTransform().inverse();
5583 drawLayers();
5584 } else {
5585 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005586 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005587 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5588 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005589
Vishnu Nair4351ad52019-02-11 14:13:02 -08005590 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005591 drawLayers();
5592 }
5593 }
chaviwa76b2712017-09-20 12:02:26 -07005594
chaviwa76b2712017-09-20 12:02:26 -07005595 private:
chaviw7206d492017-11-10 16:16:12 -08005596 const sp<Layer> mLayer;
5597 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005598
5599 // In the "childrenOnly" case we reparent the children to a screenshot
5600 // layer which has no properties set and which does not draw.
5601 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005602 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005603 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005604
5605 SurfaceFlinger* mFlinger;
5606 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005607 };
5608
5609 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5610 auto parent = layerHandle->owner.promote();
5611
Robert Carr2e102c92018-10-23 12:11:15 -07005612 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005613 ALOGE("captureLayers called with a removed parent");
5614 return NAME_NOT_FOUND;
5615 }
5616
Robert Carr578038f2018-03-09 12:25:24 -08005617 const int uid = IPCThreadState::self()->getCallingUid();
5618 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005619 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005620 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5621 return PERMISSION_DENIED;
5622 }
5623
chaviw7206d492017-11-10 16:16:12 -08005624 Rect crop(sourceCrop);
5625 if (sourceCrop.width() <= 0) {
5626 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005627 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005628 }
5629
5630 if (sourceCrop.height() <= 0) {
5631 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005632 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005633 }
5634
5635 int32_t reqWidth = crop.width() * frameScale;
5636 int32_t reqHeight = crop.height() * frameScale;
5637
Chia-I Wu20261cb2018-08-23 12:55:44 -07005638 // really small crop or frameScale
5639 if (reqWidth <= 0) {
5640 reqWidth = 1;
5641 }
5642 if (reqHeight <= 0) {
5643 reqHeight = 1;
5644 }
5645
Peiyong Lin0e003c92018-09-17 11:09:51 -07005646 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005647
Robert Carr578038f2018-03-09 12:25:24 -08005648 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005649 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5650 if (!layer->isVisible()) {
5651 return;
Robert Carr578038f2018-03-09 12:25:24 -08005652 } else if (childrenOnly && layer == parent.get()) {
5653 return;
chaviwa76b2712017-09-20 12:02:26 -07005654 }
5655 visitor(layer);
5656 });
5657 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005658 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005659}
5660
5661status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5662 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005663 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005664 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005665 bool useIdentityTransform) {
5666 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005667
Peiyong Lin0e003c92018-09-17 11:09:51 -07005668 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005669 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5670 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005671 *outBuffer =
5672 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5673 static_cast<android_pixel_format>(reqPixelFormat), 1,
5674 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005675
5676 // This mutex protects syncFd and captureResult for communication of the return values from the
5677 // main thread back to this Binder thread
5678 std::mutex captureMutex;
5679 std::condition_variable captureCondition;
5680 std::unique_lock<std::mutex> captureLock(captureMutex);
5681 int syncFd = -1;
5682 std::optional<status_t> captureResult;
5683
Robert Carr03480e22018-01-04 16:02:06 -08005684 const int uid = IPCThreadState::self()->getCallingUid();
5685 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5686
Dominik Laskowski8c001672018-05-30 16:52:06 -07005687 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005688 // If there is a refresh pending, bug out early and tell the binder thread to try again
5689 // after the refresh.
5690 if (mRefreshPending) {
5691 ATRACE_NAME("Skipping screenshot for now");
5692 std::unique_lock<std::mutex> captureLock(captureMutex);
5693 captureResult = std::make_optional<status_t>(EAGAIN);
5694 captureCondition.notify_one();
5695 return;
5696 }
5697
5698 status_t result = NO_ERROR;
5699 int fd = -1;
5700 {
5701 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005702 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005703 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5704 useIdentityTransform, forSystem, &fd);
5705 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005706 }
5707
5708 {
5709 std::unique_lock<std::mutex> captureLock(captureMutex);
5710 syncFd = fd;
5711 captureResult = std::make_optional<status_t>(result);
5712 captureCondition.notify_one();
5713 }
5714 });
5715
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005716 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005717 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005718 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005719 while (*captureResult == EAGAIN) {
5720 captureResult.reset();
5721 result = postMessageAsync(message);
5722 if (result != NO_ERROR) {
5723 return result;
5724 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005725 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005726 }
5727 result = *captureResult;
5728 }
5729
5730 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005731 sync_wait(syncFd, -1);
5732 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005733 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005734
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005735 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005736}
5737
chaviwa76b2712017-09-20 12:02:26 -07005738void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005739 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005740 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5741 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005742 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005743
chaviwa76b2712017-09-20 12:02:26 -07005744 const auto reqWidth = renderArea.getReqWidth();
5745 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005746 const auto sourceCrop = renderArea.getSourceCrop();
5747 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005748
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005749 renderengine::DisplaySettings clientCompositionDisplay;
5750 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005751
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005752 // assume that bounds are never offset, and that they are the same as the
5753 // buffer bounds.
5754 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5755 ui::Transform transform = renderArea.getTransform();
5756 mat4 m;
5757 m[0][0] = transform[0][0];
5758 m[0][1] = transform[0][1];
5759 m[0][3] = transform[0][2];
5760 m[1][0] = transform[1][0];
5761 m[1][1] = transform[1][1];
5762 m[1][3] = transform[1][2];
5763 m[3][0] = transform[2][0];
5764 m[3][1] = transform[2][1];
5765 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005766
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005767 clientCompositionDisplay.globalTransform = m;
5768 mat4 rotMatrix;
5769 // Displacement for repositioning the clipping rectangle after rotating it
5770 // with the rotation hint.
5771 int displacementX = 0;
5772 int displacementY = 0;
5773 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5774 switch (rotation) {
5775 case ui::Transform::ROT_90:
5776 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5777 displacementX = reqWidth;
5778 break;
5779 case ui::Transform::ROT_180:
5780 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5781 displacementX = reqWidth;
5782 displacementY = reqHeight;
5783 break;
5784 case ui::Transform::ROT_270:
5785 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5786 displacementY = reqHeight;
5787 break;
5788 default:
5789 break;
5790 }
5791 // We need to transform the clipping window into the right spot.
5792 // First, rotate the clipping rectangle by the rotation hint to get the
5793 // right orientation
5794 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5795 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5796 const vec4 rotClipTL = rotMatrix * clipTL;
5797 const vec4 rotClipBR = rotMatrix * clipBR;
5798 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5799 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5800 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5801 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5802
5803 // Now reposition the clipping rectangle with the displacement vector
5804 // computed above.
5805 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5806
5807 clientCompositionDisplay.clip =
5808 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5809 newClipRight + displacementX, newClipBottom + displacementY);
5810
5811 // We need to perform the same transformation in layer space, so propagate
5812 // it to the global transform.
5813 mat4 clipTransform = displacementMat * rotMatrix;
5814 clientCompositionDisplay.globalTransform *= clipTransform;
5815 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5816 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005817
chaviw50da5042018-04-09 13:49:37 -07005818 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005819
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005820 renderengine::LayerSettings fillLayer;
5821 fillLayer.source.buffer.buffer = nullptr;
5822 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5823 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5824 fillLayer.alpha = half(alpha);
5825 clientCompositionLayers.push_back(fillLayer);
5826
5827 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005828 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005829 renderengine::LayerSettings layerSettings;
5830 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5831 layerSettings);
5832 if (prepared) {
5833 clientCompositionLayers.push_back(layerSettings);
5834 }
chaviwa76b2712017-09-20 12:02:26 -07005835 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005836
5837 clientCompositionDisplay.clearRegion = clearRegion;
5838 base::unique_fd drawFence;
5839 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
5840 &drawFence);
5841
5842 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005843}
5844
chaviwa76b2712017-09-20 12:02:26 -07005845status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5846 TraverseLayersFunction traverseLayers,
5847 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005848 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005849 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005850 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005851 ATRACE_CALL();
5852
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005853 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005854
5855 traverseLayers([&](Layer* layer) {
5856 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5857 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005858
Robert Carr03480e22018-01-04 16:02:06 -08005859 // We allow the system server to take screenshots of secure layers for
5860 // use in situations like the Screen-rotation animation and place
5861 // the impetus on WindowManager to not persist them.
5862 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005863 ALOGW("FB is protected: PERMISSION_DENIED");
5864 return PERMISSION_DENIED;
5865 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005866 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005867 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005868}
5869
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005870// ---------------------------------------------------------------------------
5871
Dan Stoza412903f2017-04-27 13:42:17 -07005872void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5873 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005874}
5875
Dan Stoza412903f2017-04-27 13:42:17 -07005876void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5877 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005878}
5879
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005880void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005881 const LayerVector::Visitor& visitor) {
5882 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005883 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005884 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005885 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005886 continue;
5887 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005888 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005889 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005890 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005891 return;
5892 }
chaviwa76b2712017-09-20 12:02:26 -07005893 if (!layer->isVisible()) {
5894 return;
5895 }
5896 visitor(layer);
5897 });
5898 }
5899}
5900
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005901}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005902
Lloyd Pique074e8122018-07-26 12:57:23 -07005903
Mathias Agopian3f844832013-08-07 21:24:32 -07005904#if defined(__gl_h_)
5905#error "don't include gl/gl.h in this file"
5906#endif
5907
5908#if defined(__gl2_h_)
5909#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005910#endif