blob: 23eeb368eb4f748090e158d1956c692944f74acd [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
Lloyd Pique90c115d2018-09-18 21:39:42 -0700354 mPrimaryDispSync =
355 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
356 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700357
Daniel Solomon42d04562019-01-20 21:03:19 -0800358 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
359 if (surfaceFlingerConfigsServiceV1_2) {
360 surfaceFlingerConfigsServiceV1_2->getDisplayNativePrimaries(
361 [&](auto tmpPrimaries) {
362 memcpy(&mInternalDisplayPrimaries, &tmpPrimaries, sizeof(ui::DisplayPrimaries));
363 });
364 } else {
365 initDefaultDisplayNativePrimaries();
366 }
367
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800368 // debugging stuff...
369 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700370
Mathias Agopianb4b17302013-03-20 18:36:41 -0700371 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700372 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700373
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800374 property_get("debug.sf.showupdates", value, "0");
375 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700376
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700377 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000378
379 // DDMS debugging deprecated (b/120782499)
380 property_get("debug.sf.ddms", value, "0");
381 int debugDdms = atoi(value);
382 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700383
384 property_get("debug.sf.disable_backpressure", value, "0");
385 mPropagateBackpressure = !atoi(value);
386 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700387
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800388 property_get("debug.sf.enable_hwc_vds", value, "0");
389 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800390 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800391
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800392 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800393 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800394 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700395
Yiwei Zhang243b3782018-05-15 17:40:04 -0700396 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700397 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
398 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
399
Ana Krulec98b5b242018-08-10 15:03:23 -0700400 property_get("debug.sf.use_scheduler", value, "0");
401 mUseScheduler = atoi(value);
402
Ana Krulec757f63a2019-01-25 10:46:18 -0800403 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
404 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700405
Romain Guy11d63f42017-07-20 12:47:14 -0700406 // We should be reading 'persist.sys.sf.color_saturation' here
407 // but since /data may be encrypted, we need to wait until after vold
408 // comes online to attempt to read the property. The property is
409 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800410
411 if (useTrebleTestingOverride()) {
412 // Without the override SurfaceFlinger cannot connect to HIDL
413 // services that are not listed in the manifests. Considered
414 // deriving the setting from the set service name, but it
415 // would be brittle if the name that's not 'default' is used
416 // for production purposes later on.
417 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
418 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800419}
420
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800421void SurfaceFlinger::onFirstRef()
422{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800423 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800424}
425
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800426SurfaceFlinger::~SurfaceFlinger()
427{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800428}
429
Dan Stozac7014012014-02-14 15:03:43 -0800430void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800431{
432 // the window manager died on us. prepare its eulogy.
433
Andy McFadden13a082e2012-08-24 10:16:42 -0700434 // restore initial conditions (default device unblank, etc)
435 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800436
437 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700438 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800439}
440
Robert Carr1db73f62016-12-21 12:58:51 -0800441static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700442 status_t err = client->initCheck();
443 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800444 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800445 }
Robert Carr1db73f62016-12-21 12:58:51 -0800446 return nullptr;
447}
448
449sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
450 return initClient(new Client(this));
451}
452
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700453sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
454 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700455{
456 class DisplayToken : public BBinder {
457 sp<SurfaceFlinger> flinger;
458 virtual ~DisplayToken() {
459 // no more references, this display must be terminated
460 Mutex::Autolock _l(flinger->mStateLock);
461 flinger->mCurrentState.displays.removeItem(this);
462 flinger->setTransactionFlags(eDisplayTransactionNeeded);
463 }
464 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700465 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700466 : flinger(flinger) {
467 }
468 };
469
470 sp<BBinder> token = new DisplayToken(this);
471
472 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700473 // Display ID is assigned when virtual display is allocated by HWC.
474 DisplayDeviceState state;
475 state.isSecure = secure;
476 state.displayName = displayName;
477 mCurrentState.displays.add(token, state);
478 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700479 return token;
480}
481
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700482void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700483 Mutex::Autolock _l(mStateLock);
484
Dominik Laskowski075d3172018-05-24 15:50:06 -0700485 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
486 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700487 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700488 return;
489 }
490
Dominik Laskowski075d3172018-05-24 15:50:06 -0700491 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
492 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700493 ALOGE("destroyDisplay called for non-virtual display");
494 return;
495 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700496 mInterceptor->saveDisplayDeletion(state.sequenceId);
497 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700498 setTransactionFlags(eDisplayTransactionNeeded);
499}
500
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800501std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
502 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700503
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800504 const auto internalDisplayId = getInternalDisplayIdLocked();
505 if (!internalDisplayId) {
506 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700507 }
508
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800509 std::vector<PhysicalDisplayId> displayIds;
510 displayIds.reserve(mPhysicalDisplayTokens.size());
511 displayIds.push_back(internalDisplayId->value);
512
513 for (const auto& [id, token] : mPhysicalDisplayTokens) {
514 if (id != *internalDisplayId) {
515 displayIds.push_back(id.value);
516 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700517 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700518
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800519 return displayIds;
520}
521
522sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
523 Mutex::Autolock lock(mStateLock);
524 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700525}
526
Ady Abraham37965d42018-11-01 13:43:32 -0700527status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
528 if (!outGetColorManagement) {
529 return BAD_VALUE;
530 }
531 *outGetColorManagement = useColorManagement;
532 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700533}
534
Lloyd Pique441d5042018-10-18 16:49:51 -0700535HWComposer& SurfaceFlinger::getHwComposer() const {
536 return mCompositionEngine->getHwComposer();
537}
538
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700539renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
540 return mCompositionEngine->getRenderEngine();
541}
542
Lloyd Pique70d91362018-10-18 16:02:55 -0700543compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
544 return *mCompositionEngine.get();
545}
546
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800547void SurfaceFlinger::bootFinished()
548{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700549 if (mStartPropertySetThread->join() != NO_ERROR) {
550 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800551 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800552 const nsecs_t now = systemTime();
553 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000554 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700555
556 // wait patiently for the window manager death
557 const String16 name("window");
558 sp<IBinder> window(defaultServiceManager()->getService(name));
559 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700560 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700561 }
Robert Carr720e5062018-07-30 17:45:14 -0700562 sp<IBinder> input(defaultServiceManager()->getService(
563 String16("inputflinger")));
564 if (input == nullptr) {
565 ALOGE("Failed to link to input service");
566 } else {
567 mInputFlinger = interface_cast<IInputFlinger>(input);
568 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700569
Steven Thomas050b2c82017-03-06 11:45:16 -0800570 if (mVrFlinger) {
571 mVrFlinger->OnBootFinished();
572 }
573
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700574 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700575 // formerly we would just kill the process, but we now ask it to exit so it
576 // can choose where to stop the animation.
577 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700578
579 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
580 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
581 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700582
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800583 postMessageAsync(new LambdaMessage([this] {
584 readPersistentProperties();
585 mBootStage = BootStage::FINISHED;
586 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800587}
588
Dan Stoza436ccf32018-06-21 12:10:12 -0700589uint32_t SurfaceFlinger::getNewTexture() {
590 {
591 std::lock_guard lock(mTexturePoolMutex);
592 if (!mTexturePool.empty()) {
593 uint32_t name = mTexturePool.back();
594 mTexturePool.pop_back();
595 ATRACE_INT("TexturePoolSize", mTexturePool.size());
596 return name;
597 }
598
599 // The pool was too small, so increase it for the future
600 ++mTexturePoolSize;
601 }
602
603 // The pool was empty, so we need to get a new texture name directly using a
604 // blocking call to the main thread
605 uint32_t name = 0;
606 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
607 return name;
608}
609
Mathias Agopian3f844832013-08-07 21:24:32 -0700610void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700611 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700612}
613
Wei Wangf9b05ee2017-07-19 20:59:39 -0700614// Do not call property_set on main thread which will be blocked by init
615// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700616void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700617 ALOGI( "SurfaceFlinger's main thread ready to run. "
618 "Initializing graphics H/W...");
619
Ana Krulec757f63a2019-01-25 10:46:18 -0800620 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900621
Steven Thomasb02664d2017-07-26 18:48:28 -0700622 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800623
Dominik Laskowski83b88212018-12-11 13:34:06 -0800624 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -0800625
Steven Thomasb02664d2017-07-26 18:48:28 -0700626 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700627 if (mUseScheduler) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800628 mScheduler = getFactory().createScheduler(
629 [this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
630
Ana Krulec757f63a2019-01-25 10:46:18 -0800631 // TODO(b/113612090): Currently we assume that if scheduler is turned on, then the refresh
632 // rate is 90. Once b/122905403 is completed, this should be updated accordingly.
633 mPhaseOffsets->setRefreshRateType(
634 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700635
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800636 auto resetIdleTimerCallback =
637 std::bind(&SurfaceFlinger::setRefreshRateTo, this, RefreshRateType::PERFORMANCE);
638
Ana Krulec98b5b242018-08-10 15:03:23 -0700639 mAppConnectionHandle =
Ana Krulec757f63a2019-01-25 10:46:18 -0800640 mScheduler->createConnection("appConnection", mPhaseOffsets->getCurrentAppOffset(),
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800641 resyncCallback, resetIdleTimerCallback,
Ana Krulec98b5b242018-08-10 15:03:23 -0700642 impl::EventThread::InterceptVSyncsCallback());
643 mSfConnectionHandle =
Ana Krulec757f63a2019-01-25 10:46:18 -0800644 mScheduler->createConnection("sfConnection", mPhaseOffsets->getCurrentSfOffset(),
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800645 resyncCallback, resetIdleTimerCallback,
646 [this](nsecs_t timestamp) {
Ana Krulec98b5b242018-08-10 15:03:23 -0700647 mInterceptor->saveVSyncEvent(timestamp);
648 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800649
Ana Krulec98b5b242018-08-10 15:03:23 -0700650 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700651 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
652 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700653 } else {
654 mEventThreadSource =
655 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800656 mPhaseOffsets->getCurrentAppOffset(), true, "app");
Ana Krulec98b5b242018-08-10 15:03:23 -0700657 mEventThread =
658 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700659 impl::EventThread::InterceptVSyncsCallback(),
660 "appEventThread");
661 mSfEventThreadSource =
662 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800663 mPhaseOffsets->getCurrentSfOffset(), true, "sf");
Ana Krulec98b5b242018-08-10 15:03:23 -0700664
665 mSFEventThread =
666 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700667 [this](nsecs_t timestamp) {
668 mInterceptor->saveVSyncEvent(timestamp);
669 },
670 "sfEventThread");
Dominik Laskowskif654d572018-12-20 11:03:06 -0800671 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Ana Krulec98b5b242018-08-10 15:03:23 -0700672 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
673 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800674
Steven Thomasb02664d2017-07-26 18:48:28 -0700675 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700676 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700677 renderEngineFeature |= (useColorManagement ?
678 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700679 renderEngineFeature |= (useContextPriority ?
680 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700681
682 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700683 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700684 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700685 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700686
687 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
688 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700689 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
690 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800691 // Process any initial hotplug and resulting display changes.
692 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700693 const auto display = getDefaultDisplayDeviceLocked();
694 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700695 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700696 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800697
Steven Thomas050b2c82017-03-06 11:45:16 -0800698 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700699 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700700 // This callback is called from the vr flinger dispatch thread. We
701 // need to call signalTransaction(), which requires holding
702 // mStateLock when we're not on the main thread. Acquiring
703 // mStateLock from the vr flinger dispatch thread might trigger a
704 // deadlock in surface flinger (see b/66916578), so post a message
705 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700706 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700707 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
708 mVrFlingerRequestsDisplay = requestDisplay;
709 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700710 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800711 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700712 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
713 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700714 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700715 .value_or(0),
716 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800717 if (!mVrFlinger) {
718 ALOGE("Failed to start vrflinger");
719 }
720 }
721
Lloyd Pique90c115d2018-09-18 21:39:42 -0700722 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800723 [this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
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 });
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800748
Alec Mourifb571ea2019-01-24 18:42:10 -0800749 mRefreshRateStats =
750 std::make_unique<scheduler::RefreshRateStats>(getHwComposer().getConfigs(
751 *display->getId()),
752 mTimeStats);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800753 }
754
Dan Stoza9e56aa02015-11-02 13:00:03 -0800755 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700756}
757
Romain Guy11d63f42017-07-20 12:47:14 -0700758void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700759 Mutex::Autolock _l(mStateLock);
760
Romain Guy11d63f42017-07-20 12:47:14 -0700761 char value[PROPERTY_VALUE_MAX];
762
763 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800764 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700765 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800766 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100767
768 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700769 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700770}
771
Mathias Agopiana67e4182012-06-19 17:26:12 -0700772void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800773 // Start boot animation service by setting a property mailbox
774 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700775 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800776 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700777 if (mStartPropertySetThread->join() != NO_ERROR) {
778 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800779 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700780}
781
Mathias Agopian875d8e12013-06-07 15:35:48 -0700782size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700783 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700784}
785
Mathias Agopian875d8e12013-06-07 15:35:48 -0700786size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700787 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700788}
789
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800790// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800791
Jamie Gennis582270d2011-08-17 18:19:00 -0700792bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800793 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800794 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800795 return authenticateSurfaceTextureLocked(bufferProducer);
796}
797
798bool SurfaceFlinger::authenticateSurfaceTextureLocked(
799 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800800 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800801 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800802}
803
Brian Anderson6b376712017-04-04 10:51:39 -0700804status_t SurfaceFlinger::getSupportedFrameTimestamps(
805 std::vector<FrameEvent>* outSupported) const {
806 *outSupported = {
807 FrameEvent::REQUESTED_PRESENT,
808 FrameEvent::ACQUIRE,
809 FrameEvent::LATCH,
810 FrameEvent::FIRST_REFRESH_START,
811 FrameEvent::LAST_REFRESH_START,
812 FrameEvent::GPU_COMPOSITION_DONE,
813 FrameEvent::DEQUEUE_READY,
814 FrameEvent::RELEASE,
815 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700816 ConditionalLock _l(mStateLock,
817 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700818 if (!getHwComposer().hasCapability(
819 HWC2::Capability::PresentFenceIsNotReliable)) {
820 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
821 }
822 return NO_ERROR;
823}
824
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800825status_t SurfaceFlinger::getDisplayConfigsLocked(const sp<IBinder>& displayToken,
826 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700827 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700828 return BAD_VALUE;
829 }
830
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800831 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700832 if (!displayId) {
833 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700834 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835
Mathias Agopian8b736f12012-08-13 17:54:26 -0700836 // TODO: Not sure if display density should handled by SF any longer
837 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700838 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700839 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700840 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800841 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700842 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700843 }
844 return density;
845 }
846 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700847 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700848 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700849 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700850 return getDensityFromProperty("ro.sf.lcd_density"); }
851 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700852
Dan Stoza7f7da322014-05-02 15:26:25 -0700853 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700854
Dominik Laskowski075d3172018-05-24 15:50:06 -0700855 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700856 DisplayInfo info = DisplayInfo();
857
Dan Stoza9e56aa02015-11-02 13:00:03 -0800858 float xdpi = hwConfig->getDpiX();
859 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700860
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700861 info.w = hwConfig->getWidth();
862 info.h = hwConfig->getHeight();
863 // Default display viewport to display width and height
864 info.viewportW = info.w;
865 info.viewportH = info.h;
866
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800867 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700868 // The density of the device is provided by a build property
869 float density = Density::getBuildDensity() / 160.0f;
870 if (density == 0) {
871 // the build doesn't provide a density -- this is wrong!
872 // use xdpi instead
873 ALOGE("ro.sf.lcd_density must be defined as a build property");
874 density = xdpi / 160.0f;
875 }
876 if (Density::getEmuDensity()) {
877 // if "qemu.sf.lcd_density" is specified, it overrides everything
878 xdpi = ydpi = density = Density::getEmuDensity();
879 density /= 160.0f;
880 }
881 info.density = density;
882
883 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700884 const auto display = getDefaultDisplayDeviceLocked();
885 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700886
887 // This is for screenrecord
888 const Rect viewport = display->getViewport();
889 if (viewport.isValid()) {
890 info.viewportW = uint32_t(viewport.getWidth());
891 info.viewportH = uint32_t(viewport.getHeight());
892 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700893 } else {
894 // TODO: where should this value come from?
895 static const int TV_DENSITY = 213;
896 info.density = TV_DENSITY / 160.0f;
897 info.orientation = 0;
898 }
899
Dan Stoza7f7da322014-05-02 15:26:25 -0700900 info.xdpi = xdpi;
901 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800902 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800903 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800904
Andy McFadden91b2ca82014-06-13 14:04:23 -0700905 // This is how far in advance a buffer must be queued for
906 // presentation at a given time. If you want a buffer to appear
907 // on the screen at time N, you must submit the buffer before
908 // (N - presentationDeadline).
909 //
910 // Normally it's one full refresh period (to give SF a chance to
911 // latch the buffer), but this can be reduced by configuring a
912 // DispSync offset. Any additional delays introduced by the hardware
913 // composer or panel must be accounted for here.
914 //
915 // We add an additional 1ms to allow for processing time and
916 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800917 info.presentationDeadline =
918 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700919
920 // All non-virtual displays are currently considered secure.
921 info.secure = true;
922
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800923 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700924 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800925 std::swap(info.w, info.h);
926 }
927
Michael Wright28f24d02016-07-12 13:30:53 -0700928 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700929 }
930
Dan Stoza7f7da322014-05-02 15:26:25 -0700931 return NO_ERROR;
932}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700933
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700934status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
935 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700936 return BAD_VALUE;
937 }
938
Ana Krulece588e312018-09-18 12:32:24 -0700939 if (mUseScheduler) {
940 mScheduler->getDisplayStatInfo(stats);
941 } else {
942 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
943 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
944 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700945 return NO_ERROR;
946}
947
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700948int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
949 const auto display = getDisplayDevice(displayToken);
950 if (!display) {
951 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800952 return BAD_VALUE;
953 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700954
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700955 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700956}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700957
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800958void SurfaceFlinger::setDesiredActiveConfig(const sp<IBinder>& displayToken, int mode) {
959 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800960
Ana Krulec7d1d6832018-12-27 11:10:09 -0800961 Vector<DisplayInfo> configs;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800962 // Lock is acquired by setRefreshRateTo.
963 getDisplayConfigsLocked(displayToken, &configs);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800964 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
965 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
966 return;
967 }
968
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800969 // Lock is acquired by setRefreshRateTo.
970 const auto display = getDisplayDeviceLocked(displayToken);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800971 if (!display) {
972 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
973 displayToken.get());
974 return;
975 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700976 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800977 ALOGW("Attempt to set active config %d for virtual display", mode);
978 return;
979 }
980 int currentDisplayPowerMode = display->getPowerMode();
981 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
982 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700983 return;
984 }
985
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800986 // Don't check against the current mode yet. Worst case we set the desired
987 // config twice.
988 {
989 std::lock_guard<std::mutex> lock(mActiveConfigLock);
990 mDesiredActiveConfig = ActiveConfigInfo{mode, displayToken};
991 }
992 // This will trigger HWC refresh without resetting the idle timer.
993 repaintEverythingForHWC();
994}
995
996status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
997 ATRACE_CALL();
998 postMessageSync(new LambdaMessage(
999 [&]() NO_THREAD_SAFETY_ANALYSIS { setDesiredActiveConfig(displayToken, mode); }));
1000 return NO_ERROR;
1001}
1002
1003void SurfaceFlinger::setActiveConfigInHWC() {
1004 ATRACE_CALL();
1005
1006 const auto display = getDisplayDevice(mUpcomingActiveConfig.displayToken);
1007 if (!display) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001008 return;
1009 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001010 const auto displayId = display->getId();
1011 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001012
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001013 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1014 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1015 mSetActiveConfigState = SetActiveConfigState::NOTIFIED_HWC;
1016 ATRACE_INT("SetActiveConfigState", mSetActiveConfigState);
1017}
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001018
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001019void SurfaceFlinger::setActiveConfigInternal() {
1020 ATRACE_CALL();
1021
1022 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1023 if (mUseScheduler) {
1024 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
1025 }
1026
1027 const auto display = getDisplayDeviceLocked(mUpcomingActiveConfig.displayToken);
1028 display->setActiveConfig(mUpcomingActiveConfig.configId);
1029
1030 mSetActiveConfigState = SetActiveConfigState::NONE;
1031 ATRACE_INT("SetActiveConfigState", mSetActiveConfigState);
1032
Dominik Laskowski83b88212018-12-11 13:34:06 -08001033 resyncToHardwareVsync(true, getVsyncPeriod());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001034 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
1035}
1036
1037bool SurfaceFlinger::updateSetActiveConfigStateMachine() NO_THREAD_SAFETY_ANALYSIS {
1038 // Store the local variable to release the lock.
1039 ActiveConfigInfo desiredActiveConfig;
1040 {
1041 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1042 desiredActiveConfig = mDesiredActiveConfig;
1043 }
1044
1045 const auto display = getDisplayDevice(desiredActiveConfig.displayToken);
1046 if (display) {
1047 if (mSetActiveConfigState == SetActiveConfigState::NONE &&
1048 display->getActiveConfig() != desiredActiveConfig.configId) {
1049 // Step 1) Desired active config was set, it is different than the
1050 // config currently in use. Notify HWC.
1051 mUpcomingActiveConfig = desiredActiveConfig;
1052 setActiveConfigInHWC();
1053 } else if (mSetActiveConfigState == SetActiveConfigState::NOTIFIED_HWC) {
1054 // Step 2) HWC was notified and we received refresh from it.
1055 mSetActiveConfigState = SetActiveConfigState::REFRESH_RECEIVED;
1056 ATRACE_INT("SetActiveConfigState", mSetActiveConfigState);
1057 repaintEverythingForHWC();
1058 // We do not want to give another frame to HWC while we are transitioning.
1059 return false;
1060 } else if (mSetActiveConfigState == SetActiveConfigState::REFRESH_RECEIVED &&
1061 !(mPreviousPresentFence != Fence::NO_FENCE &&
1062 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled))) {
1063 // Step 3) We received the present fence from the HWC, so we assume it
1064 // successfully updated the config, hence we update SF.
1065 setActiveConfigInternal();
1066 // If the config changed again while we were transitioning, restart the
1067 // process.
1068 if (desiredActiveConfig != mUpcomingActiveConfig) {
1069 mUpcomingActiveConfig = desiredActiveConfig;
1070 setActiveConfigInHWC(); // sets the state to NOTIFY_HWC
1071 }
1072 }
1073 }
1074 return true;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001075}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001076
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001077status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1078 Vector<ColorMode>* outColorModes) {
1079 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001080 return BAD_VALUE;
1081 }
1082
Peiyong Lina52f0292018-03-14 17:26:31 -07001083 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001084 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001085 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1086
1087 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1088 if (!displayId) {
1089 return NAME_NOT_FOUND;
1090 }
1091
Dominik Laskowski075d3172018-05-24 15:50:06 -07001092 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001093 }
Michael Wright28f24d02016-07-12 13:30:53 -07001094 outColorModes->clear();
1095 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1096
1097 return NO_ERROR;
1098}
1099
Daniel Solomon42d04562019-01-20 21:03:19 -08001100status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1101 ui::DisplayPrimaries &primaries) {
1102 if (!displayToken) {
1103 return BAD_VALUE;
1104 }
1105
1106 // Currently we only support this API for a single internal display.
1107 if (getInternalDisplayToken() != displayToken) {
1108 return BAD_VALUE;
1109 }
1110
1111 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1112 return NO_ERROR;
1113}
1114
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001115ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1116 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001117 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001118 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001119 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001120}
1121
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001122status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001123 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001124 Vector<ColorMode> modes;
1125 getDisplayColorModes(displayToken, &modes);
1126 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1127 if (mode < ColorMode::NATIVE || !exists) {
1128 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1129 decodeColorMode(mode).c_str(), mode, displayToken.get());
1130 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001131 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001132 const auto display = getDisplayDevice(displayToken);
1133 if (!display) {
1134 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1135 decodeColorMode(mode).c_str(), mode, displayToken.get());
1136 } else if (display->isVirtual()) {
1137 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1138 decodeColorMode(mode).c_str(), mode);
1139 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001140 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1141 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001142 }
1143 }));
1144
Michael Wright28f24d02016-07-12 13:30:53 -07001145 return NO_ERROR;
1146}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001147
Svetoslavd85084b2014-03-20 10:28:31 -07001148status_t SurfaceFlinger::clearAnimationFrameStats() {
1149 Mutex::Autolock _l(mStateLock);
1150 mAnimFrameTracker.clearStats();
1151 return NO_ERROR;
1152}
1153
1154status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1155 Mutex::Autolock _l(mStateLock);
1156 mAnimFrameTracker.getStats(outStats);
1157 return NO_ERROR;
1158}
1159
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001160status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1161 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001162 Mutex::Autolock _l(mStateLock);
1163
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001164 const auto display = getDisplayDeviceLocked(displayToken);
1165 if (!display) {
1166 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001167 return BAD_VALUE;
1168 }
1169
Peiyong Linfb069302018-04-25 14:34:31 -07001170 // At this point the DisplayDeivce should already be set up,
1171 // meaning the luminance information is already queried from
1172 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001173 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001174 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1175 capabilities.getDesiredMaxLuminance(),
1176 capabilities.getDesiredMaxAverageLuminance(),
1177 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001178
1179 return NO_ERROR;
1180}
1181
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001182status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1183 ui::PixelFormat* outFormat,
1184 ui::Dataspace* outDataspace,
1185 uint8_t* outComponentMask) const {
1186 if (!outFormat || !outDataspace || !outComponentMask) {
1187 return BAD_VALUE;
1188 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001189 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001190 if (!display || !display->getId()) {
1191 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1192 return BAD_VALUE;
1193 }
1194 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1195 outDataspace, outComponentMask);
1196}
1197
Kevin DuBois74e53772018-11-19 10:52:38 -08001198status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1199 bool enable, uint8_t componentMask,
1200 uint64_t maxFrames) const {
1201 const auto display = getDisplayDevice(displayToken);
1202 if (!display || !display->getId()) {
1203 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1204 return BAD_VALUE;
1205 }
1206
1207 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1208 componentMask, maxFrames);
1209}
1210
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001211status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1212 uint64_t maxFrames, uint64_t timestamp,
1213 DisplayedFrameStats* outStats) const {
1214 const auto display = getDisplayDevice(displayToken);
1215 if (!display || !display->getId()) {
1216 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1217 return BAD_VALUE;
1218 }
1219
1220 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1221 outStats);
1222}
1223
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001224status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1225 if (!outSupported) {
1226 return BAD_VALUE;
1227 }
1228 *outSupported = getRenderEngine().supportsProtectedContent();
1229 return NO_ERROR;
1230}
1231
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001232status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1233 bool* outIsWideColorDisplay) const {
1234 if (!displayToken || !outIsWideColorDisplay) {
1235 return BAD_VALUE;
1236 }
1237 Mutex::Autolock _l(mStateLock);
1238 const auto display = getDisplayDeviceLocked(displayToken);
1239 if (!display) {
1240 return BAD_VALUE;
1241 }
1242 *outIsWideColorDisplay = display->hasWideColorGamut();
1243 return NO_ERROR;
1244}
1245
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001246status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001247 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001248 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001249
Chia-I Wu90f669f2017-10-05 14:24:41 -07001250 if (mInjectVSyncs == enable) {
1251 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001252 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001253
Dominik Laskowski83b88212018-12-11 13:34:06 -08001254 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001255
Ana Krulec98b5b242018-08-10 15:03:23 -07001256 // TODO(akrulec): Part of the Injector should be refactored, so that it
1257 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001258 if (enable) {
1259 ALOGV("VSync Injections enabled");
1260 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001261 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001262 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001263 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001264 impl::EventThread::InterceptVSyncsCallback(),
1265 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001266 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001267 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001268 } else {
1269 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001270 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001271 }
1272
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001273 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001274 }));
1275
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001276 return NO_ERROR;
1277}
1278
1279status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001280 Mutex::Autolock _l(mStateLock);
1281
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001282 if (!mInjectVSyncs) {
1283 ALOGE("VSync Injections not enabled");
1284 return BAD_VALUE;
1285 }
1286 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1287 ALOGV("Injecting VSync inside SurfaceFlinger");
1288 mVSyncInjector->onInjectSyncEvent(when);
1289 }
1290 return NO_ERROR;
1291}
1292
Lloyd Pique755e3192018-01-31 16:46:15 -08001293status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1294 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001295 // Try to acquire a lock for 1s, fail gracefully
1296 const status_t err = mStateLock.timedLock(s2ns(1));
1297 const bool locked = (err == NO_ERROR);
1298 if (!locked) {
1299 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1300 return TIMED_OUT;
1301 }
1302
1303 outLayers->clear();
1304 mCurrentState.traverseInZOrder([&](Layer* layer) {
1305 outLayers->push_back(layer->getLayerDebugInfo());
1306 });
1307
1308 mStateLock.unlock();
1309 return NO_ERROR;
1310}
1311
Peiyong Linc6780972018-10-28 15:24:08 -07001312status_t SurfaceFlinger::getCompositionPreference(
1313 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1314 Dataspace* outWideColorGamutDataspace,
1315 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001316 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001317 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001318 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001319 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001320 return NO_ERROR;
1321}
1322
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001323// ----------------------------------------------------------------------------
1324
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001325sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1326 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001327 auto resyncCallback = makeResyncCallback([this] {
1328 Mutex::Autolock lock(mStateLock);
1329 return getVsyncPeriod();
1330 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001331
Ana Krulec98b5b242018-08-10 15:03:23 -07001332 if (mUseScheduler) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001333 auto resetIdleTimerCallback = [this] {
1334 Mutex::Autolock lock(mStateLock);
1335 setRefreshRateTo(RefreshRateType::PERFORMANCE);
1336 };
1337
1338 const auto& handle = vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle
1339 : mAppConnectionHandle;
1340
1341 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback),
1342 std::move(resetIdleTimerCallback));
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001343 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001344 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001345 return mSFEventThread->createEventConnection(resyncCallback, ResetIdleTimerCallback());
Ana Krulec98b5b242018-08-10 15:03:23 -07001346 } else {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001347 return mEventThread->createEventConnection(resyncCallback, ResetIdleTimerCallback());
Ana Krulec98b5b242018-08-10 15:03:23 -07001348 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001349 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001350}
1351
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001352// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001353
1354void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001355 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001356}
1357
1358void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001359 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001360}
1361
1362void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001363 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001364}
1365
1366void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001367 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001368 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001369}
1370
1371status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001372 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001373 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001374}
1375
1376status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001377 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001378 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001379 if (res == NO_ERROR) {
1380 msg->wait();
1381 }
1382 return res;
1383}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001384
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001385void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001386 do {
1387 waitForEvent();
1388 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001389}
1390
Dominik Laskowski83b88212018-12-11 13:34:06 -08001391nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001392 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001393 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1394 return 0;
1395 }
1396
1397 const auto config = getHwComposer().getActiveConfig(*displayId);
1398 return config ? config->getVsyncPeriod() : 0;
1399}
1400
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001401void SurfaceFlinger::enableHardwareVsync() {
1402 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001403 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001404 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001405 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001406 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001407 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001408}
1409
Dominik Laskowski83b88212018-12-11 13:34:06 -08001410void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001411 Mutex::Autolock _l(mHWVsyncLock);
1412
Jesse Hall948fe0c2013-10-14 12:56:09 -07001413 if (makeAvailable) {
1414 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001415 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1416 if (mUseScheduler) {
1417 mScheduler->makeHWSyncAvailable(true);
1418 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001419 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001420 // Hardware vsync is not currently available, so abort the resync
1421 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001422 return;
1423 }
1424
Dominik Laskowski83b88212018-12-11 13:34:06 -08001425 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001426 return;
1427 }
1428
Ana Krulece588e312018-09-18 12:32:24 -07001429 if (mUseScheduler) {
1430 mScheduler->setVsyncPeriod(period);
1431 } else {
1432 mPrimaryDispSync->reset();
1433 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001434
Ana Krulece588e312018-09-18 12:32:24 -07001435 if (!mPrimaryHWVsyncEnabled) {
1436 mPrimaryDispSync->beginResync();
1437 mEventControlThread->setVsyncEnabled(true);
1438 mPrimaryHWVsyncEnabled = true;
1439 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001440 }
1441}
1442
Jesse Hall948fe0c2013-10-14 12:56:09 -07001443void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001444 Mutex::Autolock _l(mHWVsyncLock);
1445 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001446 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001447 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001448 mPrimaryHWVsyncEnabled = false;
1449 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001450 if (makeUnavailable) {
1451 mHWVsyncAvailable = false;
1452 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001453}
1454
Dominik Laskowski83b88212018-12-11 13:34:06 -08001455void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001456 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001457
Dan Stoza57164302017-05-08 14:03:54 -07001458 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001459 const nsecs_t last = lastResyncTime.exchange(now);
1460
1461 if (now - last > kIgnoreDelay) {
1462 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001463 }
1464}
1465
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001466void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1467 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001468 ATRACE_NAME("SF onVsync");
1469
Steven Thomas3cfac282017-02-06 12:29:30 -08001470 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001471 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001472 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001473 return;
1474 }
1475
Dominik Laskowski075d3172018-05-24 15:50:06 -07001476 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001477 return;
1478 }
1479
Dominik Laskowski075d3172018-05-24 15:50:06 -07001480 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001481 // For now, we don't do anything with external display vsyncs.
1482 return;
1483 }
1484
Ana Krulece588e312018-09-18 12:32:24 -07001485 if (mUseScheduler) {
1486 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001487 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001488 bool needsHwVsync = false;
1489 { // Scope for the lock
1490 Mutex::Autolock _l(mHWVsyncLock);
1491 if (mPrimaryHWVsyncEnabled) {
1492 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1493 }
1494 }
1495
1496 if (needsHwVsync) {
1497 enableHardwareVsync();
1498 } else {
1499 disableHardwareVsync(false);
1500 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001501 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001502}
1503
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001504void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001505 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1506 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001507}
1508
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001509void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate) {
1510 mPhaseOffsets->setRefreshRateType(refreshRate);
1511
1512 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1513 mVsyncModulator.setPhaseOffsets(early, gl, late);
1514
1515 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001516 return;
1517 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001518
Ana Krulec7d1d6832018-12-27 11:10:09 -08001519 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1520 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1521 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1522 // refresh cycle.
1523
1524 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001525 const nsecs_t currentVsyncPeriod = getVsyncPeriod();
Ana Krulec7d1d6832018-12-27 11:10:09 -08001526 if (currentVsyncPeriod == 0) {
1527 return;
1528 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001529
Ana Krulec7d1d6832018-12-27 11:10:09 -08001530 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1531 // floating numbers.
1532 const float currentFps = 1e9 / currentVsyncPeriod;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001533 const float newFps = refreshRate == RefreshRateType::PERFORMANCE ? kPerformanceRefreshRate
1534 : kDefaultRefreshRate;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001535 if (std::abs(currentFps - newFps) <= 1) {
1536 return;
1537 }
1538
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001539 const auto displayId = getInternalDisplayIdLocked();
1540 LOG_ALWAYS_FATAL_IF(!displayId);
1541
1542 auto configs = getHwComposer().getConfigs(*displayId);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001543 for (int i = 0; i < configs.size(); i++) {
1544 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1545 if (vsyncPeriod == 0) {
1546 continue;
1547 }
1548 const float fps = 1e9 / vsyncPeriod;
1549 // TODO(b/113612090): There should be a better way at determining which config
1550 // has the right refresh rate.
1551 if (std::abs(fps - newFps) <= 1) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001552 setDesiredActiveConfig(getInternalDisplayTokenLocked(), i);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001553 }
1554 }
1555}
1556
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001557void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001558 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001559 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001560 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001561
Lloyd Piqueba04e622017-12-14 17:11:26 -08001562 // Ignore events that do not have the right sequenceId.
1563 if (sequenceId != getBE().mComposerSequenceId) {
1564 return;
1565 }
1566
Steven Thomasb02664d2017-07-26 18:48:28 -07001567 // Only lock if we're not on the main thread. This function is normally
1568 // called on a hwbinder thread, but for the primary display it's called on
1569 // the main thread with the state lock already held, so don't attempt to
1570 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001571 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001572
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001573 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001574
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001575 if (std::this_thread::get_id() == mMainThreadId) {
1576 // Process all pending hot plug events immediately if we are on the main thread.
1577 processDisplayHotplugEventsLocked();
1578 }
1579
Lloyd Piqueba04e622017-12-14 17:11:26 -08001580 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001581}
1582
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001583void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001584 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001585 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001586 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001587 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001588 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001589}
1590
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001591void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001592 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001593 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001594 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001595 getHwComposer().setVsyncEnabled(*displayId,
1596 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1597 }
Mathias Agopian86303202012-07-24 22:46:10 -07001598}
1599
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001600// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001601void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001602 if (mUseScheduler) {
1603 mScheduler->disableHardwareVsync(true);
1604 } else {
1605 disableHardwareVsync(true);
1606 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001607 // Clear the drawing state so that the logic inside of
1608 // handleTransactionLocked will fire. It will determine the delta between
1609 // mCurrentState and mDrawingState and re-apply all changes when we make the
1610 // transition.
1611 mDrawingState.displays.clear();
1612 mDisplays.clear();
1613}
1614
Steven Thomas050b2c82017-03-06 11:45:16 -08001615void SurfaceFlinger::updateVrFlinger() {
1616 if (!mVrFlinger)
1617 return;
1618 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001619 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001620 return;
1621 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001622
Lloyd Pique441d5042018-10-18 16:49:51 -07001623 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001624 ALOGE("Vr flinger is only supported for remote hardware composer"
1625 " service connections. Ignoring request to transition to vr"
1626 " flinger.");
1627 mVrFlingerRequestsDisplay = false;
1628 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001629 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001630
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001631 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001632
Steven Thomas0123ac62018-07-12 11:32:34 -07001633 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001634 LOG_ALWAYS_FATAL_IF(!display);
1635 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001636 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1637 // called below. Clear the reference now so we don't accidentally use it
1638 // later.
1639 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001640
Steven Thomasb02664d2017-07-26 18:48:28 -07001641 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001642 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001643 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001644
Steven Thomasb02664d2017-07-26 18:48:28 -07001645 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001646 // Delete the current instance before creating the new one
1647 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1648 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1649 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1650 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001651
Lloyd Pique441d5042018-10-18 16:49:51 -07001652 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001653 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001654
1655 if (vrFlingerRequestsDisplay) {
1656 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001657 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001658
1659 mVisibleRegionsDirty = true;
1660 invalidateHwcGeometry();
1661
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001662 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001663 display = getDefaultDisplayDeviceLocked();
1664 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001665 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001666
Steven Thomasb02664d2017-07-26 18:48:28 -07001667 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001668 const nsecs_t vsyncPeriod = getVsyncPeriod();
1669 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001670
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001671 // The present fences returned from vr_hwc are not an accurate
1672 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001673 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001674 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1675 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001676 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001677 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001678 !hasSyncFramework);
1679 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001680
Steven Thomasb02664d2017-07-26 18:48:28 -07001681 // Use phase of 0 since phase is not known.
1682 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001683 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001684 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001685
Dominik Laskowski83b88212018-12-11 13:34:06 -08001686 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001687
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001688 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001689 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001690}
1691
Mathias Agopian4fec8732012-06-29 14:12:52 -07001692void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001693 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001694 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001695 case MessageQueue::INVALIDATE: {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001696 if (!updateSetActiveConfigStateMachine()) {
1697 break;
1698 }
1699
Ana Krulec3084c052018-11-21 20:27:17 +01001700 if (mUseScheduler) {
1701 // This call is made each time SF wakes up and creates a new frame.
1702 mScheduler->incrementFrameCounter();
1703 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001704 bool frameMissed = !mHadClientComposition && mPreviousPresentFence != Fence::NO_FENCE &&
1705 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001706 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001707 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001708 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001709 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001710 if (mPropagateBackpressure) {
1711 signalLayerUpdate();
1712 break;
1713 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001714 }
Dan Stoza50182882016-07-08 12:02:20 -07001715
Steven Thomas050b2c82017-03-06 11:45:16 -08001716 // Now that we're going to make it to the handleMessageTransaction()
1717 // call below it's safe to call updateVrFlinger(), which will
1718 // potentially trigger a display handoff.
1719 updateVrFlinger();
1720
Dan Stoza6b9454d2014-11-07 16:00:59 -08001721 bool refreshNeeded = handleMessageTransaction();
1722 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001723
1724 updateCursorAsync();
1725 updateInputFlinger();
1726
Dan Stoza58784442014-12-02 16:58:17 -08001727 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001728 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001729 // Signal a refresh if a transaction modified the window state,
1730 // a new buffer was latched, or if HWC has requested a full
1731 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001732 signalRefresh();
1733 }
1734 break;
1735 }
1736 case MessageQueue::REFRESH: {
1737 handleMessageRefresh();
1738 break;
1739 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001740 }
1741}
1742
Dan Stoza6b9454d2014-11-07 16:00:59 -08001743bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001744 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001745
1746 // Apply any ready transactions in the queues if there are still transactions that have not been
1747 // applied, wake up during the next vsync period and check again
1748 bool transactionNeeded = false;
1749 if (!flushTransactionQueues()) {
1750 transactionNeeded = true;
1751 }
1752
Mathias Agopian4fec8732012-06-29 14:12:52 -07001753 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001754 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001755 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001756
1757 if (transactionNeeded) {
1758 setTransactionFlags(eTransactionNeeded);
1759 }
1760
1761 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001762}
1763
Mathias Agopian4fec8732012-06-29 14:12:52 -07001764void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001765 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001766
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001767 mRefreshPending = false;
1768
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001769 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001770 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001771 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001772 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001773 for (const auto& [token, display] : mDisplays) {
1774 beginFrame(display);
1775 prepareFrame(display);
1776 doDebugFlashRegions(display, repaintEverything);
1777 doComposition(display, repaintEverything);
1778 }
1779
Adrian Roos1e1a1282017-11-01 19:05:31 +01001780 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001781 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001782
1783 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001784 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001785
Dan Stozabfbffeb2016-07-21 14:49:33 -07001786 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001787 for (const auto& [token, displayDevice] : mDisplays) {
1788 auto display = displayDevice->getCompositionDisplay();
1789 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001790 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001791 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001792 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001793
Alec Mouri86770e52018-09-24 22:40:58 +00001794 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001795 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001796 if (mHadClientComposition) {
1797 base::unique_fd flushFence(getRenderEngine().flush());
1798 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1799 getBE().flushFence = new Fence(std::move(flushFence));
1800 } else {
1801 // Cleanup for hygiene.
1802 getBE().flushFence = Fence::NO_FENCE;
1803 }
1804 }
1805
Jorim Jaggi90535212018-05-23 23:44:06 +02001806 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001807
David Sodman7e4ae112018-02-09 15:02:28 -08001808 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001809 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001810 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001811 compositionInfo.hwc.hwcLayer = nullptr;
1812 }
David Sodmanba340492018-08-05 21:51:33 -07001813 }
David Sodman7e4ae112018-02-09 15:02:28 -08001814
1815 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001816}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001817
David Sodmanfa9b2af2017-12-24 13:28:59 -08001818
1819bool SurfaceFlinger::handleMessageInvalidate() {
1820 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001821 bool refreshNeeded = handlePageFlip();
1822
1823 for (auto& layer : mLayersPendingRefresh) {
1824 Region visibleReg;
1825 visibleReg.set(layer->computeScreenBounds());
1826 invalidateLayerStack(layer, visibleReg);
1827 }
1828 mLayersPendingRefresh.clear();
1829 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001830}
1831
David Sodman79bba0e2018-08-05 18:07:49 -07001832void SurfaceFlinger::calculateWorkingSet() {
1833 ATRACE_CALL();
1834 ALOGV(__FUNCTION__);
1835
David Sodman79bba0e2018-08-05 18:07:49 -07001836 // build the h/w work list
1837 if (CC_UNLIKELY(mGeometryInvalid)) {
1838 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001839 for (const auto& [token, displayDevice] : mDisplays) {
1840 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001841 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001842 if (!displayId) {
1843 continue;
1844 }
David Sodman79bba0e2018-08-05 18:07:49 -07001845
Lloyd Pique32cbe282018-10-19 13:09:22 -07001846 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001847 for (size_t i = 0; i < currentLayers.size(); i++) {
1848 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001849
Dominik Laskowski075d3172018-05-24 15:50:06 -07001850 if (!layer->hasHwcLayer(*displayId)) {
1851 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1852 layer->forceClientComposition(*displayId);
1853 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001854 }
1855 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001856
Lloyd Pique32cbe282018-10-19 13:09:22 -07001857 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001858 if (mDebugDisableHWC || mDebugRegion) {
1859 layer->forceClientComposition(*displayId);
1860 }
David Sodman79bba0e2018-08-05 18:07:49 -07001861 }
1862 }
1863 }
1864
1865 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001866 for (const auto& [token, displayDevice] : mDisplays) {
1867 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001868 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001869 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001870 continue;
1871 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001872 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001873
1874 if (mDrawingState.colorMatrixChanged) {
1875 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001876 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001877 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001878 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001879 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001880 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1881 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001882 !profile->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001883 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001884 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1885 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001886 !profile->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001887 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001888 }
1889
Peiyong Lind3788632018-09-18 16:01:31 -07001890 // TODO(b/111562338) remove when composer 2.3 is shipped.
1891 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001892 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001893 }
1894
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001895 if (layer->getRoundedCornerState().radius > 0.0f) {
1896 layer->forceClientComposition(*displayId);
1897 }
1898
Dominik Laskowski075d3172018-05-24 15:50:06 -07001899 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001900 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001901 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001902 continue;
1903 }
1904
Lloyd Pique32cbe282018-10-19 13:09:22 -07001905 const auto& displayState = display->getState();
1906 layer->setPerFrameData(*displayId, displayState.transform, displayState.viewport,
1907 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001908 }
1909
Peiyong Lin13effd12018-07-24 17:01:47 -07001910 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001911 ColorMode colorMode;
1912 Dataspace dataSpace;
1913 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001914 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001915 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001916 }
1917 }
1918
1919 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001920
1921 for (const auto& [token, display] : mDisplays) {
1922 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001923 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001924 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001925
1926 if (displayId) {
1927 if (!layer->setHwcLayer(*displayId)) {
1928 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1929 }
1930 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001931 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001932
Dominik Laskowski05275f12018-11-01 15:03:24 -07001933 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001934 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1935 }
1936 }
David Sodman79bba0e2018-08-05 18:07:49 -07001937}
1938
Lloyd Pique32cbe282018-10-19 13:09:22 -07001939void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1940 bool repaintEverything) {
1941 auto display = displayDevice->getCompositionDisplay();
1942 const auto& displayState = display->getState();
1943
Mathias Agopiancd60f992012-08-16 16:28:27 -07001944 // is debugging enabled
1945 if (CC_LIKELY(!mDebugRegion))
1946 return;
1947
Lloyd Pique32cbe282018-10-19 13:09:22 -07001948 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001949 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001950 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001951 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001952 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001953 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001954 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001955
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001956 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001957 }
1958 }
1959
Lloyd Pique32cbe282018-10-19 13:09:22 -07001960 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001961
1962 if (mDebugRegion > 1) {
1963 usleep(mDebugRegion * 1000);
1964 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001965
Lloyd Pique32cbe282018-10-19 13:09:22 -07001966 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001967}
1968
Adrian Roos1e1a1282017-11-01 19:05:31 +01001969void SurfaceFlinger::doTracing(const char* where) {
1970 ATRACE_CALL();
1971 ATRACE_NAME(where);
1972 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001973 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001974 }
1975}
1976
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001977void SurfaceFlinger::logLayerStats() {
1978 ATRACE_CALL();
1979 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001980 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001981 if (display->isPrimary()) {
1982 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001983 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001984 }
1985 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001986
1987 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001988 }
1989}
1990
David Sodman2b406362017-12-15 13:33:47 -08001991void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001992{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001993 ATRACE_CALL();
1994 ALOGV("preComposition");
1995
David Sodman2b406362017-12-15 13:33:47 -08001996 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1997
Mathias Agopiancd60f992012-08-16 16:28:27 -07001998 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001999 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08002000 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002001 needExtraInvalidate = true;
2002 }
Robert Carr2047fae2016-11-28 14:09:09 -08002003 });
2004
Mathias Agopiancd60f992012-08-16 16:28:27 -07002005 if (needExtraInvalidate) {
2006 signalLayerUpdate();
2007 }
2008}
2009
Ana Krulece588e312018-09-18 12:32:24 -07002010void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2011 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002012 // Update queue of past composite+present times and determine the
2013 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002014 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002015 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002016 while (!getBE().mCompositePresentTimes.empty()) {
2017 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002018 // Cached values should have been updated before calling this method,
2019 // which helps avoid duplicate syscalls.
2020 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2021 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2022 break;
2023 }
2024 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002025 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002026 }
2027
2028 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002029 while (getBE().mCompositePresentTimes.size() > 16) {
2030 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002031 }
2032
Ana Krulece588e312018-09-18 12:32:24 -07002033 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002034}
2035
Ana Krulece588e312018-09-18 12:32:24 -07002036void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2037 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002038 // Integer division and modulo round toward 0 not -inf, so we need to
2039 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08002040 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
2041 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
2042 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002043
Ana Krulec757f63a2019-01-25 10:46:18 -08002044 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002045 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002046 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002047 }
2048
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002049 // Snap the latency to a value that removes scheduling jitter from the
2050 // composition and present times, which often have >1ms of jitter.
2051 // Reducing jitter is important if an app attempts to extrapolate
2052 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08002053 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002054 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002055 nsecs_t bias = stats.vsyncPeriod / 2;
2056 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2057 nsecs_t snappedCompositeToPresentLatency =
2058 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002059
David Sodman99974d22017-11-28 12:04:33 -08002060 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002061 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2062 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002063 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002064}
2065
Ady Abraham8164d482019-01-11 14:47:59 -08002066// debug patch for b/119477596 - add stack guards to catch stack
2067// corruptions and disable clang optimizations.
2068// The code below is temporary and planned to be removed once stack
2069// corruptions are found.
2070#pragma clang optimize off
2071class StackGuard {
2072public:
2073 StackGuard(const char* name, const char* func, int line) {
2074 guarders.reserve(MIN_CAPACITY);
2075 guarders.push_back({this, name, func, line});
2076 validate();
2077 }
2078 ~StackGuard() {
2079 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
2080 if (i->guard == this) {
2081 guarders.erase(i);
2082 break;
2083 }
2084 }
2085 }
2086
2087 static void validate() {
2088 for (const auto& guard : guarders) {
2089 if (guard.guard->cookie != COOKIE_VALUE) {
2090 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
2091 CallStack stack(LOG_TAG);
2092 abort();
2093 }
2094 }
2095 }
2096
2097private:
2098 uint64_t cookie = COOKIE_VALUE;
2099 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
2100 static constexpr size_t MIN_CAPACITY = 16;
2101
2102 struct GuarderElement {
2103 StackGuard* guard;
2104 const char* name;
2105 const char* func;
2106 int line;
2107 };
2108
2109 static std::vector<GuarderElement> guarders;
2110};
2111std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2112
2113#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2114
2115#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002116void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002117{
Ady Abraham8164d482019-01-11 14:47:59 -08002118 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002119 ATRACE_CALL();
2120 ALOGV("postComposition");
2121
Brian Anderson3546a3f2016-07-14 11:51:14 -07002122 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002123 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002124 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002125 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002126 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002127 }
Ady Abraham8164d482019-01-11 14:47:59 -08002128 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002129
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002130 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002131 const auto displayDevice = getDefaultDisplayDeviceLocked();
2132 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002133
David Sodman73beded2017-11-15 11:56:06 -08002134 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002135 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002136 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2137
Lloyd Pique32cbe282018-10-19 13:09:22 -07002138 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002139 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002140 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2141 ->getRenderSurface()
2142 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002143 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002144 } else {
2145 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2146 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002147
Ady Abraham8164d482019-01-11 14:47:59 -08002148 ASSERT_ON_STACK_GUARD();
2149
David Sodman73beded2017-11-15 11:56:06 -08002150 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002151 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2152 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002153 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002154 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002155 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002156
Ana Krulece588e312018-09-18 12:32:24 -07002157 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002158 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002159 if (mUseScheduler) {
2160 mScheduler->getDisplayStatInfo(&stats);
2161 } else {
2162 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2163 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2164 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002165
Ady Abraham8164d482019-01-11 14:47:59 -08002166 ASSERT_ON_STACK_GUARD();
2167
David Sodman2b406362017-12-15 13:33:47 -08002168 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002169 // when we started doing work for this frame, but that should be okay
2170 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002171 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002172 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002173 DEFINE_STACK_GUARD(compositorTiming);
2174
Brian Andersond0010582017-03-07 13:20:31 -08002175 {
David Sodman99974d22017-11-28 12:04:33 -08002176 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002177 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002178 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002179
2180 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002181 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002182
Robert Carr2047fae2016-11-28 14:09:09 -08002183 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002184 bool frameLatched =
2185 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2186 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002187 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002188 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002189 recordBufferingStats(layer->getName().string(),
2190 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002191 }
Ady Abraham8164d482019-01-11 14:47:59 -08002192 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002193 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002194
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002195 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002196 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002197 if (mUseScheduler) {
2198 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002199 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002200 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002201 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2202 enableHardwareVsync();
2203 } else {
2204 disableHardwareVsync(false);
2205 }
Ady Abraham8164d482019-01-11 14:47:59 -08002206 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002207 }
2208 }
2209
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002210 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002211 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2212 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002213 if (mUseScheduler) {
2214 mScheduler->enableHardwareVsync();
2215 } else {
2216 enableHardwareVsync();
2217 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002218 }
2219 }
2220
Ady Abraham8164d482019-01-11 14:47:59 -08002221 ASSERT_ON_STACK_GUARD();
2222
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002223 if (mAnimCompositionPending) {
2224 mAnimCompositionPending = false;
2225
Brian Anderson4e606e32017-03-16 15:34:57 -07002226 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002227 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002228 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002229
2230 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002231 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002232 // The HWC doesn't support present fences, so use the refresh
2233 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002234 const nsecs_t presentTime =
2235 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002236 DEFINE_STACK_GUARD(presentTime);
2237
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002238 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002239 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002240 }
2241 mAnimFrameTracker.advanceFrame();
2242 }
Dan Stozab90cf072015-03-05 11:05:59 -08002243
Ady Abraham8164d482019-01-11 14:47:59 -08002244 ASSERT_ON_STACK_GUARD();
2245
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002246 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002247 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002248 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002249 }
2250
Ady Abraham8164d482019-01-11 14:47:59 -08002251 ASSERT_ON_STACK_GUARD();
2252
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002253 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002254
Ady Abraham8164d482019-01-11 14:47:59 -08002255 ASSERT_ON_STACK_GUARD();
2256
Lloyd Pique32cbe282018-10-19 13:09:22 -07002257 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2258 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002259 return;
2260 }
2261
2262 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002263 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002264 if (mHasPoweredOff) {
2265 mHasPoweredOff = false;
2266 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002267 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002268 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002269 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002270 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002271 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2272 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002273 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002274 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002275 }
David Sodman4a36e932017-11-07 14:29:47 -08002276 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002277
2278 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002279 }
David Sodman4a36e932017-11-07 14:29:47 -08002280 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002281 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002282
2283 {
2284 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002285 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002286 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002287 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002288 if (refillCount > 0) {
2289 const size_t offset = mTexturePool.size();
2290 mTexturePool.resize(mTexturePoolSize);
2291 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2292 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2293 }
Ady Abraham8164d482019-01-11 14:47:59 -08002294 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002295 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002296
Marissa Wallfda30bb2018-10-12 11:34:28 -07002297 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002298 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002299
2300 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002301}
Ady Abraham8164d482019-01-11 14:47:59 -08002302#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002303
2304void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002305 ATRACE_CALL();
2306 ALOGV("rebuildLayerStacks");
2307
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002308 // We need to clear these out now as these may be holding on to a
2309 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2310 // also holds a reference. When the set of visible layers is recomputed,
2311 // some layers may be destroyed if the only thing keeping them alive was
2312 // that list of visible layers associated with each display. The layer
2313 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2314 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2315 for (const auto& [token, display] : mDisplays) {
2316 getBE().mCompositionInfo[token].clear();
2317 }
2318
Mathias Agopiancd60f992012-08-16 16:28:27 -07002319 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002320 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002321 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002322 mVisibleRegionsDirty = false;
2323 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002324
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002325 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002326 const auto& displayDevice = pair.second;
2327 auto display = displayDevice->getCompositionDisplay();
2328 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002329 Region opaqueRegion;
2330 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002331 compositionengine::Output::OutputLayers layersSortedByZ;
2332 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002333 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002334 const ui::Transform& tr = displayState.transform;
2335 const Rect bounds = displayState.bounds;
2336 if (displayState.isEnabled) {
2337 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002338
Jeff Sharkey76488112017-02-27 14:15:18 -07002339 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002340 auto compositionLayer = layer->getCompositionLayer();
2341 if (compositionLayer == nullptr) {
2342 return;
2343 }
2344
Chia-I Wu83806892017-11-16 10:50:20 -08002345 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002346 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002347 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2348 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2349
Lloyd Piqueef36b002019-01-23 17:52:04 -08002350 if (display->belongsInOutput(layer->getLayerStack(),
2351 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002352 Region drawRegion(tr.transform(
2353 layer->visibleNonTransparentRegion));
2354 drawRegion.andSelf(bounds);
2355 if (!drawRegion.isEmpty()) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002356 layersSortedByZ.emplace_back(
2357 display->getOrCreateOutputLayer(layer->getCompositionLayer(),
2358 layerFE));
2359
2360 deprecated_layersSortedByZ.add(layer);
Jeff Sharkey76488112017-02-27 14:15:18 -07002361 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002362 // Clear out the HWC layer if this layer was
2363 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002364 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002365 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002366 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002367 // WM changes display->layerStack upon sleep/awake.
2368 // Here we make sure we delete the HWC layers even if
2369 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002370 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002371 }
2372
2373 // If a layer is not going to get a release fence because
2374 // it is invisible, but it is also going to release its
2375 // old buffer, add it to the list of layers needing
2376 // fences.
2377 if (hwcLayerDestroyed) {
2378 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2379 mLayersWithQueuedFrames.cend(), layer);
2380 if (found != mLayersWithQueuedFrames.cend()) {
2381 layersNeedingFences.add(layer);
2382 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002383 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002384 });
2385 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002386
2387 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2388
2389 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002390 displayDevice->setLayersNeedingFences(layersNeedingFences);
2391
2392 Region undefinedRegion{bounds};
2393 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2394
2395 display->editState().undefinedRegion = undefinedRegion;
2396 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002397 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002398 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002399}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002400
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002401// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002402// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002403// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002404// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002405// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002406// The returned HDR data space is one of
2407// - Dataspace::UNKNOWN
2408// - Dataspace::BT2020_HLG
2409// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002410Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2411 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002412 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002413 *outHdrDataSpace = Dataspace::UNKNOWN;
2414
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002415 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002416 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002417 case Dataspace::V0_SCRGB:
2418 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002419 case Dataspace::BT2020:
2420 case Dataspace::BT2020_ITU:
2421 case Dataspace::BT2020_LINEAR:
2422 case Dataspace::DISPLAY_BT2020:
2423 bestDataSpace = Dataspace::DISPLAY_BT2020;
2424 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002425 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002426 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002427 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002428 case Dataspace::BT2020_PQ:
2429 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002430 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002431 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002432 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002433 case Dataspace::BT2020_HLG:
2434 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002435 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002436 // When there's mixed PQ content and HLG content, we set the HDR
2437 // data space to be BT2020_PQ and convert HLG to PQ.
2438 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2439 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002440 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002441 break;
2442 default:
2443 break;
2444 }
Romain Guy54f154a2017-10-24 21:40:32 +01002445 }
2446
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002447 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002448}
2449
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002450// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002451void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2452 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002453 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2454 *outMode = ColorMode::NATIVE;
2455 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002456 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002457 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002458 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002459
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002460 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002461 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002462
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002463 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2464
Peiyong Lindfde5112018-06-05 10:58:41 -07002465 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002466 const bool isHdr =
2467 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002468 if (isHdr) {
2469 bestDataSpace = hdrDataSpace;
2470 }
2471
Chia-I Wu0d711262018-05-21 15:19:35 -07002472 RenderIntent intent;
2473 switch (mDisplayColorSetting) {
2474 case DisplayColorSetting::MANAGED:
2475 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002476 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002477 break;
2478 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002479 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002480 break;
2481 default: // vendor display color setting
2482 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2483 break;
2484 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002485
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002486 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002487}
2488
Lloyd Pique32cbe282018-10-19 13:09:22 -07002489void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2490 auto display = displayDevice->getCompositionDisplay();
2491 const auto& displayState = display->getState();
2492
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002493 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002494 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2495 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002496
David Sodmanfa9b2af2017-12-24 13:28:59 -08002497 // If nothing has changed (!dirty), don't recompose.
2498 // If something changed, but we don't currently have any visible layers,
2499 // and didn't when we last did a composition, then skip it this time.
2500 // The second rule does two things:
2501 // - When all layers are removed from a display, we'll emit one black
2502 // frame, then nothing more until we get new layers.
2503 // - When a display is created with a private layer stack, we won't
2504 // emit any black frames until a layer is added to the layer stack.
2505 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002506
Dominik Laskowski075d3172018-05-24 15:50:06 -07002507 const char flagPrefix[] = {'-', '+'};
2508 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002509 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2510 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2511 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2512 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002513
Lloyd Pique31cb2942018-10-19 17:23:03 -07002514 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002515
David Sodmanfa9b2af2017-12-24 13:28:59 -08002516 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002517 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002518 }
2519}
2520
Lloyd Pique32cbe282018-10-19 13:09:22 -07002521void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2522 auto display = displayDevice->getCompositionDisplay();
2523 const auto& displayState = display->getState();
2524
2525 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002526 return;
David Sodman2b406362017-12-15 13:33:47 -08002527 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002528
Lloyd Pique31cb2942018-10-19 17:23:03 -07002529 status_t result = display->getRenderSurface()->prepareFrame(
2530 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002531 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002532 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002533}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002534
Lloyd Pique32cbe282018-10-19 13:09:22 -07002535void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002536 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002537 ALOGV("doComposition");
2538
Lloyd Pique32cbe282018-10-19 13:09:22 -07002539 auto display = displayDevice->getCompositionDisplay();
2540 const auto& displayState = display->getState();
2541
2542 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002543 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002544 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002545
David Sodmanfa9b2af2017-12-24 13:28:59 -08002546 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002547 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002548
Lloyd Pique32cbe282018-10-19 13:09:22 -07002549 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002550 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002551 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002552 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002553}
2554
David Sodmanfa9b2af2017-12-24 13:28:59 -08002555void SurfaceFlinger::postFrame()
2556{
2557 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002558 const auto display = getDefaultDisplayDeviceLocked();
2559 if (display && getHwComposer().isConnected(*display->getId())) {
2560 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002561 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2562 logFrameStats();
2563 }
2564 }
2565}
2566
Lloyd Pique32cbe282018-10-19 13:09:22 -07002567void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002568 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002569 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002570
Lloyd Pique32cbe282018-10-19 13:09:22 -07002571 auto display = displayDevice->getCompositionDisplay();
2572 const auto& displayState = display->getState();
2573 const auto displayId = display->getId();
2574
David Sodmanfa9b2af2017-12-24 13:28:59 -08002575 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002576
Lloyd Pique32cbe282018-10-19 13:09:22 -07002577 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002578 if (displayId) {
2579 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002580 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002581 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002582 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002583 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002584
Chia-I Wu7b549592017-11-15 09:14:57 -08002585 // The layer buffer from the previous frame (if any) is released
2586 // by HWC only when the release fence from this frame (if any) is
2587 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002588 if (displayId && layer->hasHwcLayer(*displayId)) {
2589 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2590 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002591 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002592
2593 // If the layer was client composited in the previous frame, we
2594 // need to merge with the previous client target acquire fence.
2595 // Since we do not track that, always merge with the current
2596 // client target acquire fence when it is available, even though
2597 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002598 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002599 releaseFence =
2600 Fence::merge("LayerRelease", releaseFence,
2601 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002602 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002603
David Sodman15094112018-10-11 09:39:37 -07002604 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002605 }
Chia-I Wu83806892017-11-16 10:50:20 -08002606
2607 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002608 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002609 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002610 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002611 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002612 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002613 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002614 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002615 }
2616 }
2617
Dominik Laskowski075d3172018-05-24 15:50:06 -07002618 if (displayId) {
2619 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002620 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002621 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002622}
2623
Mathias Agopian87baae12012-07-31 12:38:26 -07002624void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002625{
Mathias Agopian841cde52012-03-01 15:44:37 -08002626 ATRACE_CALL();
2627
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002628 // here we keep a copy of the drawing state (that is the state that's
2629 // going to be overwritten by handleTransactionLocked()) outside of
2630 // mStateLock so that the side-effects of the State assignment
2631 // don't happen with mStateLock held (which can cause deadlocks).
2632 State drawingState(mDrawingState);
2633
Mathias Agopianca4d3602011-05-19 15:38:14 -07002634 Mutex::Autolock _l(mStateLock);
2635 const nsecs_t now = systemTime();
2636 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002637
Mathias Agopianca4d3602011-05-19 15:38:14 -07002638 // Here we're guaranteed that some transaction flags are set
2639 // so we can call handleTransactionLocked() unconditionally.
2640 // We call getTransactionFlags(), which will also clear the flags,
2641 // with mStateLock held to guarantee that mCurrentState won't change
2642 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002643
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002644 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002645 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002646 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002647
Mathias Agopianca4d3602011-05-19 15:38:14 -07002648 mLastTransactionTime = systemTime() - now;
2649 mDebugInTransaction = 0;
2650 invalidateHwcGeometry();
2651 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002652}
2653
Lloyd Piqueba04e622017-12-14 17:11:26 -08002654void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2655 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002656 const std::optional<DisplayIdentificationInfo> info =
2657 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002658
Dominik Laskowski075d3172018-05-24 15:50:06 -07002659 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002660 continue;
2661 }
2662
Lloyd Piqueba04e622017-12-14 17:11:26 -08002663 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002664 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002665 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002666 mPhysicalDisplayTokens[info->id] = new BBinder();
2667 DisplayDeviceState state;
2668 state.displayId = info->id;
2669 state.isSecure = true; // All physical displays are currently considered secure.
2670 state.displayName = info->name;
2671 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2672 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002673 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002674 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002675 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002676
Dominik Laskowski075d3172018-05-24 15:50:06 -07002677 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2678 if (index >= 0) {
2679 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2680 mInterceptor->saveDisplayDeletion(state.sequenceId);
2681 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002682 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002683 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002684 }
2685
2686 processDisplayChangesLocked();
2687 }
2688
2689 mPendingHotplugEvents.clear();
2690}
2691
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002692void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002693 if (mUseScheduler) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002694 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2695 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002696 } else {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002697 mEventThread->onHotplugReceived(displayId, connected);
2698 mSFEventThread->onHotplugReceived(displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002699 }
2700}
2701
Lloyd Pique99d3da52018-01-22 17:48:03 -08002702sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002703 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002704 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002705 const sp<IGraphicBufferProducer>& producer) {
2706 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002707 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002708 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002709 creationArgs.isSecure = state.isSecure;
2710 creationArgs.displaySurface = dispSurface;
2711 creationArgs.hasWideColorGamut = false;
2712 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002713
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002714 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002715 creationArgs.isPrimary = isInternalDisplay;
2716
2717 if (useColorManagement && displayId) {
2718 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002719 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002720 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002721 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002722 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002723
Dominik Laskowski7e045462018-05-30 13:02:02 -07002724 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002725 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002726 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002727 }
tangrobin6753a022018-08-10 10:58:54 +08002728 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002729
Dominik Laskowski075d3172018-05-24 15:50:06 -07002730 if (displayId) {
2731 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002732 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002733 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002734 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002735
Lloyd Pique90c115d2018-09-18 21:39:42 -07002736 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002737 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002738 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002739
Lloyd Pique99d3da52018-01-22 17:48:03 -08002740 // Make sure that composition can never be stalled by a virtual display
2741 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002742 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002743 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002744 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2745 }
2746
Dominik Laskowski075d3172018-05-24 15:50:06 -07002747 creationArgs.displayInstallOrientation =
2748 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002749
Lloyd Pique99d3da52018-01-22 17:48:03 -08002750 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002751 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002752
Lloyd Pique90c115d2018-09-18 21:39:42 -07002753 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002754
2755 if (maxFrameBufferAcquiredBuffers >= 3) {
2756 nativeWindowSurface->preallocateBuffers();
2757 }
2758
2759 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002760 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002761 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002762 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002763 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002764 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002765 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2766 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002767 if (!state.isVirtual()) {
2768 LOG_ALWAYS_FATAL_IF(!displayId);
2769 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002770 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002771
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002772 display->setLayerStack(state.layerStack);
2773 display->setProjection(state.orientation, state.viewport, state.frame);
2774 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002775
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002776 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002777}
2778
Lloyd Pique347200f2017-12-14 17:00:15 -08002779void SurfaceFlinger::processDisplayChangesLocked() {
2780 // here we take advantage of Vector's copy-on-write semantics to
2781 // improve performance by skipping the transaction entirely when
2782 // know that the lists are identical
2783 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2784 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2785 if (!curr.isIdenticalTo(draw)) {
2786 mVisibleRegionsDirty = true;
2787 const size_t cc = curr.size();
2788 size_t dc = draw.size();
2789
2790 // find the displays that were removed
2791 // (ie: in drawing state but not in current state)
2792 // also handle displays that changed
2793 // (ie: displays that are in both lists)
2794 for (size_t i = 0; i < dc;) {
2795 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2796 if (j < 0) {
2797 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002798 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002799 // Save display ID before disconnecting.
2800 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002801 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002802
2803 if (!display->isVirtual()) {
2804 LOG_ALWAYS_FATAL_IF(!displayId);
2805 dispatchDisplayHotplugEvent(displayId->value, false);
2806 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002807 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002808
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002809 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002810 } else {
2811 // this display is in both lists. see if something changed.
2812 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002813 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002814 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2815 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2816 if (state_binder != draw_binder) {
2817 // changing the surface is like destroying and
2818 // recreating the DisplayDevice, so we just remove it
2819 // from the drawing state, so that it get re-added
2820 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002821 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002822 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002823 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002824 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002825 mDrawingState.displays.removeItemsAt(i);
2826 dc--;
2827 // at this point we must loop to the next item
2828 continue;
2829 }
2830
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002831 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002832 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002833 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002834 }
2835 if ((state.orientation != draw[i].orientation) ||
2836 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002837 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002838 }
2839 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002840 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002841 }
2842 }
2843 }
2844 ++i;
2845 }
2846
2847 // find displays that were added
2848 // (ie: in current state but not in drawing state)
2849 for (size_t i = 0; i < cc; i++) {
2850 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2851 const DisplayDeviceState& state(curr[i]);
2852
Lloyd Pique542307f2018-10-19 13:24:08 -07002853 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002854 sp<IGraphicBufferProducer> producer;
2855 sp<IGraphicBufferProducer> bqProducer;
2856 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002857 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002858
Dominik Laskowski075d3172018-05-24 15:50:06 -07002859 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002860 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002861 // Virtual displays without a surface are dormant:
2862 // they have external state (layer stack, projection,
2863 // etc.) but no internal state (i.e. a DisplayDevice).
2864 if (state.surface != nullptr) {
2865 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002866 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002867 int width = 0;
2868 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2869 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2870 int height = 0;
2871 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2872 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2873 int intFormat = 0;
2874 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2875 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002876 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002877
Dominik Laskowski075d3172018-05-24 15:50:06 -07002878 displayId =
2879 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002880 }
2881
2882 // TODO: Plumb requested format back up to consumer
2883
2884 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002885 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002886 bqProducer, bqConsumer,
2887 state.displayName);
2888
2889 dispSurface = vds;
2890 producer = vds;
2891 }
2892 } else {
2893 ALOGE_IF(state.surface != nullptr,
2894 "adding a supported display, but rendering "
2895 "surface is provided (%p), ignoring it",
2896 state.surface.get());
2897
Dominik Laskowski075d3172018-05-24 15:50:06 -07002898 displayId = state.displayId;
2899 LOG_ALWAYS_FATAL_IF(!displayId);
2900 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002901 producer = bqProducer;
2902 }
2903
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002904 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002905 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002906 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002907 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002908 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002909 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002910 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002911 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002912 }
2913 }
2914 }
2915 }
2916 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002917
2918 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002919}
2920
Mathias Agopian87baae12012-07-31 12:38:26 -07002921void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002922{
Dan Stoza7dde5992015-05-22 09:51:44 -07002923 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002924 mCurrentState.traverseInZOrder([](Layer* layer) {
2925 layer->notifyAvailableFrames();
2926 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002927
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002928 /*
2929 * Traversal of the children
2930 * (perform the transaction for each of them if needed)
2931 */
2932
Mathias Agopian3559b072012-08-15 13:46:03 -07002933 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002934 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002935 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002936 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002937
2938 const uint32_t flags = layer->doTransaction(0);
2939 if (flags & Layer::eVisibleRegion)
2940 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002941
2942 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002943 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002944 }
Robert Carr2047fae2016-11-28 14:09:09 -08002945 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002946 }
2947
2948 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002949 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002950 */
2951
Mathias Agopiane57f2922012-08-09 16:29:12 -07002952 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002953 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002954 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002955 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002956
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002957 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002958 // The transform hint might have changed for some layers
2959 // (either because a display has changed, or because a layer
2960 // as changed).
2961 //
2962 // Walk through all the layers in currentLayers,
2963 // and update their transform hint.
2964 //
2965 // If a layer is visible only on a single display, then that
2966 // display is used to calculate the hint, otherwise we use the
2967 // default display.
2968 //
2969 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2970 // the hint is set before we acquire a buffer from the surface texture.
2971 //
2972 // NOTE: layer transactions have taken place already, so we use their
2973 // drawing state. However, SurfaceFlinger's own transaction has not
2974 // happened yet, so we must use the current state layer list
2975 // (soon to become the drawing state list).
2976 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002977 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002978 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002979 bool first = true;
2980 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002981 // NOTE: we rely on the fact that layers are sorted by
2982 // layerStack first (so we don't have to traverse the list
2983 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002984 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002985 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002986 currentlayerStack = layerStack;
2987 // figure out if this layerstack is mirrored
2988 // (more than one display) if so, pick the default display,
2989 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002990 hintDisplay = nullptr;
2991 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002992 if (display->getCompositionDisplay()
2993 ->belongsInOutput(layer->getLayerStack(),
2994 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002995 if (hintDisplay) {
2996 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002997 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002998 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002999 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08003000 }
3001 }
3002 }
3003 }
Chet Haase91d25932013-04-11 15:24:55 -07003004
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003005 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003006 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
3007 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08003008
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003009 // could be null when this layer is using a layerStack
3010 // that is not visible on any display. Also can occur at
3011 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003012 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08003013 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003014
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003015 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003016 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003017 if (hintDisplay) {
3018 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08003019 }
Robert Carr2047fae2016-11-28 14:09:09 -08003020
3021 first = false;
3022 });
Mathias Agopian84300952012-11-21 16:02:13 -08003023 }
3024
3025
Mathias Agopian3559b072012-08-15 13:46:03 -07003026 /*
3027 * Perform our own transaction if needed
3028 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07003029
3030 if (mLayersAdded) {
3031 mLayersAdded = false;
3032 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07003033 mVisibleRegionsDirty = true;
3034 }
3035
3036 // some layers might have been removed, so
3037 // we need to update the regions they're exposing.
3038 if (mLayersRemoved) {
3039 mLayersRemoved = false;
3040 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08003041 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003042 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07003043 // this layer is not visible anymore
3044 // TODO: we could traverse the tree from front to back and
3045 // compute the actual visible region
3046 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003047 Region visibleReg;
3048 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07003049 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07003050 }
Robert Carr2047fae2016-11-28 14:09:09 -08003051 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003052 }
3053
3054 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07003055}
3056
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003057void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003058 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003059 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08003060 return;
3061 }
3062
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003063 if (mVisibleRegionsDirty || mInputInfoChanged) {
3064 mInputInfoChanged = false;
3065 updateInputWindowInfo();
3066 }
3067
3068 executeInputWindowCommands();
3069}
3070
3071void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07003072 Vector<InputWindowInfo> inputHandles;
3073
3074 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
3075 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08003076 // When calculating the screen bounds we ignore the transparent region since it may
3077 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08003078 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07003079 }
3080 });
3081 mInputFlinger->setInputWindows(inputHandles);
3082}
3083
chaviwfbe5d9c2018-12-26 12:23:37 -08003084void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08003085 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3086 if (transferTouchFocusCommand.fromToken != nullptr &&
3087 transferTouchFocusCommand.toToken != nullptr &&
3088 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3089 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3090 transferTouchFocusCommand.toToken);
3091 }
3092 }
3093
3094 mInputWindowCommands.clear();
3095}
3096
Riley Andrews03414a12014-07-01 14:22:59 -07003097void SurfaceFlinger::updateCursorAsync()
3098{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003099 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003100 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003101 continue;
3102 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003103
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003104 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3105 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003106 }
3107 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003108}
3109
chaviw61626f22018-11-15 16:26:27 -08003110void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3111 if (layer->hasReadyFrame()) {
3112 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3113 if (layer->shouldPresentNow(expectedPresentTime)) {
3114 bool ignored = false;
3115 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3116 }
3117 }
3118 layer->releasePendingBuffer(systemTime());
3119}
3120
Mathias Agopian4fec8732012-06-29 14:12:52 -07003121void SurfaceFlinger::commitTransaction()
3122{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003123 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003124 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003125 for (const auto& l : mLayersPendingRemoval) {
3126 recordBufferingStats(l->getName().string(),
3127 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003128
3129 // We need to release the HWC layers when the Layer is removed
3130 // from the current state otherwise the HWC layer just continues
3131 // showing at its last configured state until we eventually
3132 // abandon the buffer queue.
3133 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003134 l->destroyHwcLayersForAllDisplays();
3135 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003136 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003137 }
3138 mLayersPendingRemoval.clear();
3139 }
3140
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003141 // If this transaction is part of a window animation then the next frame
3142 // we composite should be considered an animation as well.
3143 mAnimCompositionPending = mAnimTransactionPending;
3144
Mathias Agopian4fec8732012-06-29 14:12:52 -07003145 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003146 // clear the "changed" flags in current state
3147 mCurrentState.colorMatrixChanged = false;
3148
Robert Carr1f0a16a2016-10-24 16:27:39 -07003149 mDrawingState.traverseInZOrder([](Layer* layer) {
3150 layer->commitChildList();
3151 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003152 mTransactionPending = false;
3153 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003154 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003155}
3156
Lloyd Pique32cbe282018-10-19 13:09:22 -07003157void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003158 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003159 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003160 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003161
Lloyd Pique32cbe282018-10-19 13:09:22 -07003162 auto display = displayDevice->getCompositionDisplay();
3163
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003164 Region aboveOpaqueLayers;
3165 Region aboveCoveredLayers;
3166 Region dirty;
3167
Mathias Agopian87baae12012-07-31 12:38:26 -07003168 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003169
Robert Carr2047fae2016-11-28 14:09:09 -08003170 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003171 // start with the whole surface at its current location
3172 const Layer::State& s(layer->getDrawingState());
3173
Jesse Hall01e29052013-02-19 16:13:35 -08003174 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003175 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003176 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003177 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003178
Mathias Agopianab028732010-03-16 16:41:46 -07003179 /*
3180 * opaqueRegion: area of a surface that is fully opaque.
3181 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003182 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003183
3184 /*
3185 * visibleRegion: area of a surface that is visible on screen
3186 * and not fully transparent. This is essentially the layer's
3187 * footprint minus the opaque regions above it.
3188 * Areas covered by a translucent surface are considered visible.
3189 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003190 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003191
3192 /*
3193 * coveredRegion: area of a surface that is covered by all
3194 * visible regions above it (which includes the translucent areas).
3195 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003196 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003197
Jesse Halla8026d22012-09-25 13:25:04 -07003198 /*
3199 * transparentRegion: area of a surface that is hinted to be completely
3200 * transparent. This is only used to tell when the layer has no visible
3201 * non-transparent regions and can be removed from the layer list. It
3202 * does not affect the visibleRegion of this layer or any layers
3203 * beneath it. The hint may not be correct if apps don't respect the
3204 * SurfaceView restrictions (which, sadly, some don't).
3205 */
3206 Region transparentRegion;
3207
Mathias Agopianab028732010-03-16 16:41:46 -07003208
3209 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003210 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003211 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003212 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003213
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003214 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003215 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003216 if (!visibleRegion.isEmpty()) {
3217 // Remove the transparent area from the visible region
3218 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003219 if (tr.preserveRects()) {
3220 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003221 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003222 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003223 // transformation too complex, can't do the
3224 // transparent region optimization.
3225 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003226 }
Mathias Agopianab028732010-03-16 16:41:46 -07003227 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003228
Mathias Agopianab028732010-03-16 16:41:46 -07003229 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003230 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003231 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003232 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003233 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003234 // the opaque region is the layer's footprint
3235 opaqueRegion = visibleRegion;
3236 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003237 }
3238 }
3239
Robert Carre5f4f692018-01-12 13:12:28 -08003240 if (visibleRegion.isEmpty()) {
3241 layer->clearVisibilityRegions();
3242 return;
3243 }
3244
Mathias Agopianab028732010-03-16 16:41:46 -07003245 // Clip the covered region to the visible region
3246 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3247
3248 // Update aboveCoveredLayers for next (lower) layer
3249 aboveCoveredLayers.orSelf(visibleRegion);
3250
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003251 // subtract the opaque region covered by the layers above us
3252 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003253
3254 // compute this layer's dirty region
3255 if (layer->contentDirty) {
3256 // we need to invalidate the whole region
3257 dirty = visibleRegion;
3258 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003259 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003260 layer->contentDirty = false;
3261 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003262 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003263 * the exposed region consists of two components:
3264 * 1) what's VISIBLE now and was COVERED before
3265 * 2) what's EXPOSED now less what was EXPOSED before
3266 *
3267 * note that (1) is conservative, we start with the whole
3268 * visible region but only keep what used to be covered by
3269 * something -- which mean it may have been exposed.
3270 *
3271 * (2) handles areas that were not covered by anything but got
3272 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003273 */
Mathias Agopianab028732010-03-16 16:41:46 -07003274 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003275 const Region oldVisibleRegion = layer->visibleRegion;
3276 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003277 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3278 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003279 }
3280 dirty.subtractSelf(aboveOpaqueLayers);
3281
3282 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003283 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003284
Mathias Agopianab028732010-03-16 16:41:46 -07003285 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003286 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003287
Jesse Halla8026d22012-09-25 13:25:04 -07003288 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003289 layer->setVisibleRegion(visibleRegion);
3290 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003291 layer->setVisibleNonTransparentRegion(
3292 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003293 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003294
Mathias Agopian87baae12012-07-31 12:38:26 -07003295 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003296}
3297
Chia-I Wuab0c3192017-08-01 11:29:00 -07003298void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003299 for (const auto& [token, displayDevice] : mDisplays) {
3300 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003301 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003302 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003303 }
3304 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003305}
3306
Daniel Solomon42d04562019-01-20 21:03:19 -08003307void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3308 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3309 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3310 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3311 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3312 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3313 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3314 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3315 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3316 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3317 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3318 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3319 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3320}
3321
Dan Stoza6b9454d2014-11-07 16:00:59 -08003322bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003323{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003324 ALOGV("handlePageFlip");
3325
Brian Andersond6927fb2016-07-23 23:37:30 -07003326 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003327
Mathias Agopian4fec8732012-06-29 14:12:52 -07003328 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003329 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003330 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003331
3332 // Store the set of layers that need updates. This set must not change as
3333 // buffers are being latched, as this could result in a deadlock.
3334 // Example: Two producers share the same command stream and:
3335 // 1.) Layer 0 is latched
3336 // 2.) Layer 0 gets a new frame
3337 // 2.) Layer 1 gets a new frame
3338 // 3.) Layer 1 is latched.
3339 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3340 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003341 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003342 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003343 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003344 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3345 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003346 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003347 } else {
3348 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003349 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003350 } else {
3351 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003352 }
Robert Carr2047fae2016-11-28 14:09:09 -08003353 });
3354
Lloyd Piquef2c79392018-12-20 16:23:33 -08003355 if (!mLayersWithQueuedFrames.empty()) {
3356 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3357 // writes to Layer current state. See also b/119481871
3358 Mutex::Autolock lock(mStateLock);
3359
3360 for (auto& layer : mLayersWithQueuedFrames) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003361 if (layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence)) {
3362 mLayersPendingRefresh.push_back(layer);
3363 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003364 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003365 if (layer->isBufferLatched()) {
3366 newDataLatched = true;
3367 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003368 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003369 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003370
Alec Mouri86770e52018-09-24 22:40:58 +00003371 // Clear the renderengine fence here...
3372 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3373 // clear instead of sp::clear.
3374 getBE().flushFence = Fence::NO_FENCE;
3375
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003376 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003377
3378 // If we will need to wake up at some time in the future to deal with a
3379 // queued frame that shouldn't be displayed during this vsync period, wake
3380 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003381 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003382 signalLayerUpdate();
3383 }
3384
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003385 // enter boot animation on first buffer latch
3386 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3387 ALOGI("Enter boot animation");
3388 mBootStage = BootStage::BOOTANIMATION;
3389 }
3390
Dan Stoza6b9454d2014-11-07 16:00:59 -08003391 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003392 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003393}
3394
Mathias Agopianad456f92011-01-13 17:53:01 -08003395void SurfaceFlinger::invalidateHwcGeometry()
3396{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003397 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003398}
3399
Lloyd Pique32cbe282018-10-19 13:09:22 -07003400void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003401 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003402 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003403 // We only need to actually compose the display if:
3404 // 1) It is being handled by hardware composer, which may need this to
3405 // keep its virtual display state machine in sync, or
3406 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003407 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003408 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003409 return;
3410 }
3411
Dan Stoza9e56aa02015-11-02 13:00:03 -08003412 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003413 base::unique_fd readyFence;
3414 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003415
3416 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003417 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003418}
3419
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003420bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3421 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003422 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003423 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003424
Lloyd Pique32cbe282018-10-19 13:09:22 -07003425 auto display = displayDevice->getCompositionDisplay();
3426 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003427 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003428
3429 const Region bounds(displayState.bounds);
3430 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003431 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003432 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003433
Peiyong Lind3788632018-09-18 16:01:31 -07003434 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003435 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003436
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003437 renderengine::DisplaySettings clientCompositionDisplay;
3438 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3439 sp<GraphicBuffer> buf;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003440
Dan Stoza9e56aa02015-11-02 13:00:03 -08003441 if (hasClientComposition) {
3442 ALOGV("hasClientComposition");
3443
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003444 buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003445
3446 if (buf == nullptr) {
3447 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3448 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003449 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003450 return false;
3451 }
3452
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003453 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3454 clientCompositionDisplay.clip = displayState.scissor;
3455 const ui::Transform& displayTransform = displayState.transform;
3456 mat4 m;
3457 m[0][0] = displayTransform[0][0];
3458 m[0][1] = displayTransform[0][1];
3459 m[0][3] = displayTransform[0][2];
3460 m[1][0] = displayTransform[1][0];
3461 m[1][1] = displayTransform[1][1];
3462 m[1][3] = displayTransform[1][2];
3463 m[3][0] = displayTransform[2][0];
3464 m[3][1] = displayTransform[2][1];
3465 m[3][3] = displayTransform[2][2];
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003466
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003467 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003468
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003469 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003470 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003471 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003472 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003473 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003474 clientCompositionDisplay.outputDataspace = outputDataspace;
3475 clientCompositionDisplay.maxLuminance =
3476 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003477
Lloyd Pique441d5042018-10-18 16:49:51 -07003478 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003479 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003480 getHwComposer()
3481 .hasDisplayCapability(displayId,
3482 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003483
Peiyong Lind3788632018-09-18 16:01:31 -07003484 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003485 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3486 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003487 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003488 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003489 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003490
Mathias Agopian85d751c2012-08-29 16:59:24 -07003491 /*
3492 * and then, render the layers targeted at the framebuffer
3493 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003494
Dan Stoza9e56aa02015-11-02 13:00:03 -08003495 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003496 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003497 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003498 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003499 const Region viewportRegion(displayState.viewport);
3500 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003501 ALOGV("Layer: %s", layer->getName().string());
3502 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003503 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003504 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003505 case HWC2::Composition::Cursor:
3506 case HWC2::Composition::Device:
3507 case HWC2::Composition::Sideband:
3508 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003509 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003510 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003511 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003512 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003513 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003514 // never clear the very first layer since we're
3515 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003516 renderengine::LayerSettings layerSettings;
3517 Region dummyRegion;
3518 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3519 layerSettings);
3520
3521 if (prepared) {
3522 layerSettings.source.buffer.buffer = nullptr;
3523 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3524 layerSettings.alpha = half(0.0);
3525 layerSettings.disableBlending = true;
3526 clientCompositionLayers.push_back(layerSettings);
3527 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003528 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003529 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003530 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003531 case HWC2::Composition::Client: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003532 renderengine::LayerSettings layerSettings;
3533 bool prepared =
3534 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3535 if (prepared) {
3536 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003537 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003538 break;
3539 }
3540 default:
3541 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003542 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003543 } else {
3544 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003545 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003546 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003547 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003548
Alec Mouri820c7402019-01-23 13:02:39 -08003549 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003550 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003551 clientCompositionDisplay.clearRegion = clearRegion;
3552 if (!debugRegion.isEmpty()) {
3553 Region::const_iterator it = debugRegion.begin();
3554 Region::const_iterator end = debugRegion.end();
3555 while (it != end) {
3556 const Rect& rect = *it++;
3557 renderengine::LayerSettings layerSettings;
3558 layerSettings.source.buffer.buffer = nullptr;
3559 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3560 layerSettings.geometry.boundaries = rect.toFloatRect();
3561 layerSettings.alpha = half(1.0);
3562 clientCompositionLayers.push_back(layerSettings);
3563 }
3564 }
3565 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
3566 buf->getNativeBuffer(), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003567 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003568 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003569}
3570
Chia-I Wu28e3a252018-09-07 12:05:02 -07003571void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003572 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003573 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003574}
3575
Dan Stoza7d89d062015-04-30 13:29:25 -07003576status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003577 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003578 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003579 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003580 const sp<Layer>& parent,
3581 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003582{
Dan Stoza7d89d062015-04-30 13:29:25 -07003583 // add this layer to the current state list
3584 {
3585 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003586 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003587 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3588 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003589 return NO_MEMORY;
3590 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003591 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003592 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003593 } else if (parent == nullptr) {
3594 lbc->onRemovedFromCurrentState();
3595 } else if (parent->isRemovedFromCurrentState()) {
3596 parent->addChild(lbc);
3597 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003598 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003599 parent->addChild(lbc);
3600 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003601
Yiwei Zhang243b3782018-05-15 17:40:04 -07003602 if (gbc != nullptr) {
3603 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3604 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3605 mMaxGraphicBufferProducerListSize,
3606 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3607 mGraphicBufferProducerList.size(),
3608 mMaxGraphicBufferProducerListSize, mNumLayers);
3609 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003610 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003611 }
3612
Mathias Agopian96f08192010-06-02 23:28:45 -07003613 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003614 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003615
Dan Stoza7d89d062015-04-30 13:29:25 -07003616 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003617}
3618
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003619uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003620 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003621}
3622
Mathias Agopian3f844832013-08-07 21:24:32 -07003623uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003624 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003625}
3626
Mathias Agopian3f844832013-08-07 21:24:32 -07003627uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003628 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003629}
3630
3631uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003632 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003633 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003634 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003635 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003636 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003637 }
3638 return old;
3639}
3640
Marissa Wall713b63f2018-10-17 15:42:43 -07003641bool SurfaceFlinger::flushTransactionQueues() {
3642 Mutex::Autolock _l(mStateLock);
3643 auto it = mTransactionQueues.begin();
3644 while (it != mTransactionQueues.end()) {
3645 auto& [applyToken, transactionQueue] = *it;
3646
3647 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003648 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3649 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003650 break;
3651 }
chaviw273171b2018-12-26 11:46:30 -08003652 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003653 transactionQueue.pop();
3654 }
3655
3656 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3657 }
3658 return mTransactionQueues.empty();
3659}
3660
chaviwca27f252018-02-06 16:46:39 -08003661bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3662 for (const ComposerState& state : states) {
3663 // Here we need to check that the interface we're given is indeed
3664 // one of our own. A malicious client could give us a nullptr
3665 // IInterface, or one of its own or even one of our own but a
3666 // different type. All these situations would cause us to crash.
3667 if (state.client == nullptr) {
3668 return true;
3669 }
3670
3671 sp<IBinder> binder = IInterface::asBinder(state.client);
3672 if (binder == nullptr) {
3673 return true;
3674 }
3675
3676 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3677 return true;
3678 }
3679 }
3680 return false;
3681}
3682
Marissa Wall17b4e452018-12-26 16:32:34 -08003683bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3684 const Vector<ComposerState>& states) {
3685 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3686 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3687 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3688 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3689 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3690 return false;
3691 }
3692
Marissa Wall713b63f2018-10-17 15:42:43 -07003693 for (const ComposerState& state : states) {
3694 const layer_state_t& s = state.state;
3695 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3696 continue;
3697 }
3698 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003699 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003700 }
3701 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003702 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003703}
3704
3705void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3706 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003707 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003708 const InputWindowCommands& inputWindowCommands,
3709 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003710 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003711 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003712
chaviwca27f252018-02-06 16:46:39 -08003713 if (containsAnyInvalidClientState(states)) {
3714 return;
3715 }
3716
Marissa Wall713b63f2018-10-17 15:42:43 -07003717 // If its TransactionQueue already has a pending TransactionState or if it is pending
3718 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003719 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3720 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003721 setTransactionFlags(eTransactionNeeded);
3722 return;
3723 }
3724
chaviw273171b2018-12-26 11:46:30 -08003725 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003726}
3727
3728void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003729 const Vector<DisplayState>& displays, uint32_t flags,
3730 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003731 uint32_t transactionFlags = 0;
3732
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003733 if (flags & eAnimation) {
3734 // For window updates that are part of an animation we must wait for
3735 // previous animation "frames" to be handled.
3736 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003737 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003738 if (CC_UNLIKELY(err != NO_ERROR)) {
3739 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003740 // caller after a few seconds.
3741 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3742 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003743 mAnimTransactionPending = false;
3744 break;
3745 }
3746 }
3747 }
3748
chaviwca27f252018-02-06 16:46:39 -08003749 for (const DisplayState& display : displays) {
3750 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003751 }
3752
Marissa Walle2ffb422018-10-12 11:33:52 -07003753 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003754 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003755 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003756 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003757 // If the state doesn't require a traversal and there are callbacks, send them now
3758 if (!(clientStateFlags & eTraversalNeeded)) {
3759 mTransactionCompletedThread.sendCallbacks();
3760 }
3761 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003762
chaviw273171b2018-12-26 11:46:30 -08003763 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3764
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003765 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3766 // anyway. This can be used as a flush mechanism for previous async transactions.
3767 // Empty animation transaction can be used to simulate back-pressure, so also force a
3768 // transaction for empty animation transactions.
3769 if (transactionFlags == 0 &&
3770 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003771 transactionFlags = eTransactionNeeded;
3772 }
3773
Mathias Agopian386aa982011-11-07 21:58:03 -08003774 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003775 if (mInterceptor->isEnabled()) {
3776 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003777 }
Irvel468051e2016-06-13 16:44:44 -07003778
Mathias Agopian386aa982011-11-07 21:58:03 -08003779 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003780 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3781 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003782 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003783
3784 // if this is a synchronous transaction, wait for it to take effect
3785 // before returning.
3786 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003787 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003788 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003789 if (flags & eAnimation) {
3790 mAnimTransactionPending = true;
3791 }
3792 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003793 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3794 if (CC_UNLIKELY(err != NO_ERROR)) {
3795 // just in case something goes wrong in SF, return to the
3796 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003797 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3798 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003799 break;
3800 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003801 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003802 }
3803}
3804
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003805uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3806 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3807 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003808
Mathias Agopiane57f2922012-08-09 16:29:12 -07003809 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003810 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3811
3812 const uint32_t what = s.what;
3813 if (what & DisplayState::eSurfaceChanged) {
3814 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3815 state.surface = s.surface;
3816 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003817 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003818 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003819 if (what & DisplayState::eLayerStackChanged) {
3820 if (state.layerStack != s.layerStack) {
3821 state.layerStack = s.layerStack;
3822 flags |= eDisplayTransactionNeeded;
3823 }
3824 }
3825 if (what & DisplayState::eDisplayProjectionChanged) {
3826 if (state.orientation != s.orientation) {
3827 state.orientation = s.orientation;
3828 flags |= eDisplayTransactionNeeded;
3829 }
3830 if (state.frame != s.frame) {
3831 state.frame = s.frame;
3832 flags |= eDisplayTransactionNeeded;
3833 }
3834 if (state.viewport != s.viewport) {
3835 state.viewport = s.viewport;
3836 flags |= eDisplayTransactionNeeded;
3837 }
3838 }
3839 if (what & DisplayState::eDisplaySizeChanged) {
3840 if (state.width != s.width) {
3841 state.width = s.width;
3842 flags |= eDisplayTransactionNeeded;
3843 }
3844 if (state.height != s.height) {
3845 state.height = s.height;
3846 flags |= eDisplayTransactionNeeded;
3847 }
3848 }
3849
Mathias Agopiane57f2922012-08-09 16:29:12 -07003850 return flags;
3851}
3852
Robert Carrd4ae7f32018-06-07 16:10:57 -07003853bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3854 IPCThreadState* ipc = IPCThreadState::self();
3855 const int pid = ipc->getCallingPid();
3856 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003857 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003858 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003859 return false;
3860 }
3861 return true;
3862}
3863
chaviwca27f252018-02-06 16:46:39 -08003864uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3865 const layer_state_t& s = composerState.state;
3866 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3867
Mathias Agopian13127d82013-03-05 17:47:11 -08003868 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003869 if (layer == nullptr) {
3870 return 0;
3871 }
3872
chaviw8b3871a2017-11-01 17:41:01 -07003873 uint32_t flags = 0;
3874
Garfield Tan8a3083e2018-12-03 13:21:07 -08003875 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003876 bool geometryAppliesWithResize =
3877 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003878
3879 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3880 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003881 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003882 layer->pushPendingState();
3883 }
3884
chaviw8b3871a2017-11-01 17:41:01 -07003885 if (what & layer_state_t::ePositionChanged) {
3886 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3887 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003888 }
chaviw8b3871a2017-11-01 17:41:01 -07003889 }
3890 if (what & layer_state_t::eLayerChanged) {
3891 // NOTE: index needs to be calculated before we update the state
3892 const auto& p = layer->getParent();
3893 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003894 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003895 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003896 mCurrentState.layersSortedByZ.removeAt(idx);
3897 mCurrentState.layersSortedByZ.add(layer);
3898 // we need traversal (state changed)
3899 // AND transaction (list changed)
3900 flags |= eTransactionNeeded|eTraversalNeeded;
3901 }
chaviw8b3871a2017-11-01 17:41:01 -07003902 } else {
3903 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003904 flags |= eTransactionNeeded|eTraversalNeeded;
3905 }
3906 }
chaviw8b3871a2017-11-01 17:41:01 -07003907 }
3908 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003909 // NOTE: index needs to be calculated before we update the state
3910 const auto& p = layer->getParent();
3911 if (p == nullptr) {
3912 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3913 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3914 mCurrentState.layersSortedByZ.removeAt(idx);
3915 mCurrentState.layersSortedByZ.add(layer);
3916 // we need traversal (state changed)
3917 // AND transaction (list changed)
3918 flags |= eTransactionNeeded|eTraversalNeeded;
3919 }
3920 } else {
3921 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3922 flags |= eTransactionNeeded|eTraversalNeeded;
3923 }
chaviw8b3871a2017-11-01 17:41:01 -07003924 }
3925 }
3926 if (what & layer_state_t::eSizeChanged) {
3927 if (layer->setSize(s.w, s.h)) {
3928 flags |= eTraversalNeeded;
3929 }
3930 }
3931 if (what & layer_state_t::eAlphaChanged) {
3932 if (layer->setAlpha(s.alpha))
3933 flags |= eTraversalNeeded;
3934 }
3935 if (what & layer_state_t::eColorChanged) {
3936 if (layer->setColor(s.color))
3937 flags |= eTraversalNeeded;
3938 }
Peiyong Lind3788632018-09-18 16:01:31 -07003939 if (what & layer_state_t::eColorTransformChanged) {
3940 if (layer->setColorTransform(s.colorTransform)) {
3941 flags |= eTraversalNeeded;
3942 }
3943 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003944 if (what & layer_state_t::eBackgroundColorChanged) {
3945 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3946 flags |= eTraversalNeeded;
3947 }
3948 }
chaviw8b3871a2017-11-01 17:41:01 -07003949 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003950 // TODO: b/109894387
3951 //
3952 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3953 // rotation. To see the problem observe that if we have a square parent, and a child
3954 // of the same size, then we rotate the child 45 degrees around it's center, the child
3955 // must now be cropped to a non rectangular 8 sided region.
3956 //
3957 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3958 // private API, and the WindowManager only uses rotation in one case, which is on a top
3959 // level layer in which cropping is not an issue.
3960 //
3961 // However given that abuse of rotation matrices could lead to surfaces extending outside
3962 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3963 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3964 // transformations.
3965 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003966 flags |= eTraversalNeeded;
3967 }
3968 if (what & layer_state_t::eTransparentRegionChanged) {
3969 if (layer->setTransparentRegionHint(s.transparentRegion))
3970 flags |= eTraversalNeeded;
3971 }
3972 if (what & layer_state_t::eFlagsChanged) {
3973 if (layer->setFlags(s.flags, s.mask))
3974 flags |= eTraversalNeeded;
3975 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003976 if (what & layer_state_t::eCropChanged_legacy) {
3977 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003978 flags |= eTraversalNeeded;
3979 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003980 if (what & layer_state_t::eCornerRadiusChanged) {
3981 if (layer->setCornerRadius(s.cornerRadius))
3982 flags |= eTraversalNeeded;
3983 }
chaviw8b3871a2017-11-01 17:41:01 -07003984 if (what & layer_state_t::eLayerStackChanged) {
3985 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3986 // We only allow setting layer stacks for top level layers,
3987 // everything else inherits layer stack from its parent.
3988 if (layer->hasParent()) {
3989 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3990 layer->getName().string());
3991 } else if (idx < 0) {
3992 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3993 "that also does not appear in the top level layer list. Something"
3994 " has gone wrong.", layer->getName().string());
3995 } else if (layer->setLayerStack(s.layerStack)) {
3996 mCurrentState.layersSortedByZ.removeAt(idx);
3997 mCurrentState.layersSortedByZ.add(layer);
3998 // we need traversal (state changed)
3999 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07004000 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07004001 }
4002 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004003 if (what & layer_state_t::eDeferTransaction_legacy) {
4004 if (s.barrierHandle_legacy != nullptr) {
4005 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
4006 } else if (s.barrierGbp_legacy != nullptr) {
4007 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07004008 if (authenticateSurfaceTextureLocked(gbp)) {
4009 const auto& otherLayer =
4010 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07004011 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07004012 } else {
4013 ALOGE("Attempt to defer transaction to to an"
4014 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08004015 }
4016 }
chaviw8b3871a2017-11-01 17:41:01 -07004017 // We don't trigger a traversal here because if no other state is
4018 // changed, we don't want this to cause any more work
4019 }
4020 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08004021 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07004022 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08004023 if (!hadParent) {
4024 mCurrentState.layersSortedByZ.remove(layer);
4025 }
chaviw8b3871a2017-11-01 17:41:01 -07004026 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08004027 }
chaviw8b3871a2017-11-01 17:41:01 -07004028 }
4029 if (what & layer_state_t::eReparentChildren) {
4030 if (layer->reparentChildren(s.reparentHandle)) {
4031 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07004032 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004033 }
chaviw8b3871a2017-11-01 17:41:01 -07004034 if (what & layer_state_t::eDetachChildren) {
4035 layer->detachChildren();
4036 }
4037 if (what & layer_state_t::eOverrideScalingModeChanged) {
4038 layer->setOverrideScalingMode(s.overrideScalingMode);
4039 // We don't trigger a traversal here because if no other state is
4040 // changed, we don't want this to cause any more work
4041 }
Marissa Wall61c58622018-07-18 10:12:20 -07004042 if (what & layer_state_t::eTransformChanged) {
4043 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4044 }
4045 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4046 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4047 flags |= eTraversalNeeded;
4048 }
4049 if (what & layer_state_t::eCropChanged) {
4050 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4051 }
Marissa Wall861616d2018-10-22 12:52:23 -07004052 if (what & layer_state_t::eFrameChanged) {
4053 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4054 }
Marissa Wall61c58622018-07-18 10:12:20 -07004055 if (what & layer_state_t::eAcquireFenceChanged) {
4056 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4057 }
4058 if (what & layer_state_t::eDataspaceChanged) {
4059 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4060 }
4061 if (what & layer_state_t::eHdrMetadataChanged) {
4062 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4063 }
4064 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4065 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4066 }
4067 if (what & layer_state_t::eApiChanged) {
4068 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4069 }
4070 if (what & layer_state_t::eSidebandStreamChanged) {
4071 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4072 }
Robert Carr720e5062018-07-30 17:45:14 -07004073 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004074 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
4075 layer->setInputInfo(s.inputInfo);
4076 flags |= eTraversalNeeded;
4077 } else {
4078 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4079 }
Robert Carr720e5062018-07-30 17:45:14 -07004080 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004081 if (what & layer_state_t::eMetadataChanged) {
4082 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4083 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004084 std::vector<sp<CallbackHandle>> callbackHandles;
4085 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
4086 mTransactionCompletedThread.run();
4087 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
4088 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4089 }
4090 }
Marissa Wall73411622019-01-25 10:45:41 -08004091
4092 if (what & layer_state_t::eBufferChanged) {
4093 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
4094 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
4095 s.buffer);
4096 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004097 if (what & layer_state_t::eCachedBufferChanged) {
4098 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08004099 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
4100 s.cachedBuffer.bufferId);
Marissa Wallebc2c052019-01-16 19:16:55 -08004101 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4102 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004103 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4104 // Do not put anything that updates layer state or modifies flags after
4105 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004106 return flags;
4107}
4108
chaviw273171b2018-12-26 11:46:30 -08004109uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4110 uint32_t flags = 0;
4111 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4112 flags |= eTraversalNeeded;
4113 }
4114
4115 mInputWindowCommands.merge(inputWindowCommands);
4116 return flags;
4117}
4118
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004119status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4120 uint32_t h, PixelFormat format, uint32_t flags,
4121 LayerMetadata metadata, sp<IBinder>* handle,
4122 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004123 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004124 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004125 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004126 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004127 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004128
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004129 status_t result = NO_ERROR;
4130
4131 sp<Layer> layer;
4132
Cody Northropbc755282017-03-31 12:00:08 -06004133 String8 uniqueName = getUniqueLayerName(name);
4134
Mathias Agopian3165cc22012-08-08 19:42:09 -07004135 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004136 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004137 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4138 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004139
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004140 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004141 case ISurfaceComposerClient::eFXSurfaceBufferState:
4142 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4143 break;
chaviw13fdc492017-06-27 12:40:18 -07004144 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004145 // check if buffer size is set for color layer.
4146 if (w > 0 || h > 0) {
4147 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4148 int(w), int(h));
4149 return BAD_VALUE;
4150 }
4151
chaviw13fdc492017-06-27 12:40:18 -07004152 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004153 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004154 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004155 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004156 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004157 // check if buffer size is set for container layer.
4158 if (w > 0 || h > 0) {
4159 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4160 int(w), int(h));
4161 return BAD_VALUE;
4162 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004163 result = createContainerLayer(client,
4164 uniqueName, w, h, flags,
4165 handle, &layer);
4166 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004167 default:
4168 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004169 break;
4170 }
4171
Dan Stoza7d89d062015-04-30 13:29:25 -07004172 if (result != NO_ERROR) {
4173 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004174 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004175
Chia-I Wuab0c3192017-08-01 11:29:00 -07004176 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4177 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004178 if (metadata.has(METADATA_WINDOW_TYPE)) {
4179 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4180 if (windowType == 441731) {
4181 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4182 layer->setPrimaryDisplayOnly();
4183 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004184 }
4185
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004186 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004187
Robert Carrb89ea9d2018-12-10 13:01:14 -08004188 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4189 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4190 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004191 if (result != NO_ERROR) {
4192 return result;
4193 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004194 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004195
4196 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004197 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004198}
4199
Cody Northropbc755282017-03-31 12:00:08 -06004200String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4201{
4202 bool matchFound = true;
4203 uint32_t dupeCounter = 0;
4204
4205 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4206 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4207
Dan Stoza436ccf32018-06-21 12:10:12 -07004208 // Grab the state lock since we're accessing mCurrentState
4209 Mutex::Autolock lock(mStateLock);
4210
Cody Northropbc755282017-03-31 12:00:08 -06004211 // Loop over layers until we're sure there is no matching name
4212 while (matchFound) {
4213 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004214 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004215 if (layer->getName() == uniqueName) {
4216 matchFound = true;
4217 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4218 }
4219 });
4220 }
4221
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004222 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4223 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004224
4225 return uniqueName;
4226}
4227
Marissa Wallfd668622018-05-10 10:21:13 -07004228status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4229 uint32_t w, uint32_t h, uint32_t flags,
4230 PixelFormat& format, sp<IBinder>* handle,
4231 sp<IGraphicBufferProducer>* gbp,
4232 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004233 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004234 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004235 case PIXEL_FORMAT_TRANSPARENT:
4236 case PIXEL_FORMAT_TRANSLUCENT:
4237 format = PIXEL_FORMAT_RGBA_8888;
4238 break;
4239 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004240 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004241 break;
4242 }
4243
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004244 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004245 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004246 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004247 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004248 *handle = layer->getHandle();
4249 *gbp = layer->getProducer();
4250 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004251 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004252
Marissa Wallfd668622018-05-10 10:21:13 -07004253 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004254 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004255}
4256
Marissa Wall61c58622018-07-18 10:12:20 -07004257status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4258 uint32_t w, uint32_t h, uint32_t flags,
4259 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004260 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004261 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004262 *handle = layer->getHandle();
4263 *outLayer = layer;
4264
4265 return NO_ERROR;
4266}
4267
chaviw13fdc492017-06-27 12:40:18 -07004268status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004269 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004270 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004271{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004272 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004273 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004274 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004275}
4276
Robert Carr6b3f6c52018-08-13 13:05:17 -07004277status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4278 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4279 sp<IBinder>* handle, sp<Layer>* outLayer)
4280{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004281 *outLayer =
4282 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004283 *handle = (*outLayer)->getHandle();
4284 return NO_ERROR;
4285}
4286
4287
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004288void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004289 mLayersPendingRemoval.add(layer);
4290 mLayersRemoved = true;
4291 setTransactionFlags(eTransactionNeeded);
4292}
4293
Robert Carr695d5282018-12-18 15:27:58 -08004294void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004295{
Robert Carr2e102c92018-10-23 12:11:15 -07004296 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004297 // If a layer has a parent, we allow it to out-live it's handle
4298 // with the idea that the parent holds a reference and will eventually
4299 // be cleaned up. However no one cleans up the top-level so we do so
4300 // here.
4301 if (layer->getParent() == nullptr) {
4302 mCurrentState.layersSortedByZ.remove(layer);
4303 }
4304 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004305 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004306}
4307
Mathias Agopianb60314a2012-04-10 22:09:54 -07004308// ---------------------------------------------------------------------------
4309
Andy McFadden13a082e2012-08-24 10:16:42 -07004310void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004311 const auto display = getDefaultDisplayDeviceLocked();
4312 if (!display) return;
4313
4314 const sp<IBinder> token = display->getDisplayToken().promote();
4315 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004316
Jesse Hall01e29052013-02-19 16:13:35 -08004317 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004318 Vector<ComposerState> state;
4319 Vector<DisplayState> displays;
4320 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004321 d.what = DisplayState::eDisplayProjectionChanged |
4322 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004323 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004324 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004325 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004326 d.frame.makeInvalid();
4327 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004328 d.width = 0;
4329 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004330 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004331 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004332
Dominik Laskowskie9774092018-12-11 10:04:24 -08004333 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004334
Dominik Laskowski83b88212018-12-11 13:34:06 -08004335 const nsecs_t vsyncPeriod = getVsyncPeriod();
4336 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004337
Brian Andersond0010582017-03-07 13:20:31 -08004338 // Use phase of 0 since phase is not known.
4339 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004340 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004341 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004342}
4343
4344void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004345 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004346 postMessageAsync(
4347 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004348}
4349
Dominik Laskowskie9774092018-12-11 10:04:24 -08004350void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004351 if (display->isVirtual()) {
4352 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004353 return;
4354 }
4355
Dominik Laskowski075d3172018-05-24 15:50:06 -07004356 const auto displayId = display->getId();
4357 LOG_ALWAYS_FATAL_IF(!displayId);
4358
Dominik Laskowski34157762018-10-31 13:07:19 -07004359 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004360
4361 int currentMode = display->getPowerMode();
4362 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004363 return;
4364 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004365
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004366 display->setPowerMode(mode);
4367
Lloyd Pique4dccc412018-01-22 17:21:36 -08004368 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004369 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004370 }
4371
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004372 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004373 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004374 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004375 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004376 if (mUseScheduler) {
4377 mScheduler->onScreenAcquired(mAppConnectionHandle);
4378 } else {
4379 mEventThread->onScreenAcquired();
4380 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004381 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004382 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004383
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004384 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004385 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004386 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004387
4388 struct sched_param param = {0};
4389 param.sched_priority = 1;
4390 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4391 ALOGW("Couldn't set SCHED_FIFO on display on");
4392 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004393 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004394 // Turn off the display
4395 struct sched_param param = {0};
4396 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4397 ALOGW("Couldn't set SCHED_OTHER on display off");
4398 }
4399
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004400 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004401 if (mUseScheduler) {
4402 mScheduler->disableHardwareVsync(true);
4403 } else {
4404 disableHardwareVsync(true); // also cancels any in-progress resync
4405 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004406 if (mUseScheduler) {
4407 mScheduler->onScreenReleased(mAppConnectionHandle);
4408 } else {
4409 mEventThread->onScreenReleased();
4410 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004411 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004412
Dominik Laskowski075d3172018-05-24 15:50:06 -07004413 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004414 mVisibleRegionsDirty = true;
4415 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004416 } else if (mode == HWC_POWER_MODE_DOZE ||
4417 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004418 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004419 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004420 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004421 if (mUseScheduler) {
4422 mScheduler->onScreenAcquired(mAppConnectionHandle);
4423 } else {
4424 mEventThread->onScreenAcquired();
4425 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004426 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004427 }
4428 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4429 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004430 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004431 if (mUseScheduler) {
4432 mScheduler->disableHardwareVsync(true);
4433 } else {
4434 disableHardwareVsync(true); // also cancels any in-progress resync
4435 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004436 if (mUseScheduler) {
4437 mScheduler->onScreenReleased(mAppConnectionHandle);
4438 } else {
4439 mEventThread->onScreenReleased();
4440 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004441 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004442 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004443 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004444 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004445 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004446 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004447
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004448 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004449 mTimeStats->setPowerMode(mode);
Ana Krulec4593b692019-01-11 22:07:25 -08004450 if (mUseScheduler && mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004451 // Update refresh rate stats.
4452 mRefreshRateStats->setPowerMode(mode);
4453 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004454 }
4455
Dominik Laskowski34157762018-10-31 13:07:19 -07004456 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004457}
4458
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004459void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004460 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004461 const auto display = getDisplayDevice(displayToken);
4462 if (!display) {
4463 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4464 displayToken.get());
4465 } else if (display->isVirtual()) {
4466 ALOGW("Attempt to set power mode %d for virtual display", mode);
4467 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004468 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004469 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004470 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004471}
4472
4473// ---------------------------------------------------------------------------
4474
Dominik Laskowskic2867142019-01-21 11:33:38 -08004475status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4476 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004477 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004478
Mathias Agopianbd115332013-04-18 16:41:04 -07004479 IPCThreadState* ipc = IPCThreadState::self();
4480 const int pid = ipc->getCallingPid();
4481 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004482
Mathias Agopianbd115332013-04-18 16:41:04 -07004483 if ((uid != AID_SHELL) &&
4484 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004485 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4486 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004487 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004488 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004489 // (this would indicate SF is stuck, but we want to be able to
4490 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004491 status_t err = mStateLock.timedLock(s2ns(1));
4492 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004493 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004494 StringAppendF(&result,
4495 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4496 "(no locks held)\n",
4497 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004498 }
4499
Dominik Laskowskic2867142019-01-21 11:33:38 -08004500 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004501
Dominik Laskowskic2867142019-01-21 11:33:38 -08004502 static const std::unordered_map<std::string, Dumper> dumpers = {
4503 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4504 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4505 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
4506 {"--dispsync"s, dumper([this](std::string& s) { mPrimaryDispSync->dump(s); })},
4507 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4508 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
4509 {"--frame-composition"s, dumper(&SurfaceFlinger::dumpFrameCompositionInfo)},
4510 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4511 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4512 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4513 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4514 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4515 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004516 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004517 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4518 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004519
Dominik Laskowskic2867142019-01-21 11:33:38 -08004520 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004521
Dominik Laskowskic2867142019-01-21 11:33:38 -08004522 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4523 (it->second)(args, asProto, result);
4524 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004525 if (asProto) {
4526 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4527 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4528 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004529 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004530 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004531 }
4532
Mathias Agopian9795c422009-08-26 16:36:26 -07004533 if (locked) {
4534 mStateLock.unlock();
4535 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004536 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004537 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004538 return NO_ERROR;
4539}
4540
Dominik Laskowskic2867142019-01-21 11:33:38 -08004541void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004542 mCurrentState.traverseInZOrder(
4543 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004544}
4545
Dominik Laskowskic2867142019-01-21 11:33:38 -08004546void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004547 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004548
Dominik Laskowskic2867142019-01-21 11:33:38 -08004549 if (args.size() > 1) {
4550 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004551 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004552 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004553 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004554 }
Robert Carr2047fae2016-11-28 14:09:09 -08004555 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004556 } else {
4557 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004558 }
4559}
4560
Dominik Laskowskic2867142019-01-21 11:33:38 -08004561void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004562 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004563 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004564 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004565 }
Robert Carr2047fae2016-11-28 14:09:09 -08004566 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004567
Svetoslavd85084b2014-03-20 10:28:31 -07004568 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004569}
4570
Dominik Laskowskic2867142019-01-21 11:33:38 -08004571void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4572 mTimeStats->parseArgs(asProto, args, result);
4573}
4574
Jamie Gennis6547ff42013-07-16 20:12:42 -07004575// This should only be called from the main thread. Otherwise it would need
4576// the lock and should use mCurrentState rather than mDrawingState.
4577void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004578 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004579 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004580 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004581
4582 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4583}
4584
Yiwei Zhang5434a782018-12-05 18:06:32 -08004585void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004586 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004587
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004588 if (isLayerTripleBufferingDisabled())
4589 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004590
Yiwei Zhang5434a782018-12-05 18:06:32 -08004591 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4592 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4593 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4594 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4595 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4596 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004597 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004598}
4599
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004600void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004601 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004602 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004603 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004604 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004605
4606 StringAppendF(&result, "Scheduler: %s\n\n", mUseScheduler ? "enabled" : "disabled");
4607
4608 if (mUseScheduler) {
4609 mScheduler->dump(mAppConnectionHandle, result);
4610 } else {
4611 mEventThread->dump(result);
4612 }
4613}
4614
Yiwei Zhang5434a782018-12-05 18:06:32 -08004615void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4616 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004617 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4618 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004619 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004620 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004621 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004622 }
David Sodman4a36e932017-11-07 14:29:47 -08004623 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004624 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004625 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004626 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4627 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004628}
4629
Dan Stozae77c7662016-05-13 11:37:28 -07004630void SurfaceFlinger::recordBufferingStats(const char* layerName,
4631 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004632 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4633 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004634 for (const auto& segment : history) {
4635 if (!segment.usedThirdBuffer) {
4636 stats.twoBufferTime += segment.totalTime;
4637 }
4638 if (segment.occupancyAverage < 1.0f) {
4639 stats.doubleBufferedTime += segment.totalTime;
4640 } else if (segment.occupancyAverage < 2.0f) {
4641 stats.tripleBufferedTime += segment.totalTime;
4642 }
4643 ++stats.numSegments;
4644 stats.totalTime += segment.totalTime;
4645 }
4646}
4647
Yiwei Zhang5434a782018-12-05 18:06:32 -08004648void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4649 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004650
4651 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4652 const size_t count = currentLayers.size();
4653 for (size_t i=0 ; i<count ; i++) {
4654 currentLayers[i]->dumpFrameEvents(result);
4655 }
4656}
4657
Yiwei Zhang5434a782018-12-05 18:06:32 -08004658void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004659 result.append("Buffering stats:\n");
4660 result.append(" [Layer name] <Active time> <Two buffer> "
4661 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004662 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004663 typedef std::tuple<std::string, float, float, float> BufferTuple;
4664 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004665 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004666 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004667 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004668 if (stats.numSegments == 0) {
4669 continue;
4670 }
4671 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4672 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4673 stats.totalTime;
4674 float doubleBufferRatio = static_cast<float>(
4675 stats.doubleBufferedTime) / stats.totalTime;
4676 float tripleBufferRatio = static_cast<float>(
4677 stats.tripleBufferedTime) / stats.totalTime;
4678 sorted.insert({activeTime, {name, twoBufferRatio,
4679 doubleBufferRatio, tripleBufferRatio}});
4680 }
4681 for (const auto& sortedPair : sorted) {
4682 float activeTime = sortedPair.first;
4683 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004684 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4685 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004686 }
4687 result.append("\n");
4688}
4689
Yiwei Zhang5434a782018-12-05 18:06:32 -08004690void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004691 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004692 const auto displayId = display->getId();
4693 if (!displayId) {
4694 continue;
4695 }
4696 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004697 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004698 continue;
4699 }
4700
Yiwei Zhang5434a782018-12-05 18:06:32 -08004701 StringAppendF(&result,
4702 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4703 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004704 uint8_t port;
4705 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004706 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004707 result.append("no identification data\n");
4708 continue;
4709 }
4710
4711 if (!isEdid(data)) {
4712 result.append("unknown identification data: ");
4713 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004714 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004715 }
4716 result.append("\n");
4717 continue;
4718 }
4719
4720 const auto edid = parseEdid(data);
4721 if (!edid) {
4722 result.append("invalid EDID: ");
4723 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004724 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004725 }
4726 result.append("\n");
4727 continue;
4728 }
4729
Yiwei Zhang5434a782018-12-05 18:06:32 -08004730 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004731 result.append(edid->displayName.data(), edid->displayName.length());
4732 result.append("\"\n");
4733 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004734}
4735
Yiwei Zhang5434a782018-12-05 18:06:32 -08004736void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4737 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4738 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4739 StringAppendF(&result, "DisplayColorSetting: %s\n",
4740 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004741
4742 // TODO: print out if wide-color mode is active or not
4743
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004744 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004745 const auto displayId = display->getId();
4746 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004747 continue;
4748 }
4749
Yiwei Zhang5434a782018-12-05 18:06:32 -08004750 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004751 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004752 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004753 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004754 }
4755
Lloyd Pique32cbe282018-10-19 13:09:22 -07004756 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004757 StringAppendF(&result, " Current color mode: %s (%d)\n",
4758 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004759 }
4760 result.append("\n");
4761}
4762
Yiwei Zhang5434a782018-12-05 18:06:32 -08004763void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004764 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004765 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4766 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004767 continue;
4768 }
4769
Dominik Laskowski05275f12018-11-01 15:03:24 -07004770 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004771 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4772 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004773 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004774 compositionInfo.dump(result, nullptr);
4775 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004776 }
4777 }
David Sodman7e4ae112018-02-09 15:02:28 -08004778}
4779
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004780LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004781 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004782 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4783 const State& state = useDrawing ? mDrawingState : mCurrentState;
4784 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004785 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004786 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004787 });
4788
4789 return layersProto;
4790}
4791
Lloyd Pique32cbe282018-10-19 13:09:22 -07004792LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004793 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004794
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004795 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004796 resolution->set_w(displayDevice.getWidth());
4797 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004798
Lloyd Pique32cbe282018-10-19 13:09:22 -07004799 auto display = displayDevice.getCompositionDisplay();
4800 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004801
Lloyd Pique32cbe282018-10-19 13:09:22 -07004802 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4803 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4804 layersProto.set_global_transform(displayState.orientation);
4805
4806 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004807 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004808 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004809 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004810 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004811 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004812 }
4813 });
4814
4815 return layersProto;
4816}
4817
Dominik Laskowskic2867142019-01-21 11:33:38 -08004818void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4819 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004820 Colorizer colorizer(colorize);
4821
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004822 // figure out if we're stuck somewhere
4823 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004824 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004825 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4826
4827 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004828 * Dump library configuration.
4829 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004830
4831 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004832 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004833 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004834 appendSfConfigString(result);
4835 appendUiConfigString(result);
4836 appendGuiConfigString(result);
4837 result.append("\n");
4838
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004839 result.append("\nDisplay identification data:\n");
4840 dumpDisplayIdentificationData(result);
4841
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004842 result.append("\nWide-Color information:\n");
4843 dumpWideColorInfo(result);
4844
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004845 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004846 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004847 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004848 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004849 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004850
Andy McFadden41d67d72014-04-25 16:58:34 -07004851 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004852 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004853 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004854 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004855 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004856
Dan Stozab90cf072015-03-05 11:05:59 -08004857 dumpStaticScreenStats(result);
4858 result.append("\n");
4859
Yiwei Zhang5434a782018-12-05 18:06:32 -08004860 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004861
Dan Stozae77c7662016-05-13 11:37:28 -07004862 dumpBufferingStats(result);
4863
Andy McFadden4803b742012-09-24 19:07:20 -07004864 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004865 * Dump the visible layer list
4866 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004867 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004868 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4869 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4870 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004871 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004872
Chia-I Wu2f884132018-09-13 15:17:58 -07004873 {
4874 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4875 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004876 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004877 result.append("\n");
4878 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004879
David Sodman7e4ae112018-02-09 15:02:28 -08004880 result.append("\nFrame-Composition information:\n");
4881 dumpFrameCompositionInfo(result);
4882 result.append("\n");
4883
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004884 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004885 * Dump Display state
4886 */
4887
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004888 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004889 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004890 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004891 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004892 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004893 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004894 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004895
4896 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004897 * Dump SurfaceFlinger global state
4898 */
4899
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004900 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004901 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004902 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004903
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004904 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004905
Dominik Laskowski075d3172018-05-24 15:50:06 -07004906 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004907 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4908 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004909 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4910 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004911 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004912 StringAppendF(&result,
4913 " transaction-flags : %08x\n"
4914 " gpu_to_cpu_unsupported : %d\n",
4915 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004916
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004917 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004918 displayId && getHwComposer().isConnected(*displayId)) {
4919 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004920 StringAppendF(&result,
4921 " refresh-rate : %f fps\n"
4922 " x-dpi : %f\n"
4923 " y-dpi : %f\n",
4924 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4925 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004926 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004927
Yiwei Zhang5434a782018-12-05 18:06:32 -08004928 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004929
Dan Stozae22aec72016-08-01 13:20:59 -07004930 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004931 * Tracing state
4932 */
4933 mTracing.dump(result);
4934 result.append("\n");
4935
4936 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004937 * HWC layer minidump
4938 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004939 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004940 const auto displayId = display->getId();
4941 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004942 continue;
4943 }
4944
Yiwei Zhang5434a782018-12-05 18:06:32 -08004945 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004946 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004947 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004948 result.append("\n");
4949 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004950
4951 /*
4952 * Dump HWComposer state
4953 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004954 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004955 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004956 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004957 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004958 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004959 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004960
4961 /*
4962 * Dump gralloc state
4963 */
4964 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4965 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004966
4967 /*
4968 * Dump VrFlinger state if in use.
4969 */
4970 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4971 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004972 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004973 result.append("\n");
4974 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004975
4976 /**
4977 * Scheduler dump state.
4978 */
4979 if (mUseScheduler) {
4980 result.append("\nScheduler state:\n");
4981 result.append(mScheduler->doDump() + "\n");
4982 result.append(mRefreshRateStats->doDump() + "\n");
4983 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004984}
4985
Dominik Laskowski075d3172018-05-24 15:50:06 -07004986const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004987 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004988 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004989 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004990 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004991 }
4992 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004993
Dominik Laskowski34157762018-10-31 13:07:19 -07004994 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004995 static const Vector<sp<Layer>> empty;
4996 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004997}
4998
Chia-I Wu28f320b2018-05-03 11:02:56 -07004999void SurfaceFlinger::updateColorMatrixLocked() {
5000 mat4 colorMatrix;
5001 if (mGlobalSaturationFactor != 1.0f) {
5002 // Rec.709 luma coefficients
5003 float3 luminance{0.213f, 0.715f, 0.072f};
5004 luminance *= 1.0f - mGlobalSaturationFactor;
5005 mat4 saturationMatrix = mat4(
5006 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
5007 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
5008 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
5009 vec4{0.0f, 0.0f, 0.0f, 1.0f}
5010 );
5011 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
5012 } else {
5013 colorMatrix = mClientColorMatrix * mDaltonizer();
5014 }
5015
5016 if (mCurrentState.colorMatrix != colorMatrix) {
5017 mCurrentState.colorMatrix = colorMatrix;
5018 mCurrentState.colorMatrixChanged = true;
5019 setTransactionFlags(eTransactionNeeded);
5020 }
5021}
5022
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005023status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005024#pragma clang diagnostic push
5025#pragma clang diagnostic error "-Wswitch-enum"
5026 switch (static_cast<ISurfaceComposerTag>(code)) {
5027 // These methods should at minimum make sure that the client requested
5028 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005029 case BOOT_FINISHED:
5030 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005031 case CREATE_DISPLAY:
5032 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005033 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005034 case GET_ACTIVE_COLOR_MODE:
5035 case GET_ANIMATION_FRAME_STATS:
5036 case GET_HDR_CAPABILITIES:
5037 case SET_ACTIVE_CONFIG:
5038 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005039 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005040 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005041 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005042 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
5043 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005044 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5045 IPCThreadState* ipc = IPCThreadState::self();
5046 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5047 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005048 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005049 }
Robert Carr1db73f62016-12-21 12:58:51 -08005050 return OK;
5051 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005052 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005053 IPCThreadState* ipc = IPCThreadState::self();
5054 const int pid = ipc->getCallingPid();
5055 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005056 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5057 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005058 return PERMISSION_DENIED;
5059 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005060 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005061 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005062 // Used by apps to hook Choreographer to SurfaceFlinger.
5063 case CREATE_DISPLAY_EVENT_CONNECTION:
5064 // The following calls are currently used by clients that do not
5065 // request necessary permissions. However, they do not expose any secret
5066 // information, so it is OK to pass them.
5067 case AUTHENTICATE_SURFACE:
5068 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005069 case GET_PHYSICAL_DISPLAY_IDS:
5070 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005071 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005072 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005073 case GET_DISPLAY_CONFIGS:
5074 case GET_DISPLAY_STATS:
5075 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5076 // Calling setTransactionState is safe, because you need to have been
5077 // granted a reference to Client* and Handle* to do anything with it.
5078 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005079 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005080 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005081 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005082 case GET_PROTECTED_CONTENT_SUPPORT:
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08005083 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005084 return OK;
5085 }
5086 case CAPTURE_LAYERS:
5087 case CAPTURE_SCREEN: {
5088 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005089 IPCThreadState* ipc = IPCThreadState::self();
5090 const int pid = ipc->getCallingPid();
5091 const int uid = ipc->getCallingUid();
5092 if ((uid != AID_GRAPHICS) &&
5093 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5094 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5095 return PERMISSION_DENIED;
5096 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005097 return OK;
5098 }
5099 // The following codes are deprecated and should never be allowed to access SF.
5100 case CONNECT_DISPLAY_UNUSED:
5101 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5102 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5103 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005104 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005105 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005106
5107 // These codes are used for the IBinder protocol to either interrogate the recipient
5108 // side of the transaction for its canonical interface descriptor or to dump its state.
5109 // We let them pass by default.
5110 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5111 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5112 code == IBinder::SYSPROPS_TRANSACTION) {
5113 return OK;
5114 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005115 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005116 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005117 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005118 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5119 return OK;
5120 }
5121 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5122 return PERMISSION_DENIED;
5123#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005124}
5125
Ana Krulec13be8ad2018-08-21 02:43:56 +00005126status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5127 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005128 status_t credentialCheck = CheckTransactCodeCredentials(code);
5129 if (credentialCheck != OK) {
5130 return credentialCheck;
5131 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005132
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005133 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5134 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005135 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005136 IPCThreadState* ipc = IPCThreadState::self();
5137 const int uid = ipc->getCallingUid();
5138 if (CC_UNLIKELY(uid != AID_SYSTEM
5139 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005140 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005141 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005142 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005143 return PERMISSION_DENIED;
5144 }
5145 int n;
5146 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005147 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005148 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005149 return NO_ERROR;
5150 case 1002: // SHOW_UPDATES
5151 n = data.readInt32();
5152 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005153 invalidateHwcGeometry();
5154 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005155 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005156 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005157 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005158 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005159 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005160 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005161 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005162 setTransactionFlags(
5163 eTransactionNeeded|
5164 eDisplayTransactionNeeded|
5165 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005166 return NO_ERROR;
5167 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005168 case 1006:{ // send empty update
5169 signalRefresh();
5170 return NO_ERROR;
5171 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005172 case 1008: // toggle use of hw composer
5173 n = data.readInt32();
5174 mDebugDisableHWC = n ? 1 : 0;
5175 invalidateHwcGeometry();
5176 repaintEverything();
5177 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005178 case 1009: // toggle use of transform hint
5179 n = data.readInt32();
5180 mDebugDisableTransformHint = n ? 1 : 0;
5181 invalidateHwcGeometry();
5182 repaintEverything();
5183 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005184 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005185 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005186 reply->writeInt32(0);
5187 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005188 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005189 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005190 return NO_ERROR;
5191 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005192 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005193 if (!display) {
5194 return NAME_NOT_FOUND;
5195 }
5196
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005197 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005198 return NO_ERROR;
5199 }
5200 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005201 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005202 // daltonize
5203 n = data.readInt32();
5204 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005205 case 1:
5206 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5207 break;
5208 case 2:
5209 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5210 break;
5211 case 3:
5212 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5213 break;
5214 default:
5215 mDaltonizer.setType(ColorBlindnessType::None);
5216 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005217 }
5218 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005219 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005220 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005221 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005222 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005223
5224 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005225 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005226 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005227 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005228 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005229 // apply a color matrix
5230 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005231 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005232 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005233 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005234 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005235 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005236 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005237 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005238 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005239 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005240 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005241
5242 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5243 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005244 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005245 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5246 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5247 }
5248
Chia-I Wu28f320b2018-05-03 11:02:56 -07005249 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005250 return NO_ERROR;
5251 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005252 // This is an experimental interface
5253 // Needs to be shifted to proper binder interface when we productize
5254 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005255 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005256 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005257 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005258 return NO_ERROR;
5259 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005260 case 1017: {
5261 n = data.readInt32();
5262 mForceFullDamage = static_cast<bool>(n);
5263 return NO_ERROR;
5264 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005265 case 1018: { // Modify Choreographer's phase offset
5266 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005267 if (mUseScheduler) {
5268 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5269 } else {
5270 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5271 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005272 return NO_ERROR;
5273 }
5274 case 1019: { // Modify SurfaceFlinger's phase offset
5275 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005276 if (mUseScheduler) {
5277 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5278 } else {
5279 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5280 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005281 return NO_ERROR;
5282 }
Irvel468051e2016-06-13 16:44:44 -07005283 case 1020: { // Layer updates interceptor
5284 n = data.readInt32();
5285 if (n) {
5286 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005287 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005288 }
5289 else{
5290 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005291 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005292 }
5293 return NO_ERROR;
5294 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005295 case 1021: { // Disable HWC virtual displays
5296 n = data.readInt32();
5297 mUseHwcVirtualDisplays = !n;
5298 return NO_ERROR;
5299 }
Romain Guy0147a172017-06-01 13:53:56 -07005300 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005301 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005302 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005303
Chia-I Wu28f320b2018-05-03 11:02:56 -07005304 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005305 return NO_ERROR;
5306 }
Romain Guy54f154a2017-10-24 21:40:32 +01005307 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005308 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005309 invalidateHwcGeometry();
5310 repaintEverything();
5311 return NO_ERROR;
5312 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005313 // Deprecate, use 1030 to check whether the device is color managed.
5314 case 1024: {
5315 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005316 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005317 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005318 n = data.readInt32();
5319 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005320 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005321 mTracing.enable();
5322 doTracing("tracing.enable");
5323 reply->writeInt32(NO_ERROR);
5324 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005325 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005326 status_t err = mTracing.disable();
5327 reply->writeInt32(err);
5328 }
5329 return NO_ERROR;
5330 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005331 case 1026: { // Get layer tracing status
5332 reply->writeBool(mTracing.isEnabled());
5333 return NO_ERROR;
5334 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005335 // Is a DisplayColorSetting supported?
5336 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005337 const auto display = getDefaultDisplayDevice();
5338 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005339 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005340 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005341
5342 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5343 switch (setting) {
5344 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005345 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005346 break;
5347 case DisplayColorSetting::UNMANAGED:
5348 reply->writeBool(true);
5349 break;
5350 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005351 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005352 break;
5353 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005354 reply->writeBool(
5355 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005356 break;
5357 }
5358 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005359 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005360 // Is VrFlinger active?
5361 case 1028: {
5362 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005363 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005364 return NO_ERROR;
5365 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005366 // Is device color managed?
5367 case 1030: {
5368 reply->writeBool(useColorManagement);
5369 return NO_ERROR;
5370 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005371 // Override default composition data space
5372 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5373 // && adb shell stop zygote && adb shell start zygote
5374 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5375 // adb shell stop zygote && adb shell start zygote
5376 case 1031: {
5377 Mutex::Autolock _l(mStateLock);
5378 n = data.readInt32();
5379 if (n) {
5380 n = data.readInt32();
5381 if (n) {
5382 Dataspace dataspace = static_cast<Dataspace>(n);
5383 if (!validateCompositionDataspace(dataspace)) {
5384 return BAD_VALUE;
5385 }
5386 mDefaultCompositionDataspace = dataspace;
5387 }
5388 n = data.readInt32();
5389 if (n) {
5390 Dataspace dataspace = static_cast<Dataspace>(n);
5391 if (!validateCompositionDataspace(dataspace)) {
5392 return BAD_VALUE;
5393 }
5394 mWideColorGamutCompositionDataspace = dataspace;
5395 }
5396 } else {
5397 // restore composition data space.
5398 mDefaultCompositionDataspace = defaultCompositionDataspace;
5399 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5400 }
5401 return NO_ERROR;
5402 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005403 }
5404 }
5405 return err;
5406}
5407
Steven Thomas6d8110b2017-08-31 18:24:21 -07005408void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005409 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005410 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005411}
5412
Ana Krulec7d1d6832018-12-27 11:10:09 -08005413void SurfaceFlinger::repaintEverythingForHWC() {
5414 mRepaintEverything = true;
5415 mEventQueue->invalidateForHWC();
5416}
5417
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005418// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5419class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005420public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005421 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5422 ~WindowDisconnector() {
5423 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005424 }
5425
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005426private:
5427 ANativeWindow* mWindow;
5428 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005429};
5430
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005431status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005432 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5433 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005434 uint32_t reqWidth, uint32_t reqHeight,
5435 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005436 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005437 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005438
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005439 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005440
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005441 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5442
Chia-I Wu20261cb2018-08-23 12:55:44 -07005443 sp<DisplayDevice> display;
5444 {
5445 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005446
Chia-I Wu20261cb2018-08-23 12:55:44 -07005447 display = getDisplayDeviceLocked(displayToken);
5448 if (!display) return BAD_VALUE;
5449
Chia-I Wucb023152018-08-28 12:57:23 -07005450 // set the requested width/height to the logical display viewport size
5451 // by default
5452 if (reqWidth == 0 || reqHeight == 0) {
5453 reqWidth = uint32_t(display->getViewport().width());
5454 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005455 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005456 }
5457
Peiyong Lin0e003c92018-09-17 11:09:51 -07005458 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5459 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005460
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005461 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5462 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005463 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5464 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005465}
5466
5467status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005468 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5469 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005470 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005471 ATRACE_CALL();
5472
5473 class LayerRenderArea : public RenderArea {
5474 public:
Robert Carr578038f2018-03-09 12:25:24 -08005475 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005476 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5477 bool childrenOnly)
5478 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005479 mLayer(layer),
5480 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005481 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005482 mFlinger(flinger),
5483 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005484 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005485 Rect getBounds() const override {
5486 const Layer::State& layerState(mLayer->getDrawingState());
5487 return mLayer->getBufferSize(layerState);
5488 }
Marissa Wall61c58622018-07-18 10:12:20 -07005489 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005490 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005491 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005492 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005493 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005494 }
chaviwa76b2712017-09-20 12:02:26 -07005495 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005496 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005497 Rect getSourceCrop() const override {
5498 if (mCrop.isEmpty()) {
5499 return getBounds();
5500 } else {
5501 return mCrop;
5502 }
5503 }
Robert Carr578038f2018-03-09 12:25:24 -08005504 class ReparentForDrawing {
5505 public:
5506 const sp<Layer>& oldParent;
5507 const sp<Layer>& newParent;
5508
5509 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5510 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005511 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005512 }
Robert Carr15eae092018-03-23 13:43:53 -07005513 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005514 };
5515
5516 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005517 const Rect sourceCrop = getSourceCrop();
5518 // no need to check rotation because there is none
5519 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5520 sourceCrop.height() != getReqHeight();
5521
Robert Carr578038f2018-03-09 12:25:24 -08005522 if (!mChildrenOnly) {
5523 mTransform = mLayer->getTransform().inverse();
5524 drawLayers();
5525 } else {
5526 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005527 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005528 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5529 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005530
5531 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5532 drawLayers();
5533 }
5534 }
chaviwa76b2712017-09-20 12:02:26 -07005535
chaviwa76b2712017-09-20 12:02:26 -07005536 private:
chaviw7206d492017-11-10 16:16:12 -08005537 const sp<Layer> mLayer;
5538 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005539
5540 // In the "childrenOnly" case we reparent the children to a screenshot
5541 // layer which has no properties set and which does not draw.
5542 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005543 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005544 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005545
5546 SurfaceFlinger* mFlinger;
5547 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005548 };
5549
5550 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5551 auto parent = layerHandle->owner.promote();
5552
Robert Carr2e102c92018-10-23 12:11:15 -07005553 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005554 ALOGE("captureLayers called with a removed parent");
5555 return NAME_NOT_FOUND;
5556 }
5557
Robert Carr578038f2018-03-09 12:25:24 -08005558 const int uid = IPCThreadState::self()->getCallingUid();
5559 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005560 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005561 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5562 return PERMISSION_DENIED;
5563 }
5564
chaviw7206d492017-11-10 16:16:12 -08005565 Rect crop(sourceCrop);
5566 if (sourceCrop.width() <= 0) {
5567 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005568 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005569 }
5570
5571 if (sourceCrop.height() <= 0) {
5572 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005573 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005574 }
5575
5576 int32_t reqWidth = crop.width() * frameScale;
5577 int32_t reqHeight = crop.height() * frameScale;
5578
Chia-I Wu20261cb2018-08-23 12:55:44 -07005579 // really small crop or frameScale
5580 if (reqWidth <= 0) {
5581 reqWidth = 1;
5582 }
5583 if (reqHeight <= 0) {
5584 reqHeight = 1;
5585 }
5586
Peiyong Lin0e003c92018-09-17 11:09:51 -07005587 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005588
Robert Carr578038f2018-03-09 12:25:24 -08005589 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005590 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5591 if (!layer->isVisible()) {
5592 return;
Robert Carr578038f2018-03-09 12:25:24 -08005593 } else if (childrenOnly && layer == parent.get()) {
5594 return;
chaviwa76b2712017-09-20 12:02:26 -07005595 }
5596 visitor(layer);
5597 });
5598 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005599 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005600}
5601
5602status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5603 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005604 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005605 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005606 bool useIdentityTransform) {
5607 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005608
Peiyong Lin0e003c92018-09-17 11:09:51 -07005609 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005610 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5611 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005612 *outBuffer =
5613 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5614 static_cast<android_pixel_format>(reqPixelFormat), 1,
5615 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005616
5617 // This mutex protects syncFd and captureResult for communication of the return values from the
5618 // main thread back to this Binder thread
5619 std::mutex captureMutex;
5620 std::condition_variable captureCondition;
5621 std::unique_lock<std::mutex> captureLock(captureMutex);
5622 int syncFd = -1;
5623 std::optional<status_t> captureResult;
5624
Robert Carr03480e22018-01-04 16:02:06 -08005625 const int uid = IPCThreadState::self()->getCallingUid();
5626 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5627
Dominik Laskowski8c001672018-05-30 16:52:06 -07005628 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005629 // If there is a refresh pending, bug out early and tell the binder thread to try again
5630 // after the refresh.
5631 if (mRefreshPending) {
5632 ATRACE_NAME("Skipping screenshot for now");
5633 std::unique_lock<std::mutex> captureLock(captureMutex);
5634 captureResult = std::make_optional<status_t>(EAGAIN);
5635 captureCondition.notify_one();
5636 return;
5637 }
5638
5639 status_t result = NO_ERROR;
5640 int fd = -1;
5641 {
5642 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005643 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005644 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5645 useIdentityTransform, forSystem, &fd);
5646 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005647 }
5648
5649 {
5650 std::unique_lock<std::mutex> captureLock(captureMutex);
5651 syncFd = fd;
5652 captureResult = std::make_optional<status_t>(result);
5653 captureCondition.notify_one();
5654 }
5655 });
5656
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005657 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005658 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005659 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005660 while (*captureResult == EAGAIN) {
5661 captureResult.reset();
5662 result = postMessageAsync(message);
5663 if (result != NO_ERROR) {
5664 return result;
5665 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005666 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005667 }
5668 result = *captureResult;
5669 }
5670
5671 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005672 sync_wait(syncFd, -1);
5673 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005674 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005675
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005676 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005677}
5678
chaviwa76b2712017-09-20 12:02:26 -07005679void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005680 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005681 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5682 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005683 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005684
chaviwa76b2712017-09-20 12:02:26 -07005685 const auto reqWidth = renderArea.getReqWidth();
5686 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005687 const auto sourceCrop = renderArea.getSourceCrop();
5688 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005689
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005690 renderengine::DisplaySettings clientCompositionDisplay;
5691 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005692
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005693 // assume that bounds are never offset, and that they are the same as the
5694 // buffer bounds.
5695 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5696 ui::Transform transform = renderArea.getTransform();
5697 mat4 m;
5698 m[0][0] = transform[0][0];
5699 m[0][1] = transform[0][1];
5700 m[0][3] = transform[0][2];
5701 m[1][0] = transform[1][0];
5702 m[1][1] = transform[1][1];
5703 m[1][3] = transform[1][2];
5704 m[3][0] = transform[2][0];
5705 m[3][1] = transform[2][1];
5706 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005707
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005708 clientCompositionDisplay.globalTransform = m;
5709 mat4 rotMatrix;
5710 // Displacement for repositioning the clipping rectangle after rotating it
5711 // with the rotation hint.
5712 int displacementX = 0;
5713 int displacementY = 0;
5714 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5715 switch (rotation) {
5716 case ui::Transform::ROT_90:
5717 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5718 displacementX = reqWidth;
5719 break;
5720 case ui::Transform::ROT_180:
5721 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5722 displacementX = reqWidth;
5723 displacementY = reqHeight;
5724 break;
5725 case ui::Transform::ROT_270:
5726 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5727 displacementY = reqHeight;
5728 break;
5729 default:
5730 break;
5731 }
5732 // We need to transform the clipping window into the right spot.
5733 // First, rotate the clipping rectangle by the rotation hint to get the
5734 // right orientation
5735 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5736 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5737 const vec4 rotClipTL = rotMatrix * clipTL;
5738 const vec4 rotClipBR = rotMatrix * clipBR;
5739 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5740 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5741 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5742 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5743
5744 // Now reposition the clipping rectangle with the displacement vector
5745 // computed above.
5746 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5747
5748 clientCompositionDisplay.clip =
5749 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5750 newClipRight + displacementX, newClipBottom + displacementY);
5751
5752 // We need to perform the same transformation in layer space, so propagate
5753 // it to the global transform.
5754 mat4 clipTransform = displacementMat * rotMatrix;
5755 clientCompositionDisplay.globalTransform *= clipTransform;
5756 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5757 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005758
chaviw50da5042018-04-09 13:49:37 -07005759 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005760
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005761 renderengine::LayerSettings fillLayer;
5762 fillLayer.source.buffer.buffer = nullptr;
5763 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5764 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5765 fillLayer.alpha = half(alpha);
5766 clientCompositionLayers.push_back(fillLayer);
5767
5768 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005769 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005770 renderengine::LayerSettings layerSettings;
5771 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5772 layerSettings);
5773 if (prepared) {
5774 clientCompositionLayers.push_back(layerSettings);
5775 }
chaviwa76b2712017-09-20 12:02:26 -07005776 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005777
5778 clientCompositionDisplay.clearRegion = clearRegion;
5779 base::unique_fd drawFence;
5780 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
5781 &drawFence);
5782
5783 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005784}
5785
chaviwa76b2712017-09-20 12:02:26 -07005786status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5787 TraverseLayersFunction traverseLayers,
5788 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005789 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005790 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005791 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005792 ATRACE_CALL();
5793
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005794 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005795
5796 traverseLayers([&](Layer* layer) {
5797 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5798 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005799
Robert Carr03480e22018-01-04 16:02:06 -08005800 // We allow the system server to take screenshots of secure layers for
5801 // use in situations like the Screen-rotation animation and place
5802 // the impetus on WindowManager to not persist them.
5803 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005804 ALOGW("FB is protected: PERMISSION_DENIED");
5805 return PERMISSION_DENIED;
5806 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005807 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005808 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005809}
5810
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005811// ---------------------------------------------------------------------------
5812
Dan Stoza412903f2017-04-27 13:42:17 -07005813void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5814 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005815}
5816
Dan Stoza412903f2017-04-27 13:42:17 -07005817void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5818 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005819}
5820
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005821void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005822 const LayerVector::Visitor& visitor) {
5823 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005824 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005825 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005826 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005827 continue;
5828 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005829 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005830 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005831 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005832 return;
5833 }
chaviwa76b2712017-09-20 12:02:26 -07005834 if (!layer->isVisible()) {
5835 return;
5836 }
5837 visitor(layer);
5838 });
5839 }
5840}
5841
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005842}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005843
Lloyd Pique074e8122018-07-26 12:57:23 -07005844
Mathias Agopian3f844832013-08-07 21:24:32 -07005845#if defined(__gl_h_)
5846#error "don't include gl/gl.h in this file"
5847#endif
5848
5849#if defined(__gl2_h_)
5850#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005851#endif