blob: cf2b80cf21082535ee31d88674570e348af85e1b [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 Mouri0f714832018-11-12 15:31:06 -080017//#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"
Mathias Agopian90ac7992012-02-25 18:48:35 -080081#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080082#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070084#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080085#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070086#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070087#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080088#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070089#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080090
Steven Thomasb02664d2017-07-26 18:48:28 -070091#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070092#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070093#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070094#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070095#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070096#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070097#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070098#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070099#include "Scheduler/EventControlThread.h"
100#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700101#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700102#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700103#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800104#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700105
Mathias Agopianff2ed702013-09-01 21:36:12 -0700106#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700107
David Sodman7e4ae112018-02-09 15:02:28 -0800108#include "android-base/stringprintf.h"
109
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900110#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800111#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700112#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800113#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900114#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900115
chaviw1d044282017-09-27 12:19:28 -0700116#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900117#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700118
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800119namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700120
Jaesoo Lee43518572017-01-23 19:03:16 +0900121using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900122using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900123using namespace android::sysprop;
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
Steven Thomasb02664d2017-07-26 18:48:28 -0700131namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700132
133#pragma clang diagnostic push
134#pragma clang diagnostic error "-Wswitch-enum"
135
136bool isWideColorMode(const ColorMode colorMode) {
137 switch (colorMode) {
138 case ColorMode::DISPLAY_P3:
139 case ColorMode::ADOBE_RGB:
140 case ColorMode::DCI_P3:
141 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700142 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700143 case ColorMode::BT2100_PQ:
144 case ColorMode::BT2100_HLG:
145 return true;
146 case ColorMode::NATIVE:
147 case ColorMode::STANDARD_BT601_625:
148 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
149 case ColorMode::STANDARD_BT601_525:
150 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
151 case ColorMode::STANDARD_BT709:
152 case ColorMode::SRGB:
153 return false;
154 }
155 return false;
156}
157
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700158ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
159 switch (rotation) {
160 case ISurfaceComposer::eRotateNone:
161 return ui::Transform::ROT_0;
162 case ISurfaceComposer::eRotate90:
163 return ui::Transform::ROT_90;
164 case ISurfaceComposer::eRotate180:
165 return ui::Transform::ROT_180;
166 case ISurfaceComposer::eRotate270:
167 return ui::Transform::ROT_270;
168 }
169 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
170 return ui::Transform::ROT_0;
171}
172
Peiyong Linfca547f2018-07-09 13:03:33 -0700173#pragma clang diagnostic pop
174
Steven Thomasb02664d2017-07-26 18:48:28 -0700175class ConditionalLock {
176public:
177 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
178 if (lock) {
179 mMutex.lock();
180 }
181 }
182 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
183private:
184 Mutex& mMutex;
185 bool mLocked;
186};
Peiyong Linfca547f2018-07-09 13:03:33 -0700187
Peiyong Lin9d846a52018-11-05 13:18:20 -0800188// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
189bool validateCompositionDataspace(Dataspace dataspace) {
190 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
191}
192
Steven Thomasb02664d2017-07-26 18:48:28 -0700193} // namespace anonymous
194
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800195// ---------------------------------------------------------------------------
196
Mathias Agopian99b49842011-06-27 16:05:52 -0700197const String16 sHardwareTest("android.permission.HARDWARE_TEST");
198const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
199const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
200const String16 sDump("android.permission.DUMP");
201
Daniel Solomon42d04562019-01-20 21:03:19 -0800202constexpr float kSrgbRedX = 0.4123f;
203constexpr float kSrgbRedY = 0.2126f;
204constexpr float kSrgbRedZ = 0.0193f;
205constexpr float kSrgbGreenX = 0.3576f;
206constexpr float kSrgbGreenY = 0.7152f;
207constexpr float kSrgbGreenZ = 0.1192f;
208constexpr float kSrgbBlueX = 0.1805f;
209constexpr float kSrgbBlueY = 0.0722f;
210constexpr float kSrgbBlueZ = 0.9506f;
211constexpr float kSrgbWhiteX = 0.9505f;
212constexpr float kSrgbWhiteY = 1.0000f;
213constexpr float kSrgbWhiteZ = 1.0891f;
214
Mathias Agopian99b49842011-06-27 16:05:52 -0700215// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700216int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700217bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800218uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800219bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800220bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800221int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600222bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700223int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700224bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700225bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700226Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
227ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
228Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
229ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700230
Kalle Raitaa099a242017-01-11 11:17:29 -0800231std::string getHwcServiceName() {
232 char value[PROPERTY_VALUE_MAX] = {};
233 property_get("debug.sf.hwc_service_name", value, "default");
234 ALOGI("Using HWComposer service: '%s'", value);
235 return std::string(value);
236}
237
238bool useTrebleTestingOverride() {
239 char value[PROPERTY_VALUE_MAX] = {};
240 property_get("debug.sf.treble_testing_override", value, "false");
241 ALOGI("Treble testing override: '%s'", value);
242 return std::string(value) == "true";
243}
244
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800245std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
246 switch(displayColorSetting) {
247 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700248 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800249 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700250 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800251 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700252 return std::string("Enhanced");
253 default:
254 return std::string("Unknown ") +
255 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800256 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800257}
258
David Sodmanbc815282017-11-05 18:57:52 -0800259SurfaceFlingerBE::SurfaceFlingerBE()
260 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800261 mFrameBuckets(),
262 mTotalTime(0),
263 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800264 mComposerSequenceId(0) {
265}
266
Lloyd Pique90c115d2018-09-18 21:39:42 -0700267SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
268 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800269 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700270 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700271 mTransactionPending(false),
272 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700273 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700274 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800275 mBootTime(systemTime()),
Ana Krulec757f63a2019-01-25 10:46:18 -0800276 mPhaseOffsets{getFactory().createPhaseOffsets()},
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800277 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800278 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800279 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800280 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800281 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700282 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700283 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700284 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700285 mDebugInTransaction(0),
286 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700287 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800288 mTimeStats(factory.createTimeStats()),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700289 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700290 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800291 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800292 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800293 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700294 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700295 mMainThreadId(std::this_thread::get_id()),
296 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800297
Lloyd Pique90c115d2018-09-18 21:39:42 -0700298SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
299 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800300 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800301
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900302 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800303
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900304 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700305
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900306 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700307
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800309
Steven Thomas050b2c82017-03-06 11:45:16 -0800310 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900311 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800312
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900313 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800314
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900315 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700316
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900317 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600318
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900319 mDefaultCompositionDataspace =
320 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
321 mWideColorGamutCompositionDataspace =
322 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
323 defaultCompositionDataspace = mDefaultCompositionDataspace;
324 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
325 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
326 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
327 wideColorGamutCompositionPixelFormat =
328 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700329
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900330 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800331
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900332 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
333 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
334 switch (tmpPrimaryDisplayOrientation) {
335 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700336 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800337 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900338 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700339 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800340 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900341 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700342 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800343 break;
344 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700345 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800346 break;
347 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700348 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800349
Lloyd Pique90c115d2018-09-18 21:39:42 -0700350 mPrimaryDispSync =
351 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
352 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700353
Daniel Solomon42d04562019-01-20 21:03:19 -0800354 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
355 if (surfaceFlingerConfigsServiceV1_2) {
356 surfaceFlingerConfigsServiceV1_2->getDisplayNativePrimaries(
357 [&](auto tmpPrimaries) {
358 memcpy(&mInternalDisplayPrimaries, &tmpPrimaries, sizeof(ui::DisplayPrimaries));
359 });
360 } else {
361 initDefaultDisplayNativePrimaries();
362 }
363
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800364 // debugging stuff...
365 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700366
Mathias Agopianb4b17302013-03-20 18:36:41 -0700367 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700368 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700369
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800370 property_get("debug.sf.showupdates", value, "0");
371 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700372
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700373 property_get("debug.sf.ddms", value, "0");
374 mDebugDDMS = atoi(value);
375 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700376 if (!startDdmConnection()) {
377 // start failed, and DDMS debugging not enabled
378 mDebugDDMS = 0;
379 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700380 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700381 ALOGI_IF(mDebugRegion, "showupdates enabled");
382 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
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
Mathias Agopiane57f2922012-08-09 16:29:12 -0700501sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700502 std::optional<DisplayId> displayId;
503
504 if (id == HWC_DISPLAY_PRIMARY) {
505 displayId = getInternalDisplayId();
506 } else if (id == HWC_DISPLAY_EXTERNAL) {
507 displayId = getExternalDisplayId();
508 }
509
510 if (!displayId) {
511 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800512 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700513 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700514
515 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700516}
517
Ady Abraham37965d42018-11-01 13:43:32 -0700518status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
519 if (!outGetColorManagement) {
520 return BAD_VALUE;
521 }
522 *outGetColorManagement = useColorManagement;
523 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700524}
525
Lloyd Pique441d5042018-10-18 16:49:51 -0700526HWComposer& SurfaceFlinger::getHwComposer() const {
527 return mCompositionEngine->getHwComposer();
528}
529
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700530renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
531 return mCompositionEngine->getRenderEngine();
532}
533
Lloyd Pique70d91362018-10-18 16:02:55 -0700534compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
535 return *mCompositionEngine.get();
536}
537
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800538void SurfaceFlinger::bootFinished()
539{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700540 if (mStartPropertySetThread->join() != NO_ERROR) {
541 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800542 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800543 const nsecs_t now = systemTime();
544 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000545 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700546
547 // wait patiently for the window manager death
548 const String16 name("window");
549 sp<IBinder> window(defaultServiceManager()->getService(name));
550 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700551 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700552 }
Robert Carr720e5062018-07-30 17:45:14 -0700553 sp<IBinder> input(defaultServiceManager()->getService(
554 String16("inputflinger")));
555 if (input == nullptr) {
556 ALOGE("Failed to link to input service");
557 } else {
558 mInputFlinger = interface_cast<IInputFlinger>(input);
559 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700560
Steven Thomas050b2c82017-03-06 11:45:16 -0800561 if (mVrFlinger) {
562 mVrFlinger->OnBootFinished();
563 }
564
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700565 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700566 // formerly we would just kill the process, but we now ask it to exit so it
567 // can choose where to stop the animation.
568 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700569
570 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
571 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
572 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700573
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800574 postMessageAsync(new LambdaMessage([this] {
575 readPersistentProperties();
576 mBootStage = BootStage::FINISHED;
577 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800578}
579
Dan Stoza436ccf32018-06-21 12:10:12 -0700580uint32_t SurfaceFlinger::getNewTexture() {
581 {
582 std::lock_guard lock(mTexturePoolMutex);
583 if (!mTexturePool.empty()) {
584 uint32_t name = mTexturePool.back();
585 mTexturePool.pop_back();
586 ATRACE_INT("TexturePoolSize", mTexturePool.size());
587 return name;
588 }
589
590 // The pool was too small, so increase it for the future
591 ++mTexturePoolSize;
592 }
593
594 // The pool was empty, so we need to get a new texture name directly using a
595 // blocking call to the main thread
596 uint32_t name = 0;
597 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
598 return name;
599}
600
Mathias Agopian3f844832013-08-07 21:24:32 -0700601void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700602 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700603}
604
Wei Wangf9b05ee2017-07-19 20:59:39 -0700605// Do not call property_set on main thread which will be blocked by init
606// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700607void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700608 ALOGI( "SurfaceFlinger's main thread ready to run. "
609 "Initializing graphics H/W...");
610
Ana Krulec757f63a2019-01-25 10:46:18 -0800611 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900612
Steven Thomasb02664d2017-07-26 18:48:28 -0700613 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800614
Dominik Laskowski83b88212018-12-11 13:34:06 -0800615 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -0800616
Steven Thomasb02664d2017-07-26 18:48:28 -0700617 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700618 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700619 mScheduler = getFactory().createScheduler([this](bool enabled) {
620 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
621 });
Ana Krulec757f63a2019-01-25 10:46:18 -0800622 // TODO(b/113612090): Currently we assume that if scheduler is turned on, then the refresh
623 // rate is 90. Once b/122905403 is completed, this should be updated accordingly.
624 mPhaseOffsets->setRefreshRateType(
625 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700626
Ana Krulec98b5b242018-08-10 15:03:23 -0700627 mAppConnectionHandle =
Ana Krulec757f63a2019-01-25 10:46:18 -0800628 mScheduler->createConnection("appConnection", mPhaseOffsets->getCurrentAppOffset(),
Dominik Laskowskif654d572018-12-20 11:03:06 -0800629 resyncCallback,
Ana Krulec98b5b242018-08-10 15:03:23 -0700630 impl::EventThread::InterceptVSyncsCallback());
631 mSfConnectionHandle =
Ana Krulec757f63a2019-01-25 10:46:18 -0800632 mScheduler->createConnection("sfConnection", mPhaseOffsets->getCurrentSfOffset(),
Dominik Laskowskif654d572018-12-20 11:03:06 -0800633 resyncCallback, [this](nsecs_t timestamp) {
Ana Krulec98b5b242018-08-10 15:03:23 -0700634 mInterceptor->saveVSyncEvent(timestamp);
635 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800636
Ana Krulec98b5b242018-08-10 15:03:23 -0700637 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700638 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
639 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700640 } else {
641 mEventThreadSource =
642 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800643 mPhaseOffsets->getCurrentAppOffset(), true, "app");
Ana Krulec98b5b242018-08-10 15:03:23 -0700644 mEventThread =
645 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700646 impl::EventThread::InterceptVSyncsCallback(),
647 "appEventThread");
648 mSfEventThreadSource =
649 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800650 mPhaseOffsets->getCurrentSfOffset(), true, "sf");
Ana Krulec98b5b242018-08-10 15:03:23 -0700651
652 mSFEventThread =
653 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700654 [this](nsecs_t timestamp) {
655 mInterceptor->saveVSyncEvent(timestamp);
656 },
657 "sfEventThread");
Dominik Laskowskif654d572018-12-20 11:03:06 -0800658 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Ana Krulec98b5b242018-08-10 15:03:23 -0700659 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
660 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800661
Steven Thomasb02664d2017-07-26 18:48:28 -0700662 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700663 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700664 renderEngineFeature |= (useColorManagement ?
665 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700666 renderEngineFeature |= (useContextPriority ?
667 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700668
669 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700670 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700671 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700672 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700673
674 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
675 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700676 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
677 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800678 // Process any initial hotplug and resulting display changes.
679 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700680 const auto display = getDefaultDisplayDeviceLocked();
681 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700682 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700683 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800684
Steven Thomas050b2c82017-03-06 11:45:16 -0800685 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700686 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700687 // This callback is called from the vr flinger dispatch thread. We
688 // need to call signalTransaction(), which requires holding
689 // mStateLock when we're not on the main thread. Acquiring
690 // mStateLock from the vr flinger dispatch thread might trigger a
691 // deadlock in surface flinger (see b/66916578), so post a message
692 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700693 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700694 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
695 mVrFlingerRequestsDisplay = requestDisplay;
696 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700697 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800698 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700699 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
700 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700701 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700702 .value_or(0),
703 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800704 if (!mVrFlinger) {
705 ALOGE("Failed to start vrflinger");
706 }
707 }
708
Lloyd Pique90c115d2018-09-18 21:39:42 -0700709 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700710 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700711
Mathias Agopian92a979a2012-08-02 18:32:23 -0700712 // initialize our drawing state
713 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700714
Andy McFadden13a082e2012-08-24 10:16:42 -0700715 // set initial conditions (e.g. unblank default device)
716 initializeDisplays();
717
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700718 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700719
Wei Wangf9b05ee2017-07-19 20:59:39 -0700720 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700721
722 const bool presentFenceReliable =
723 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
724 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700725
726 if (mStartPropertySetThread->Start() != NO_ERROR) {
727 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800728 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800729
Ana Krulec7d1d6832018-12-27 11:10:09 -0800730 if (mUseScheduler) {
Ana Krulec757f63a2019-01-25 10:46:18 -0800731 mScheduler->setExpiredIdleTimerCallback([this]() {
732 mPhaseOffsets->setRefreshRateType(
733 scheduler::RefreshRateConfigs::RefreshRateType::DEFAULT);
734 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
735 mVsyncModulator.setPhaseOffsets(early, gl, late);
736 setRefreshRateTo(60.f /* fps */);
737 });
738 mScheduler->setResetIdleTimerCallback([this]() {
739 mPhaseOffsets->setRefreshRateType(
740 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
741 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
742 mVsyncModulator.setPhaseOffsets(early, gl, late);
743 setRefreshRateTo(90.f /* fps */);
744 });
Alec Mourifb571ea2019-01-24 18:42:10 -0800745 mRefreshRateStats =
746 std::make_unique<scheduler::RefreshRateStats>(getHwComposer().getConfigs(
747 *display->getId()),
748 mTimeStats);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800749 }
750
Dan Stoza9e56aa02015-11-02 13:00:03 -0800751 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700752}
753
Romain Guy11d63f42017-07-20 12:47:14 -0700754void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700755 Mutex::Autolock _l(mStateLock);
756
Romain Guy11d63f42017-07-20 12:47:14 -0700757 char value[PROPERTY_VALUE_MAX];
758
759 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800760 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700761 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800762 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100763
764 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700765 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700766}
767
Mathias Agopiana67e4182012-06-19 17:26:12 -0700768void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800769 // Start boot animation service by setting a property mailbox
770 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700771 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800772 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700773 if (mStartPropertySetThread->join() != NO_ERROR) {
774 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800775 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700776}
777
Mathias Agopian875d8e12013-06-07 15:35:48 -0700778size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700779 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700780}
781
Mathias Agopian875d8e12013-06-07 15:35:48 -0700782size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700783 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700784}
785
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800786// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800787
Jamie Gennis582270d2011-08-17 18:19:00 -0700788bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800789 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800790 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800791 return authenticateSurfaceTextureLocked(bufferProducer);
792}
793
794bool SurfaceFlinger::authenticateSurfaceTextureLocked(
795 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800796 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800797 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800798}
799
Brian Anderson6b376712017-04-04 10:51:39 -0700800status_t SurfaceFlinger::getSupportedFrameTimestamps(
801 std::vector<FrameEvent>* outSupported) const {
802 *outSupported = {
803 FrameEvent::REQUESTED_PRESENT,
804 FrameEvent::ACQUIRE,
805 FrameEvent::LATCH,
806 FrameEvent::FIRST_REFRESH_START,
807 FrameEvent::LAST_REFRESH_START,
808 FrameEvent::GPU_COMPOSITION_DONE,
809 FrameEvent::DEQUEUE_READY,
810 FrameEvent::RELEASE,
811 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700812 ConditionalLock _l(mStateLock,
813 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700814 if (!getHwComposer().hasCapability(
815 HWC2::Capability::PresentFenceIsNotReliable)) {
816 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
817 }
818 return NO_ERROR;
819}
820
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700821status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
822 Vector<DisplayInfo>* configs) {
823 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700824 return BAD_VALUE;
825 }
826
Dominik Laskowski075d3172018-05-24 15:50:06 -0700827 const auto displayId = getPhysicalDisplayId(displayToken);
828 if (!displayId) {
829 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700830 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700831
Mathias Agopian8b736f12012-08-13 17:54:26 -0700832 // TODO: Not sure if display density should handled by SF any longer
833 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700834 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700836 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800837 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700838 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700839 }
840 return density;
841 }
842 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700843 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700844 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700845 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700846 return getDensityFromProperty("ro.sf.lcd_density"); }
847 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700848
Dan Stoza7f7da322014-05-02 15:26:25 -0700849 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700850
Steven Thomas6d8110b2017-08-31 18:24:21 -0700851 ConditionalLock _l(mStateLock,
852 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700853 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700854 DisplayInfo info = DisplayInfo();
855
Dan Stoza9e56aa02015-11-02 13:00:03 -0800856 float xdpi = hwConfig->getDpiX();
857 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700858
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700859 info.w = hwConfig->getWidth();
860 info.h = hwConfig->getHeight();
861 // Default display viewport to display width and height
862 info.viewportW = info.w;
863 info.viewportH = info.h;
864
Dominik Laskowski075d3172018-05-24 15:50:06 -0700865 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700866 // The density of the device is provided by a build property
867 float density = Density::getBuildDensity() / 160.0f;
868 if (density == 0) {
869 // the build doesn't provide a density -- this is wrong!
870 // use xdpi instead
871 ALOGE("ro.sf.lcd_density must be defined as a build property");
872 density = xdpi / 160.0f;
873 }
874 if (Density::getEmuDensity()) {
875 // if "qemu.sf.lcd_density" is specified, it overrides everything
876 xdpi = ydpi = density = Density::getEmuDensity();
877 density /= 160.0f;
878 }
879 info.density = density;
880
881 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700882 const auto display = getDefaultDisplayDeviceLocked();
883 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700884
885 // This is for screenrecord
886 const Rect viewport = display->getViewport();
887 if (viewport.isValid()) {
888 info.viewportW = uint32_t(viewport.getWidth());
889 info.viewportH = uint32_t(viewport.getHeight());
890 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700891 } else {
892 // TODO: where should this value come from?
893 static const int TV_DENSITY = 213;
894 info.density = TV_DENSITY / 160.0f;
895 info.orientation = 0;
896 }
897
Dan Stoza7f7da322014-05-02 15:26:25 -0700898 info.xdpi = xdpi;
899 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800900 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800901 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800902
Andy McFadden91b2ca82014-06-13 14:04:23 -0700903 // This is how far in advance a buffer must be queued for
904 // presentation at a given time. If you want a buffer to appear
905 // on the screen at time N, you must submit the buffer before
906 // (N - presentationDeadline).
907 //
908 // Normally it's one full refresh period (to give SF a chance to
909 // latch the buffer), but this can be reduced by configuring a
910 // DispSync offset. Any additional delays introduced by the hardware
911 // composer or panel must be accounted for here.
912 //
913 // We add an additional 1ms to allow for processing time and
914 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800915 info.presentationDeadline =
916 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700917
918 // All non-virtual displays are currently considered secure.
919 info.secure = true;
920
Dominik Laskowski075d3172018-05-24 15:50:06 -0700921 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700922 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800923 std::swap(info.w, info.h);
924 }
925
Michael Wright28f24d02016-07-12 13:30:53 -0700926 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700927 }
928
Dan Stoza7f7da322014-05-02 15:26:25 -0700929 return NO_ERROR;
930}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700931
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700932status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
933 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700934 return BAD_VALUE;
935 }
936
Ana Krulece588e312018-09-18 12:32:24 -0700937 if (mUseScheduler) {
938 mScheduler->getDisplayStatInfo(stats);
939 } else {
940 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
941 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
942 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700943 return NO_ERROR;
944}
945
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700946int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
947 const auto display = getDisplayDevice(displayToken);
948 if (!display) {
949 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800950 return BAD_VALUE;
951 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700952
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700953 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700954}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700955
Ana Krulec7d1d6832018-12-27 11:10:09 -0800956status_t SurfaceFlinger::setActiveConfigAsync(const sp<IBinder>& displayToken, int mode) {
957 ATRACE_NAME("setActiveConfigAsync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800958 postMessageAsync(new LambdaMessage(
959 [=]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800960 return NO_ERROR;
961}
962
963status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
964 ATRACE_NAME("setActiveConfigSync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800965 postMessageSync(new LambdaMessage(
966 [&]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800967 return NO_ERROR;
968}
969
970void SurfaceFlinger::setActiveConfigInternal(const sp<IBinder>& displayToken, int mode) {
971 Vector<DisplayInfo> configs;
972 getDisplayConfigs(displayToken, &configs);
973 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
974 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
975 return;
976 }
977
978 const auto display = getDisplayDevice(displayToken);
979 if (!display) {
980 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
981 displayToken.get());
982 return;
983 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700984 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800985 ALOGW("Attempt to set active config %d for virtual display", mode);
986 return;
987 }
988 int currentDisplayPowerMode = display->getPowerMode();
989 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
990 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700991 return;
992 }
993
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700994 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700995 if (mode == currentMode) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800996 // Don't update config if we are already running in the desired mode.
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700997 return;
998 }
Ana Krulecb43429d2019-01-09 14:28:51 -0800999 if (mUseScheduler) {
1000 mRefreshRateStats->setConfigMode(mode);
1001 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001002
Dominik Laskowski075d3172018-05-24 15:50:06 -07001003 const auto displayId = display->getId();
1004 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001005
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001006 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001007 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001008
Ana Krulec7d1d6832018-12-27 11:10:09 -08001009 ATRACE_INT("ActiveConfigMode", mode);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001010 resyncToHardwareVsync(true, getVsyncPeriod());
Mathias Agopianc666cae2012-07-25 18:56:13 -07001011}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001012
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001013status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1014 Vector<ColorMode>* outColorModes) {
1015 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001016 return BAD_VALUE;
1017 }
1018
Dominik Laskowski075d3172018-05-24 15:50:06 -07001019 const auto displayId = getPhysicalDisplayId(displayToken);
1020 if (!displayId) {
1021 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -07001022 }
1023
Peiyong Lina52f0292018-03-14 17:26:31 -07001024 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001025 {
1026 ConditionalLock _l(mStateLock,
1027 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001028 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001029 }
Michael Wright28f24d02016-07-12 13:30:53 -07001030 outColorModes->clear();
1031 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1032
1033 return NO_ERROR;
1034}
1035
Daniel Solomon42d04562019-01-20 21:03:19 -08001036status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1037 ui::DisplayPrimaries &primaries) {
1038 if (!displayToken) {
1039 return BAD_VALUE;
1040 }
1041
1042 // Currently we only support this API for a single internal display.
1043 if (getInternalDisplayToken() != displayToken) {
1044 return BAD_VALUE;
1045 }
1046
1047 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1048 return NO_ERROR;
1049}
1050
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001051ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1052 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001053 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001054 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001055 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001056}
1057
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001058status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001059 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001060 Vector<ColorMode> modes;
1061 getDisplayColorModes(displayToken, &modes);
1062 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1063 if (mode < ColorMode::NATIVE || !exists) {
1064 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1065 decodeColorMode(mode).c_str(), mode, displayToken.get());
1066 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001067 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001068 const auto display = getDisplayDevice(displayToken);
1069 if (!display) {
1070 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1071 decodeColorMode(mode).c_str(), mode, displayToken.get());
1072 } else if (display->isVirtual()) {
1073 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1074 decodeColorMode(mode).c_str(), mode);
1075 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001076 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1077 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001078 }
1079 }));
1080
Michael Wright28f24d02016-07-12 13:30:53 -07001081 return NO_ERROR;
1082}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001083
Svetoslavd85084b2014-03-20 10:28:31 -07001084status_t SurfaceFlinger::clearAnimationFrameStats() {
1085 Mutex::Autolock _l(mStateLock);
1086 mAnimFrameTracker.clearStats();
1087 return NO_ERROR;
1088}
1089
1090status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1091 Mutex::Autolock _l(mStateLock);
1092 mAnimFrameTracker.getStats(outStats);
1093 return NO_ERROR;
1094}
1095
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001096status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1097 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001098 Mutex::Autolock _l(mStateLock);
1099
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001100 const auto display = getDisplayDeviceLocked(displayToken);
1101 if (!display) {
1102 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001103 return BAD_VALUE;
1104 }
1105
Peiyong Linfb069302018-04-25 14:34:31 -07001106 // At this point the DisplayDeivce should already be set up,
1107 // meaning the luminance information is already queried from
1108 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001109 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001110 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1111 capabilities.getDesiredMaxLuminance(),
1112 capabilities.getDesiredMaxAverageLuminance(),
1113 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001114
1115 return NO_ERROR;
1116}
1117
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001118status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1119 ui::PixelFormat* outFormat,
1120 ui::Dataspace* outDataspace,
1121 uint8_t* outComponentMask) const {
1122 if (!outFormat || !outDataspace || !outComponentMask) {
1123 return BAD_VALUE;
1124 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001125 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001126 if (!display || !display->getId()) {
1127 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1128 return BAD_VALUE;
1129 }
1130 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1131 outDataspace, outComponentMask);
1132}
1133
Kevin DuBois74e53772018-11-19 10:52:38 -08001134status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1135 bool enable, uint8_t componentMask,
1136 uint64_t maxFrames) const {
1137 const auto display = getDisplayDevice(displayToken);
1138 if (!display || !display->getId()) {
1139 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1140 return BAD_VALUE;
1141 }
1142
1143 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1144 componentMask, maxFrames);
1145}
1146
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001147status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1148 uint64_t maxFrames, uint64_t timestamp,
1149 DisplayedFrameStats* outStats) const {
1150 const auto display = getDisplayDevice(displayToken);
1151 if (!display || !display->getId()) {
1152 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1153 return BAD_VALUE;
1154 }
1155
1156 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1157 outStats);
1158}
1159
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001160status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1161 if (!outSupported) {
1162 return BAD_VALUE;
1163 }
1164 *outSupported = getRenderEngine().supportsProtectedContent();
1165 return NO_ERROR;
1166}
1167
Marissa Wallebc2c052019-01-16 19:16:55 -08001168status_t SurfaceFlinger::cacheBuffer(const sp<IBinder>& token, const sp<GraphicBuffer>& buffer,
1169 int32_t* outBufferId) {
1170 if (!outBufferId) {
1171 return BAD_VALUE;
1172 }
1173 *outBufferId = mBufferStateLayerCache.add(token, buffer);
1174 return NO_ERROR;
1175}
1176
1177status_t SurfaceFlinger::uncacheBuffer(const sp<IBinder>& token, int32_t bufferId) {
1178 mBufferStateLayerCache.release(token, bufferId);
1179 return NO_ERROR;
1180}
1181
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001182status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1183 bool* outIsWideColorDisplay) const {
1184 if (!displayToken || !outIsWideColorDisplay) {
1185 return BAD_VALUE;
1186 }
1187 Mutex::Autolock _l(mStateLock);
1188 const auto display = getDisplayDeviceLocked(displayToken);
1189 if (!display) {
1190 return BAD_VALUE;
1191 }
1192 *outIsWideColorDisplay = display->hasWideColorGamut();
1193 return NO_ERROR;
1194}
1195
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001196status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001197 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001198 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001199
Chia-I Wu90f669f2017-10-05 14:24:41 -07001200 if (mInjectVSyncs == enable) {
1201 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001202 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001203
Dominik Laskowski83b88212018-12-11 13:34:06 -08001204 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001205
Ana Krulec98b5b242018-08-10 15:03:23 -07001206 // TODO(akrulec): Part of the Injector should be refactored, so that it
1207 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001208 if (enable) {
1209 ALOGV("VSync Injections enabled");
1210 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001211 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001212 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001213 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001214 impl::EventThread::InterceptVSyncsCallback(),
1215 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001216 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001217 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001218 } else {
1219 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001220 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001221 }
1222
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001223 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001224 }));
1225
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001226 return NO_ERROR;
1227}
1228
1229status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001230 Mutex::Autolock _l(mStateLock);
1231
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001232 if (!mInjectVSyncs) {
1233 ALOGE("VSync Injections not enabled");
1234 return BAD_VALUE;
1235 }
1236 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1237 ALOGV("Injecting VSync inside SurfaceFlinger");
1238 mVSyncInjector->onInjectSyncEvent(when);
1239 }
1240 return NO_ERROR;
1241}
1242
Lloyd Pique755e3192018-01-31 16:46:15 -08001243status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1244 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001245 // Try to acquire a lock for 1s, fail gracefully
1246 const status_t err = mStateLock.timedLock(s2ns(1));
1247 const bool locked = (err == NO_ERROR);
1248 if (!locked) {
1249 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1250 return TIMED_OUT;
1251 }
1252
1253 outLayers->clear();
1254 mCurrentState.traverseInZOrder([&](Layer* layer) {
1255 outLayers->push_back(layer->getLayerDebugInfo());
1256 });
1257
1258 mStateLock.unlock();
1259 return NO_ERROR;
1260}
1261
Peiyong Linc6780972018-10-28 15:24:08 -07001262status_t SurfaceFlinger::getCompositionPreference(
1263 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1264 Dataspace* outWideColorGamutDataspace,
1265 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001266 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001267 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001268 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001269 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001270 return NO_ERROR;
1271}
1272
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001273// ----------------------------------------------------------------------------
1274
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001275sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1276 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001277 auto resyncCallback = makeResyncCallback([this] {
1278 Mutex::Autolock lock(mStateLock);
1279 return getVsyncPeriod();
1280 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001281
Ana Krulec98b5b242018-08-10 15:03:23 -07001282 if (mUseScheduler) {
1283 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001284 return mScheduler->createDisplayEventConnection(mSfConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001285 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001286 return mScheduler->createDisplayEventConnection(mAppConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001287 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001288 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001289 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001290 return mSFEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001291 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001292 return mEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001293 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001294 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001295}
1296
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001297// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001298
1299void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001300 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001301}
1302
1303void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001304 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001305}
1306
1307void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001308 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001309}
1310
1311void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001312 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001313 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001314}
1315
1316status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001317 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001318 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001319}
1320
1321status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001322 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001323 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001324 if (res == NO_ERROR) {
1325 msg->wait();
1326 }
1327 return res;
1328}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001329
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001330void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001331 do {
1332 waitForEvent();
1333 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001334}
1335
Dominik Laskowski83b88212018-12-11 13:34:06 -08001336nsecs_t SurfaceFlinger::getVsyncPeriod() const {
1337 const auto displayId = getInternalDisplayId();
1338 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1339 return 0;
1340 }
1341
1342 const auto config = getHwComposer().getActiveConfig(*displayId);
1343 return config ? config->getVsyncPeriod() : 0;
1344}
1345
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001346void SurfaceFlinger::enableHardwareVsync() {
1347 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001348 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001349 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001350 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001351 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001352 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001353}
1354
Dominik Laskowski83b88212018-12-11 13:34:06 -08001355void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001356 Mutex::Autolock _l(mHWVsyncLock);
1357
Jesse Hall948fe0c2013-10-14 12:56:09 -07001358 if (makeAvailable) {
1359 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001360 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1361 if (mUseScheduler) {
1362 mScheduler->makeHWSyncAvailable(true);
1363 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001364 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001365 // Hardware vsync is not currently available, so abort the resync
1366 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001367 return;
1368 }
1369
Dominik Laskowski83b88212018-12-11 13:34:06 -08001370 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001371 return;
1372 }
1373
Ana Krulece588e312018-09-18 12:32:24 -07001374 if (mUseScheduler) {
1375 mScheduler->setVsyncPeriod(period);
1376 } else {
1377 mPrimaryDispSync->reset();
1378 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001379
Ana Krulece588e312018-09-18 12:32:24 -07001380 if (!mPrimaryHWVsyncEnabled) {
1381 mPrimaryDispSync->beginResync();
1382 mEventControlThread->setVsyncEnabled(true);
1383 mPrimaryHWVsyncEnabled = true;
1384 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001385 }
1386}
1387
Jesse Hall948fe0c2013-10-14 12:56:09 -07001388void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001389 Mutex::Autolock _l(mHWVsyncLock);
1390 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001391 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001392 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001393 mPrimaryHWVsyncEnabled = false;
1394 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001395 if (makeUnavailable) {
1396 mHWVsyncAvailable = false;
1397 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001398}
1399
Dominik Laskowski83b88212018-12-11 13:34:06 -08001400void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001401 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001402
Dan Stoza57164302017-05-08 14:03:54 -07001403 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001404 const nsecs_t last = lastResyncTime.exchange(now);
1405
1406 if (now - last > kIgnoreDelay) {
1407 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001408 }
1409}
1410
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001411void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1412 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001413 ATRACE_NAME("SF onVsync");
1414
Steven Thomas3cfac282017-02-06 12:29:30 -08001415 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001416 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001417 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001418 return;
1419 }
1420
Dominik Laskowski075d3172018-05-24 15:50:06 -07001421 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001422 return;
1423 }
1424
Dominik Laskowski075d3172018-05-24 15:50:06 -07001425 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001426 // For now, we don't do anything with external display vsyncs.
1427 return;
1428 }
1429
Ana Krulece588e312018-09-18 12:32:24 -07001430 if (mUseScheduler) {
1431 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001432 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001433 bool needsHwVsync = false;
1434 { // Scope for the lock
1435 Mutex::Autolock _l(mHWVsyncLock);
1436 if (mPrimaryHWVsyncEnabled) {
1437 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1438 }
1439 }
1440
1441 if (needsHwVsync) {
1442 enableHardwareVsync();
1443 } else {
1444 disableHardwareVsync(false);
1445 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001446 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001447}
1448
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001449void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001450 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1451 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001452}
1453
Ana Krulec7d1d6832018-12-27 11:10:09 -08001454void SurfaceFlinger::setRefreshRateTo(float newFps) {
1455 const auto displayId = getInternalDisplayId();
1456 if (!displayId || mBootStage != BootStage::FINISHED) {
1457 return;
1458 }
1459 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1460 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1461 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1462 // refresh cycle.
1463
1464 // Don't do any updating if the current fps is the same as the new one.
1465 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
1466 const nsecs_t currentVsyncPeriod = activeConfig->getVsyncPeriod();
1467 if (currentVsyncPeriod == 0) {
1468 return;
1469 }
1470 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1471 // floating numbers.
1472 const float currentFps = 1e9 / currentVsyncPeriod;
1473 if (std::abs(currentFps - newFps) <= 1) {
1474 return;
1475 }
1476
1477 auto configs = getHwComposer().getConfigs(*displayId);
1478 for (int i = 0; i < configs.size(); i++) {
1479 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1480 if (vsyncPeriod == 0) {
1481 continue;
1482 }
1483 const float fps = 1e9 / vsyncPeriod;
1484 // TODO(b/113612090): There should be a better way at determining which config
1485 // has the right refresh rate.
1486 if (std::abs(fps - newFps) <= 1) {
1487 const auto display = getBuiltInDisplay(HWC_DISPLAY_PRIMARY);
1488 if (!display) return;
1489 // This is posted in async function to avoid deadlock when getDisplayDevice
1490 // requires mStateLock.
1491 setActiveConfigAsync(display, i);
1492 ATRACE_INT("FPS", newFps);
1493 }
1494 }
1495}
1496
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001497void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001498 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001499 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001500 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001501
Lloyd Piqueba04e622017-12-14 17:11:26 -08001502 // Ignore events that do not have the right sequenceId.
1503 if (sequenceId != getBE().mComposerSequenceId) {
1504 return;
1505 }
1506
Steven Thomasb02664d2017-07-26 18:48:28 -07001507 // Only lock if we're not on the main thread. This function is normally
1508 // called on a hwbinder thread, but for the primary display it's called on
1509 // the main thread with the state lock already held, so don't attempt to
1510 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001511 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001512
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001513 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001514
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001515 if (std::this_thread::get_id() == mMainThreadId) {
1516 // Process all pending hot plug events immediately if we are on the main thread.
1517 processDisplayHotplugEventsLocked();
1518 }
1519
Lloyd Piqueba04e622017-12-14 17:11:26 -08001520 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001521}
1522
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001523void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001524 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001525 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001526 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001527 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001528 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001529}
1530
Dominik Laskowski075d3172018-05-24 15:50:06 -07001531void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001532 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001533 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001534 if (const auto displayId = getInternalDisplayId()) {
1535 getHwComposer().setVsyncEnabled(*displayId,
1536 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1537 }
Mathias Agopian86303202012-07-24 22:46:10 -07001538}
1539
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001540// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001541void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001542 if (mUseScheduler) {
1543 mScheduler->disableHardwareVsync(true);
1544 } else {
1545 disableHardwareVsync(true);
1546 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001547 // Clear the drawing state so that the logic inside of
1548 // handleTransactionLocked will fire. It will determine the delta between
1549 // mCurrentState and mDrawingState and re-apply all changes when we make the
1550 // transition.
1551 mDrawingState.displays.clear();
1552 mDisplays.clear();
1553}
1554
Steven Thomas050b2c82017-03-06 11:45:16 -08001555void SurfaceFlinger::updateVrFlinger() {
1556 if (!mVrFlinger)
1557 return;
1558 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001559 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001560 return;
1561 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001562
Lloyd Pique441d5042018-10-18 16:49:51 -07001563 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001564 ALOGE("Vr flinger is only supported for remote hardware composer"
1565 " service connections. Ignoring request to transition to vr"
1566 " flinger.");
1567 mVrFlingerRequestsDisplay = false;
1568 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001569 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001570
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001571 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001572
Steven Thomas0123ac62018-07-12 11:32:34 -07001573 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001574 LOG_ALWAYS_FATAL_IF(!display);
1575 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001576 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1577 // called below. Clear the reference now so we don't accidentally use it
1578 // later.
1579 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001580
Steven Thomasb02664d2017-07-26 18:48:28 -07001581 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001582 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001583 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001584
Steven Thomasb02664d2017-07-26 18:48:28 -07001585 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001586 // Delete the current instance before creating the new one
1587 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1588 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1589 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1590 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001591
Lloyd Pique441d5042018-10-18 16:49:51 -07001592 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001593 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001594
1595 if (vrFlingerRequestsDisplay) {
1596 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001597 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001598
1599 mVisibleRegionsDirty = true;
1600 invalidateHwcGeometry();
1601
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001602 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001603 display = getDefaultDisplayDeviceLocked();
1604 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001605 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001606
Steven Thomasb02664d2017-07-26 18:48:28 -07001607 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001608 const nsecs_t vsyncPeriod = getVsyncPeriod();
1609 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001610
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001611 // The present fences returned from vr_hwc are not an accurate
1612 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001613 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001614 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1615 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001616 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001617 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001618 !hasSyncFramework);
1619 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001620
Steven Thomasb02664d2017-07-26 18:48:28 -07001621 // Use phase of 0 since phase is not known.
1622 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001623 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001624 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001625
Dominik Laskowski83b88212018-12-11 13:34:06 -08001626 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001627
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001628 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001629 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001630}
1631
Mathias Agopian4fec8732012-06-29 14:12:52 -07001632void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001633 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001634 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001635 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001636 if (mUseScheduler) {
1637 // This call is made each time SF wakes up and creates a new frame.
1638 mScheduler->incrementFrameCounter();
1639 }
Dan Stoza50182882016-07-08 12:02:20 -07001640 bool frameMissed = !mHadClientComposition &&
1641 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001642 (mPreviousPresentFence->getSignalTime() ==
1643 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001644 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001645 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001646 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001647 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001648 if (mPropagateBackpressure) {
1649 signalLayerUpdate();
1650 break;
1651 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001652 }
Dan Stoza50182882016-07-08 12:02:20 -07001653
Steven Thomas050b2c82017-03-06 11:45:16 -08001654 // Now that we're going to make it to the handleMessageTransaction()
1655 // call below it's safe to call updateVrFlinger(), which will
1656 // potentially trigger a display handoff.
1657 updateVrFlinger();
1658
Dan Stoza6b9454d2014-11-07 16:00:59 -08001659 bool refreshNeeded = handleMessageTransaction();
1660 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001661 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001662 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001663 // Signal a refresh if a transaction modified the window state,
1664 // a new buffer was latched, or if HWC has requested a full
1665 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001666 signalRefresh();
1667 }
1668 break;
1669 }
1670 case MessageQueue::REFRESH: {
1671 handleMessageRefresh();
1672 break;
1673 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001674 }
1675}
1676
Dan Stoza6b9454d2014-11-07 16:00:59 -08001677bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001678 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001679
1680 // Apply any ready transactions in the queues if there are still transactions that have not been
1681 // applied, wake up during the next vsync period and check again
1682 bool transactionNeeded = false;
1683 if (!flushTransactionQueues()) {
1684 transactionNeeded = true;
1685 }
1686
Mathias Agopian4fec8732012-06-29 14:12:52 -07001687 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001688 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001689 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001690
1691 if (transactionNeeded) {
1692 setTransactionFlags(eTransactionNeeded);
1693 }
1694
1695 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001696}
1697
Mathias Agopian4fec8732012-06-29 14:12:52 -07001698void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001699 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001700
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001701 mRefreshPending = false;
1702
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001703 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001704 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001705 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001706 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001707 for (const auto& [token, display] : mDisplays) {
1708 beginFrame(display);
1709 prepareFrame(display);
1710 doDebugFlashRegions(display, repaintEverything);
1711 doComposition(display, repaintEverything);
1712 }
1713
Adrian Roos1e1a1282017-11-01 19:05:31 +01001714 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001715 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001716
1717 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001718 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001719
Dan Stozabfbffeb2016-07-21 14:49:33 -07001720 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001721 for (const auto& [token, displayDevice] : mDisplays) {
1722 auto display = displayDevice->getCompositionDisplay();
1723 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001724 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001725 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001726 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001727
Alec Mouri86770e52018-09-24 22:40:58 +00001728 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001729 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001730 if (mHadClientComposition) {
1731 base::unique_fd flushFence(getRenderEngine().flush());
1732 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1733 getBE().flushFence = new Fence(std::move(flushFence));
1734 } else {
1735 // Cleanup for hygiene.
1736 getBE().flushFence = Fence::NO_FENCE;
1737 }
1738 }
1739
Jorim Jaggi90535212018-05-23 23:44:06 +02001740 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001741
David Sodman7e4ae112018-02-09 15:02:28 -08001742 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001743 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001744 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001745 compositionInfo.hwc.hwcLayer = nullptr;
1746 }
David Sodmanba340492018-08-05 21:51:33 -07001747 }
David Sodman7e4ae112018-02-09 15:02:28 -08001748
1749 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001750}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001751
David Sodmanfa9b2af2017-12-24 13:28:59 -08001752
1753bool SurfaceFlinger::handleMessageInvalidate() {
1754 ATRACE_CALL();
1755 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001756}
1757
David Sodman79bba0e2018-08-05 18:07:49 -07001758void SurfaceFlinger::calculateWorkingSet() {
1759 ATRACE_CALL();
1760 ALOGV(__FUNCTION__);
1761
David Sodman79bba0e2018-08-05 18:07:49 -07001762 // build the h/w work list
1763 if (CC_UNLIKELY(mGeometryInvalid)) {
1764 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001765 for (const auto& [token, displayDevice] : mDisplays) {
1766 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001767 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001768 if (!displayId) {
1769 continue;
1770 }
David Sodman79bba0e2018-08-05 18:07:49 -07001771
Lloyd Pique32cbe282018-10-19 13:09:22 -07001772 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001773 for (size_t i = 0; i < currentLayers.size(); i++) {
1774 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001775
Dominik Laskowski075d3172018-05-24 15:50:06 -07001776 if (!layer->hasHwcLayer(*displayId)) {
1777 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1778 layer->forceClientComposition(*displayId);
1779 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001780 }
1781 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001782
Lloyd Pique32cbe282018-10-19 13:09:22 -07001783 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001784 if (mDebugDisableHWC || mDebugRegion) {
1785 layer->forceClientComposition(*displayId);
1786 }
David Sodman79bba0e2018-08-05 18:07:49 -07001787 }
1788 }
1789 }
1790
1791 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001792 for (const auto& [token, displayDevice] : mDisplays) {
1793 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001794 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001795 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001796 continue;
1797 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001798 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001799
1800 if (mDrawingState.colorMatrixChanged) {
1801 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001802 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001803 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001804 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001805 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001806 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1807 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001808 !profile->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001809 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001810 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1811 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001812 !profile->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001813 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001814 }
1815
Peiyong Lind3788632018-09-18 16:01:31 -07001816 // TODO(b/111562338) remove when composer 2.3 is shipped.
1817 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001818 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001819 }
1820
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001821 if (layer->getRoundedCornerState().radius > 0.0f) {
1822 layer->forceClientComposition(*displayId);
1823 }
1824
Dominik Laskowski075d3172018-05-24 15:50:06 -07001825 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001826 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001827 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001828 continue;
1829 }
1830
Lloyd Pique32cbe282018-10-19 13:09:22 -07001831 const auto& displayState = display->getState();
1832 layer->setPerFrameData(*displayId, displayState.transform, displayState.viewport,
1833 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001834 }
1835
Peiyong Lin13effd12018-07-24 17:01:47 -07001836 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001837 ColorMode colorMode;
1838 Dataspace dataSpace;
1839 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001840 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001841 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001842 }
1843 }
1844
1845 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001846
1847 for (const auto& [token, display] : mDisplays) {
1848 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001849 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001850 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001851
1852 if (displayId) {
1853 if (!layer->setHwcLayer(*displayId)) {
1854 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1855 }
1856 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001857 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001858
Dominik Laskowski05275f12018-11-01 15:03:24 -07001859 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001860 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1861 }
1862 }
David Sodman79bba0e2018-08-05 18:07:49 -07001863}
1864
Lloyd Pique32cbe282018-10-19 13:09:22 -07001865void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1866 bool repaintEverything) {
1867 auto display = displayDevice->getCompositionDisplay();
1868 const auto& displayState = display->getState();
1869
Mathias Agopiancd60f992012-08-16 16:28:27 -07001870 // is debugging enabled
1871 if (CC_LIKELY(!mDebugRegion))
1872 return;
1873
Lloyd Pique32cbe282018-10-19 13:09:22 -07001874 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001875 // transform the dirty region into this screen's coordinate space
Alec Mouri0f714832018-11-12 15:31:06 -08001876 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001877 if (!dirtyRegion.isEmpty()) {
Alec Mouri0f714832018-11-12 15:31:06 -08001878 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001879 // redraw the whole screen
Alec Mouri0f714832018-11-12 15:31:06 -08001880 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001881
Alec Mouri0f714832018-11-12 15:31:06 -08001882 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001883 }
1884 }
1885
Lloyd Pique32cbe282018-10-19 13:09:22 -07001886 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001887
1888 if (mDebugRegion > 1) {
1889 usleep(mDebugRegion * 1000);
1890 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001891
Lloyd Pique32cbe282018-10-19 13:09:22 -07001892 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001893}
1894
Adrian Roos1e1a1282017-11-01 19:05:31 +01001895void SurfaceFlinger::doTracing(const char* where) {
1896 ATRACE_CALL();
1897 ATRACE_NAME(where);
1898 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001899 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001900 }
1901}
1902
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001903void SurfaceFlinger::logLayerStats() {
1904 ATRACE_CALL();
1905 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001906 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001907 if (display->isPrimary()) {
1908 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001909 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001910 }
1911 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001912
1913 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001914 }
1915}
1916
David Sodman2b406362017-12-15 13:33:47 -08001917void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001918{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001919 ATRACE_CALL();
1920 ALOGV("preComposition");
1921
David Sodman2b406362017-12-15 13:33:47 -08001922 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1923
Mathias Agopiancd60f992012-08-16 16:28:27 -07001924 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001925 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001926 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001927 needExtraInvalidate = true;
1928 }
Robert Carr2047fae2016-11-28 14:09:09 -08001929 });
1930
Mathias Agopiancd60f992012-08-16 16:28:27 -07001931 if (needExtraInvalidate) {
1932 signalLayerUpdate();
1933 }
1934}
1935
Ana Krulece588e312018-09-18 12:32:24 -07001936void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1937 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001938 // Update queue of past composite+present times and determine the
1939 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001940 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001941 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001942 while (!getBE().mCompositePresentTimes.empty()) {
1943 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001944 // Cached values should have been updated before calling this method,
1945 // which helps avoid duplicate syscalls.
1946 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1947 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1948 break;
1949 }
1950 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001951 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001952 }
1953
1954 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001955 while (getBE().mCompositePresentTimes.size() > 16) {
1956 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001957 }
1958
Ana Krulece588e312018-09-18 12:32:24 -07001959 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001960}
1961
Ana Krulece588e312018-09-18 12:32:24 -07001962void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1963 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001964 // Integer division and modulo round toward 0 not -inf, so we need to
1965 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001966 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1967 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1968 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001969
Ana Krulec757f63a2019-01-25 10:46:18 -08001970 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001971 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001972 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001973 }
1974
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001975 // Snap the latency to a value that removes scheduling jitter from the
1976 // composition and present times, which often have >1ms of jitter.
1977 // Reducing jitter is important if an app attempts to extrapolate
1978 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001979 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001980 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001981 nsecs_t bias = stats.vsyncPeriod / 2;
1982 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1983 nsecs_t snappedCompositeToPresentLatency =
1984 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001985
David Sodman99974d22017-11-28 12:04:33 -08001986 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001987 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1988 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001989 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001990}
1991
Ady Abraham8164d482019-01-11 14:47:59 -08001992// debug patch for b/119477596 - add stack guards to catch stack
1993// corruptions and disable clang optimizations.
1994// The code below is temporary and planned to be removed once stack
1995// corruptions are found.
1996#pragma clang optimize off
1997class StackGuard {
1998public:
1999 StackGuard(const char* name, const char* func, int line) {
2000 guarders.reserve(MIN_CAPACITY);
2001 guarders.push_back({this, name, func, line});
2002 validate();
2003 }
2004 ~StackGuard() {
2005 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
2006 if (i->guard == this) {
2007 guarders.erase(i);
2008 break;
2009 }
2010 }
2011 }
2012
2013 static void validate() {
2014 for (const auto& guard : guarders) {
2015 if (guard.guard->cookie != COOKIE_VALUE) {
2016 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
2017 CallStack stack(LOG_TAG);
2018 abort();
2019 }
2020 }
2021 }
2022
2023private:
2024 uint64_t cookie = COOKIE_VALUE;
2025 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
2026 static constexpr size_t MIN_CAPACITY = 16;
2027
2028 struct GuarderElement {
2029 StackGuard* guard;
2030 const char* name;
2031 const char* func;
2032 int line;
2033 };
2034
2035 static std::vector<GuarderElement> guarders;
2036};
2037std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2038
2039#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2040
2041#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002042void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002043{
Ady Abraham8164d482019-01-11 14:47:59 -08002044 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002045 ATRACE_CALL();
2046 ALOGV("postComposition");
2047
Brian Anderson3546a3f2016-07-14 11:51:14 -07002048 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002049 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002050 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002051 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002052 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002053 }
Ady Abraham8164d482019-01-11 14:47:59 -08002054 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002055
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002056 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002057 const auto displayDevice = getDefaultDisplayDeviceLocked();
2058 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002059
David Sodman73beded2017-11-15 11:56:06 -08002060 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002061 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002062 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2063
Lloyd Pique32cbe282018-10-19 13:09:22 -07002064 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002065 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002066 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2067 ->getRenderSurface()
2068 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002069 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002070 } else {
2071 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2072 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002073
Ady Abraham8164d482019-01-11 14:47:59 -08002074 ASSERT_ON_STACK_GUARD();
2075
David Sodman73beded2017-11-15 11:56:06 -08002076 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002077 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2078 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002079 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002080 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002081 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002082
Ana Krulece588e312018-09-18 12:32:24 -07002083 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002084 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002085 if (mUseScheduler) {
2086 mScheduler->getDisplayStatInfo(&stats);
2087 } else {
2088 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2089 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2090 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002091
Ady Abraham8164d482019-01-11 14:47:59 -08002092 ASSERT_ON_STACK_GUARD();
2093
David Sodman2b406362017-12-15 13:33:47 -08002094 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002095 // when we started doing work for this frame, but that should be okay
2096 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002097 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002098 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002099 DEFINE_STACK_GUARD(compositorTiming);
2100
Brian Andersond0010582017-03-07 13:20:31 -08002101 {
David Sodman99974d22017-11-28 12:04:33 -08002102 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002103 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002104 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002105
2106 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002107 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002108
Robert Carr2047fae2016-11-28 14:09:09 -08002109 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002110 bool frameLatched =
2111 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2112 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002113 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002114 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002115 recordBufferingStats(layer->getName().string(),
2116 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002117 }
Ady Abraham8164d482019-01-11 14:47:59 -08002118 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002119 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002120
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002121 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002122 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002123 if (mUseScheduler) {
2124 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002125 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002126 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002127 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2128 enableHardwareVsync();
2129 } else {
2130 disableHardwareVsync(false);
2131 }
Ady Abraham8164d482019-01-11 14:47:59 -08002132 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002133 }
2134 }
2135
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002136 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002137 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2138 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002139 if (mUseScheduler) {
2140 mScheduler->enableHardwareVsync();
2141 } else {
2142 enableHardwareVsync();
2143 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002144 }
2145 }
2146
Ady Abraham8164d482019-01-11 14:47:59 -08002147 ASSERT_ON_STACK_GUARD();
2148
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002149 if (mAnimCompositionPending) {
2150 mAnimCompositionPending = false;
2151
Brian Anderson4e606e32017-03-16 15:34:57 -07002152 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002153 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002154 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002155
2156 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002157 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002158 // The HWC doesn't support present fences, so use the refresh
2159 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002160 const nsecs_t presentTime =
2161 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002162 DEFINE_STACK_GUARD(presentTime);
2163
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002164 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002165 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002166 }
2167 mAnimFrameTracker.advanceFrame();
2168 }
Dan Stozab90cf072015-03-05 11:05:59 -08002169
Ady Abraham8164d482019-01-11 14:47:59 -08002170 ASSERT_ON_STACK_GUARD();
2171
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002172 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002173 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002174 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002175 }
2176
Ady Abraham8164d482019-01-11 14:47:59 -08002177 ASSERT_ON_STACK_GUARD();
2178
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002179 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002180
Ady Abraham8164d482019-01-11 14:47:59 -08002181 ASSERT_ON_STACK_GUARD();
2182
Lloyd Pique32cbe282018-10-19 13:09:22 -07002183 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2184 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002185 return;
2186 }
2187
2188 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002189 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002190 if (mHasPoweredOff) {
2191 mHasPoweredOff = false;
2192 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002193 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002194 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002195 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002196 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002197 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2198 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002199 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002200 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002201 }
David Sodman4a36e932017-11-07 14:29:47 -08002202 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002203
2204 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002205 }
David Sodman4a36e932017-11-07 14:29:47 -08002206 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002207 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002208
2209 {
2210 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002211 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002212 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002213 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002214 if (refillCount > 0) {
2215 const size_t offset = mTexturePool.size();
2216 mTexturePool.resize(mTexturePoolSize);
2217 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2218 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2219 }
Ady Abraham8164d482019-01-11 14:47:59 -08002220 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002221 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002222
Marissa Wallfda30bb2018-10-12 11:34:28 -07002223 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002224 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002225
2226 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002227}
Ady Abraham8164d482019-01-11 14:47:59 -08002228#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002229
2230void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002231 ATRACE_CALL();
2232 ALOGV("rebuildLayerStacks");
2233
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002234 // We need to clear these out now as these may be holding on to a
2235 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2236 // also holds a reference. When the set of visible layers is recomputed,
2237 // some layers may be destroyed if the only thing keeping them alive was
2238 // that list of visible layers associated with each display. The layer
2239 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2240 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2241 for (const auto& [token, display] : mDisplays) {
2242 getBE().mCompositionInfo[token].clear();
2243 }
2244
Mathias Agopiancd60f992012-08-16 16:28:27 -07002245 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002246 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002247 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002248 mVisibleRegionsDirty = false;
2249 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002250
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002251 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002252 const auto& displayDevice = pair.second;
2253 auto display = displayDevice->getCompositionDisplay();
2254 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002255 Region opaqueRegion;
2256 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002257 compositionengine::Output::OutputLayers layersSortedByZ;
2258 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002259 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002260 const ui::Transform& tr = displayState.transform;
2261 const Rect bounds = displayState.bounds;
2262 if (displayState.isEnabled) {
2263 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002264
Jeff Sharkey76488112017-02-27 14:15:18 -07002265 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002266 auto compositionLayer = layer->getCompositionLayer();
2267 if (compositionLayer == nullptr) {
2268 return;
2269 }
2270
Chia-I Wu83806892017-11-16 10:50:20 -08002271 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002272 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002273 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2274 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2275
Lloyd Piqueef36b002019-01-23 17:52:04 -08002276 if (display->belongsInOutput(layer->getLayerStack(),
2277 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002278 Region drawRegion(tr.transform(
2279 layer->visibleNonTransparentRegion));
2280 drawRegion.andSelf(bounds);
2281 if (!drawRegion.isEmpty()) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002282 layersSortedByZ.emplace_back(
2283 display->getOrCreateOutputLayer(layer->getCompositionLayer(),
2284 layerFE));
2285
2286 deprecated_layersSortedByZ.add(layer);
Jeff Sharkey76488112017-02-27 14:15:18 -07002287 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002288 // Clear out the HWC layer if this layer was
2289 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002290 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002291 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002292 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002293 // WM changes display->layerStack upon sleep/awake.
2294 // Here we make sure we delete the HWC layers even if
2295 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002296 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002297 }
2298
2299 // If a layer is not going to get a release fence because
2300 // it is invisible, but it is also going to release its
2301 // old buffer, add it to the list of layers needing
2302 // fences.
2303 if (hwcLayerDestroyed) {
2304 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2305 mLayersWithQueuedFrames.cend(), layer);
2306 if (found != mLayersWithQueuedFrames.cend()) {
2307 layersNeedingFences.add(layer);
2308 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002309 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002310 });
2311 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002312
2313 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2314
2315 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002316 displayDevice->setLayersNeedingFences(layersNeedingFences);
2317
2318 Region undefinedRegion{bounds};
2319 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2320
2321 display->editState().undefinedRegion = undefinedRegion;
2322 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002323 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002324 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002325}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002326
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002327// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002328// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002329// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002330// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002331// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002332// The returned HDR data space is one of
2333// - Dataspace::UNKNOWN
2334// - Dataspace::BT2020_HLG
2335// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002336Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2337 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002338 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002339 *outHdrDataSpace = Dataspace::UNKNOWN;
2340
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002341 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002342 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002343 case Dataspace::V0_SCRGB:
2344 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002345 case Dataspace::BT2020:
2346 case Dataspace::BT2020_ITU:
2347 case Dataspace::BT2020_LINEAR:
2348 case Dataspace::DISPLAY_BT2020:
2349 bestDataSpace = Dataspace::DISPLAY_BT2020;
2350 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002351 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002352 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002353 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002354 case Dataspace::BT2020_PQ:
2355 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002356 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002357 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002358 case Dataspace::BT2020_HLG:
2359 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002360 // When there's mixed PQ content and HLG content, we set the HDR
2361 // data space to be BT2020_PQ and convert HLG to PQ.
2362 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2363 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002364 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002365 break;
2366 default:
2367 break;
2368 }
Romain Guy54f154a2017-10-24 21:40:32 +01002369 }
2370
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002371 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002372}
2373
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002374// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002375void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2376 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002377 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2378 *outMode = ColorMode::NATIVE;
2379 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002380 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002381 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002382 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002383
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002384 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002385 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002386
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002387 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2388
Peiyong Lindfde5112018-06-05 10:58:41 -07002389 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002390 const bool isHdr =
2391 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002392 if (isHdr) {
2393 bestDataSpace = hdrDataSpace;
2394 }
2395
Chia-I Wu0d711262018-05-21 15:19:35 -07002396 RenderIntent intent;
2397 switch (mDisplayColorSetting) {
2398 case DisplayColorSetting::MANAGED:
2399 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002400 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002401 break;
2402 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002403 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002404 break;
2405 default: // vendor display color setting
2406 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2407 break;
2408 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002409
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002410 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002411}
2412
Lloyd Pique32cbe282018-10-19 13:09:22 -07002413void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2414 auto display = displayDevice->getCompositionDisplay();
2415 const auto& displayState = display->getState();
2416
Alec Mouri0f714832018-11-12 15:31:06 -08002417 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002418 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2419 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002420
David Sodmanfa9b2af2017-12-24 13:28:59 -08002421 // If nothing has changed (!dirty), don't recompose.
2422 // If something changed, but we don't currently have any visible layers,
2423 // and didn't when we last did a composition, then skip it this time.
2424 // The second rule does two things:
2425 // - When all layers are removed from a display, we'll emit one black
2426 // frame, then nothing more until we get new layers.
2427 // - When a display is created with a private layer stack, we won't
2428 // emit any black frames until a layer is added to the layer stack.
2429 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002430
Dominik Laskowski075d3172018-05-24 15:50:06 -07002431 const char flagPrefix[] = {'-', '+'};
2432 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002433 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2434 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2435 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2436 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002437
Lloyd Pique31cb2942018-10-19 17:23:03 -07002438 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002439
David Sodmanfa9b2af2017-12-24 13:28:59 -08002440 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002441 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002442 }
2443}
2444
Lloyd Pique32cbe282018-10-19 13:09:22 -07002445void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2446 auto display = displayDevice->getCompositionDisplay();
2447 const auto& displayState = display->getState();
2448
2449 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002450 return;
David Sodman2b406362017-12-15 13:33:47 -08002451 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002452
Lloyd Pique31cb2942018-10-19 17:23:03 -07002453 status_t result = display->getRenderSurface()->prepareFrame(
2454 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002455 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002456 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002457}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002458
Lloyd Pique32cbe282018-10-19 13:09:22 -07002459void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002460 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002461 ALOGV("doComposition");
2462
Lloyd Pique32cbe282018-10-19 13:09:22 -07002463 auto display = displayDevice->getCompositionDisplay();
2464 const auto& displayState = display->getState();
2465
2466 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002467 // transform the dirty region into this screen's coordinate space
Alec Mouri0f714832018-11-12 15:31:06 -08002468 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002469
David Sodmanfa9b2af2017-12-24 13:28:59 -08002470 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002471 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002472
Lloyd Pique32cbe282018-10-19 13:09:22 -07002473 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002474 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002475 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002476 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002477}
2478
David Sodmanfa9b2af2017-12-24 13:28:59 -08002479void SurfaceFlinger::postFrame()
2480{
2481 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002482 const auto display = getDefaultDisplayDeviceLocked();
2483 if (display && getHwComposer().isConnected(*display->getId())) {
2484 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002485 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2486 logFrameStats();
2487 }
2488 }
2489}
2490
Lloyd Pique32cbe282018-10-19 13:09:22 -07002491void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002492 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002493 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002494
Lloyd Pique32cbe282018-10-19 13:09:22 -07002495 auto display = displayDevice->getCompositionDisplay();
2496 const auto& displayState = display->getState();
2497 const auto displayId = display->getId();
2498
David Sodmanfa9b2af2017-12-24 13:28:59 -08002499 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002500
Lloyd Pique32cbe282018-10-19 13:09:22 -07002501 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002502 if (displayId) {
2503 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002504 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002505 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002506 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002507 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002508
Chia-I Wu7b549592017-11-15 09:14:57 -08002509 // The layer buffer from the previous frame (if any) is released
2510 // by HWC only when the release fence from this frame (if any) is
2511 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002512 if (displayId && layer->hasHwcLayer(*displayId)) {
2513 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2514 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002515 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002516
2517 // If the layer was client composited in the previous frame, we
2518 // need to merge with the previous client target acquire fence.
2519 // Since we do not track that, always merge with the current
2520 // client target acquire fence when it is available, even though
2521 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002522 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002523 releaseFence =
2524 Fence::merge("LayerRelease", releaseFence,
2525 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002526 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002527
David Sodman15094112018-10-11 09:39:37 -07002528 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002529 }
Chia-I Wu83806892017-11-16 10:50:20 -08002530
2531 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002532 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002533 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002534 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002535 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002536 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002537 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002538 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002539 }
2540 }
2541
Dominik Laskowski075d3172018-05-24 15:50:06 -07002542 if (displayId) {
2543 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002544 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002545 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002546}
2547
Mathias Agopian87baae12012-07-31 12:38:26 -07002548void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002549{
Mathias Agopian841cde52012-03-01 15:44:37 -08002550 ATRACE_CALL();
2551
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002552 // here we keep a copy of the drawing state (that is the state that's
2553 // going to be overwritten by handleTransactionLocked()) outside of
2554 // mStateLock so that the side-effects of the State assignment
2555 // don't happen with mStateLock held (which can cause deadlocks).
2556 State drawingState(mDrawingState);
2557
Mathias Agopianca4d3602011-05-19 15:38:14 -07002558 Mutex::Autolock _l(mStateLock);
2559 const nsecs_t now = systemTime();
2560 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002561
Mathias Agopianca4d3602011-05-19 15:38:14 -07002562 // Here we're guaranteed that some transaction flags are set
2563 // so we can call handleTransactionLocked() unconditionally.
2564 // We call getTransactionFlags(), which will also clear the flags,
2565 // with mStateLock held to guarantee that mCurrentState won't change
2566 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002567
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002568 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002569 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002570 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002571
Mathias Agopianca4d3602011-05-19 15:38:14 -07002572 mLastTransactionTime = systemTime() - now;
2573 mDebugInTransaction = 0;
2574 invalidateHwcGeometry();
2575 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002576}
2577
Lloyd Piqueba04e622017-12-14 17:11:26 -08002578void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2579 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002580 const std::optional<DisplayIdentificationInfo> info =
2581 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002582
Dominik Laskowski075d3172018-05-24 15:50:06 -07002583 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002584 continue;
2585 }
2586
Lloyd Piqueba04e622017-12-14 17:11:26 -08002587 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002588 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002589 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002590 mPhysicalDisplayTokens[info->id] = new BBinder();
2591 DisplayDeviceState state;
2592 state.displayId = info->id;
2593 state.isSecure = true; // All physical displays are currently considered secure.
2594 state.displayName = info->name;
2595 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2596 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002597 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002598 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002599 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002600
Dominik Laskowski075d3172018-05-24 15:50:06 -07002601 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2602 if (index >= 0) {
2603 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2604 mInterceptor->saveDisplayDeletion(state.sequenceId);
2605 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002606 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002607 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002608 }
2609
2610 processDisplayChangesLocked();
2611 }
2612
2613 mPendingHotplugEvents.clear();
2614}
2615
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002616void SurfaceFlinger::dispatchDisplayHotplugEvent(EventThread::DisplayType displayType,
2617 bool connected) {
2618 if (mUseScheduler) {
2619 mScheduler->hotplugReceived(mAppConnectionHandle, displayType, connected);
2620 mScheduler->hotplugReceived(mSfConnectionHandle, displayType, connected);
2621 } else {
2622 mEventThread->onHotplugReceived(displayType, connected);
2623 mSFEventThread->onHotplugReceived(displayType, connected);
2624 }
2625}
2626
Lloyd Pique99d3da52018-01-22 17:48:03 -08002627sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002628 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002629 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002630 const sp<IGraphicBufferProducer>& producer) {
2631 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002632 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002633 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002634 creationArgs.isSecure = state.isSecure;
2635 creationArgs.displaySurface = dispSurface;
2636 creationArgs.hasWideColorGamut = false;
2637 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002638
Dominik Laskowski075d3172018-05-24 15:50:06 -07002639 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2640 creationArgs.isPrimary = isInternalDisplay;
2641
2642 if (useColorManagement && displayId) {
2643 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002644 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002645 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002646 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002647 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002648
Dominik Laskowski7e045462018-05-30 13:02:02 -07002649 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002650 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002651 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002652 }
tangrobin6753a022018-08-10 10:58:54 +08002653 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002654
Dominik Laskowski075d3172018-05-24 15:50:06 -07002655 if (displayId) {
2656 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002657 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002658 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002659 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002660
Lloyd Pique90c115d2018-09-18 21:39:42 -07002661 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002662 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002663 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002664
Lloyd Pique99d3da52018-01-22 17:48:03 -08002665 // Make sure that composition can never be stalled by a virtual display
2666 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002667 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002668 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002669 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2670 }
2671
Dominik Laskowski075d3172018-05-24 15:50:06 -07002672 creationArgs.displayInstallOrientation =
2673 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002674
Lloyd Pique99d3da52018-01-22 17:48:03 -08002675 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002676 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002677
Lloyd Pique90c115d2018-09-18 21:39:42 -07002678 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002679
2680 if (maxFrameBufferAcquiredBuffers >= 3) {
2681 nativeWindowSurface->preallocateBuffers();
2682 }
2683
2684 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002685 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002686 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002687 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002688 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002689 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002690 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2691 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002692 if (!state.isVirtual()) {
2693 LOG_ALWAYS_FATAL_IF(!displayId);
2694 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002695 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002696
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002697 display->setLayerStack(state.layerStack);
2698 display->setProjection(state.orientation, state.viewport, state.frame);
2699 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002700
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002701 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002702}
2703
Lloyd Pique347200f2017-12-14 17:00:15 -08002704void SurfaceFlinger::processDisplayChangesLocked() {
2705 // here we take advantage of Vector's copy-on-write semantics to
2706 // improve performance by skipping the transaction entirely when
2707 // know that the lists are identical
2708 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2709 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2710 if (!curr.isIdenticalTo(draw)) {
2711 mVisibleRegionsDirty = true;
2712 const size_t cc = curr.size();
2713 size_t dc = draw.size();
2714
2715 // find the displays that were removed
2716 // (ie: in drawing state but not in current state)
2717 // also handle displays that changed
2718 // (ie: displays that are in both lists)
2719 for (size_t i = 0; i < dc;) {
2720 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2721 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002722 // Save display IDs before disconnecting.
2723 const auto internalDisplayId = getInternalDisplayId();
2724 const auto externalDisplayId = getExternalDisplayId();
2725
Lloyd Pique347200f2017-12-14 17:00:15 -08002726 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002727 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002728 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002729 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002730 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002731 dispatchDisplayHotplugEvent(EventThread::DisplayType::Primary, false);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002732 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002733 dispatchDisplayHotplugEvent(EventThread::DisplayType::External, false);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002734 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002735 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002736 } else {
2737 // this display is in both lists. see if something changed.
2738 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002739 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002740 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2741 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2742 if (state_binder != draw_binder) {
2743 // changing the surface is like destroying and
2744 // recreating the DisplayDevice, so we just remove it
2745 // from the drawing state, so that it get re-added
2746 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002747 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002748 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002749 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002750 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002751 mDrawingState.displays.removeItemsAt(i);
2752 dc--;
2753 // at this point we must loop to the next item
2754 continue;
2755 }
2756
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002757 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002758 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002759 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002760 }
2761 if ((state.orientation != draw[i].orientation) ||
2762 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002763 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002764 }
2765 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002766 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002767 }
2768 }
2769 }
2770 ++i;
2771 }
2772
2773 // find displays that were added
2774 // (ie: in current state but not in drawing state)
2775 for (size_t i = 0; i < cc; i++) {
2776 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2777 const DisplayDeviceState& state(curr[i]);
2778
Lloyd Pique542307f2018-10-19 13:24:08 -07002779 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002780 sp<IGraphicBufferProducer> producer;
2781 sp<IGraphicBufferProducer> bqProducer;
2782 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002783 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002784
Dominik Laskowski075d3172018-05-24 15:50:06 -07002785 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002786 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002787 // Virtual displays without a surface are dormant:
2788 // they have external state (layer stack, projection,
2789 // etc.) but no internal state (i.e. a DisplayDevice).
2790 if (state.surface != nullptr) {
2791 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002792 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002793 int width = 0;
2794 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2795 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2796 int height = 0;
2797 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2798 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2799 int intFormat = 0;
2800 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2801 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002802 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002803
Dominik Laskowski075d3172018-05-24 15:50:06 -07002804 displayId =
2805 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002806 }
2807
2808 // TODO: Plumb requested format back up to consumer
2809
2810 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002811 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002812 bqProducer, bqConsumer,
2813 state.displayName);
2814
2815 dispSurface = vds;
2816 producer = vds;
2817 }
2818 } else {
2819 ALOGE_IF(state.surface != nullptr,
2820 "adding a supported display, but rendering "
2821 "surface is provided (%p), ignoring it",
2822 state.surface.get());
2823
Dominik Laskowski075d3172018-05-24 15:50:06 -07002824 displayId = state.displayId;
2825 LOG_ALWAYS_FATAL_IF(!displayId);
2826 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002827 producer = bqProducer;
2828 }
2829
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002830 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002831 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002832 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002833 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002834 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002835 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002836 LOG_ALWAYS_FATAL_IF(!displayId);
2837
2838 if (displayId == getInternalDisplayId()) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002839 dispatchDisplayHotplugEvent(EventThread::DisplayType::Primary, true);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002840 } else if (displayId == getExternalDisplayId()) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002841 dispatchDisplayHotplugEvent(EventThread::DisplayType::External, true);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002842 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002843 }
2844 }
2845 }
2846 }
2847 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002848
2849 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002850}
2851
Mathias Agopian87baae12012-07-31 12:38:26 -07002852void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002853{
Dan Stoza7dde5992015-05-22 09:51:44 -07002854 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002855 mCurrentState.traverseInZOrder([](Layer* layer) {
2856 layer->notifyAvailableFrames();
2857 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002858
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002859 /*
2860 * Traversal of the children
2861 * (perform the transaction for each of them if needed)
2862 */
2863
Robert Carr720e5062018-07-30 17:45:14 -07002864 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002865 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002866 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002867 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002868 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002869
2870 const uint32_t flags = layer->doTransaction(0);
2871 if (flags & Layer::eVisibleRegion)
2872 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002873
2874 if (flags & Layer::eInputInfoChanged) {
2875 inputChanged = true;
2876 }
Robert Carr2047fae2016-11-28 14:09:09 -08002877 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002878 }
2879
2880 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002881 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002882 */
2883
Mathias Agopiane57f2922012-08-09 16:29:12 -07002884 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002885 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002886 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002887 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002888
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002889 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002890 // The transform hint might have changed for some layers
2891 // (either because a display has changed, or because a layer
2892 // as changed).
2893 //
2894 // Walk through all the layers in currentLayers,
2895 // and update their transform hint.
2896 //
2897 // If a layer is visible only on a single display, then that
2898 // display is used to calculate the hint, otherwise we use the
2899 // default display.
2900 //
2901 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2902 // the hint is set before we acquire a buffer from the surface texture.
2903 //
2904 // NOTE: layer transactions have taken place already, so we use their
2905 // drawing state. However, SurfaceFlinger's own transaction has not
2906 // happened yet, so we must use the current state layer list
2907 // (soon to become the drawing state list).
2908 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002909 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002910 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002911 bool first = true;
2912 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002913 // NOTE: we rely on the fact that layers are sorted by
2914 // layerStack first (so we don't have to traverse the list
2915 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002916 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002917 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002918 currentlayerStack = layerStack;
2919 // figure out if this layerstack is mirrored
2920 // (more than one display) if so, pick the default display,
2921 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002922 hintDisplay = nullptr;
2923 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002924 if (display->getCompositionDisplay()
2925 ->belongsInOutput(layer->getLayerStack(),
2926 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002927 if (hintDisplay) {
2928 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002929 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002930 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002931 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002932 }
2933 }
2934 }
2935 }
Chet Haase91d25932013-04-11 15:24:55 -07002936
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002937 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002938 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2939 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002940
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002941 // could be null when this layer is using a layerStack
2942 // that is not visible on any display. Also can occur at
2943 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002944 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002945 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002946
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002947 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002948 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002949 if (hintDisplay) {
2950 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002951 }
Robert Carr2047fae2016-11-28 14:09:09 -08002952
2953 first = false;
2954 });
Mathias Agopian84300952012-11-21 16:02:13 -08002955 }
2956
2957
Mathias Agopian3559b072012-08-15 13:46:03 -07002958 /*
2959 * Perform our own transaction if needed
2960 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002961
2962 if (mLayersAdded) {
2963 mLayersAdded = false;
2964 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002965 mVisibleRegionsDirty = true;
2966 }
2967
2968 // some layers might have been removed, so
2969 // we need to update the regions they're exposing.
2970 if (mLayersRemoved) {
2971 mLayersRemoved = false;
2972 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002973 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002974 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002975 // this layer is not visible anymore
2976 // TODO: we could traverse the tree from front to back and
2977 // compute the actual visible region
2978 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002979 Region visibleReg;
2980 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002981 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002982 }
Robert Carr2047fae2016-11-28 14:09:09 -08002983 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002984 }
2985
2986 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002987
Vishnu Nairde19f852018-12-18 16:11:53 -08002988 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002989 updateInputWindows();
2990 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002991 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002992
Riley Andrews03414a12014-07-01 14:22:59 -07002993 updateCursorAsync();
2994}
2995
Robert Carr720e5062018-07-30 17:45:14 -07002996void SurfaceFlinger::updateInputWindows() {
2997 ATRACE_CALL();
2998
Vishnu Nairde19f852018-12-18 16:11:53 -08002999 if (mInputFlinger == nullptr) {
3000 return;
3001 }
3002
Robert Carr720e5062018-07-30 17:45:14 -07003003 Vector<InputWindowInfo> inputHandles;
3004
3005 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
3006 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08003007 // When calculating the screen bounds we ignore the transparent region since it may
3008 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08003009 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07003010 }
3011 });
3012 mInputFlinger->setInputWindows(inputHandles);
3013}
3014
chaviwfbe5d9c2018-12-26 12:23:37 -08003015void SurfaceFlinger::executeInputWindowCommands() {
3016 if (!mInputFlinger) {
3017 return;
3018 }
3019
3020 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3021 if (transferTouchFocusCommand.fromToken != nullptr &&
3022 transferTouchFocusCommand.toToken != nullptr &&
3023 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3024 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3025 transferTouchFocusCommand.toToken);
3026 }
3027 }
3028
3029 mInputWindowCommands.clear();
3030}
3031
Riley Andrews03414a12014-07-01 14:22:59 -07003032void SurfaceFlinger::updateCursorAsync()
3033{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003034 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003035 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003036 continue;
3037 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003038
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003039 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3040 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003041 }
3042 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003043}
3044
chaviw61626f22018-11-15 16:26:27 -08003045void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3046 if (layer->hasReadyFrame()) {
3047 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3048 if (layer->shouldPresentNow(expectedPresentTime)) {
3049 bool ignored = false;
3050 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3051 }
3052 }
3053 layer->releasePendingBuffer(systemTime());
3054}
3055
Mathias Agopian4fec8732012-06-29 14:12:52 -07003056void SurfaceFlinger::commitTransaction()
3057{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003058 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003059 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003060 for (const auto& l : mLayersPendingRemoval) {
3061 recordBufferingStats(l->getName().string(),
3062 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003063
3064 // We need to release the HWC layers when the Layer is removed
3065 // from the current state otherwise the HWC layer just continues
3066 // showing at its last configured state until we eventually
3067 // abandon the buffer queue.
3068 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003069 l->destroyHwcLayersForAllDisplays();
3070 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003071 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003072 }
3073 mLayersPendingRemoval.clear();
3074 }
3075
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003076 // If this transaction is part of a window animation then the next frame
3077 // we composite should be considered an animation as well.
3078 mAnimCompositionPending = mAnimTransactionPending;
3079
Mathias Agopian4fec8732012-06-29 14:12:52 -07003080 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003081 // clear the "changed" flags in current state
3082 mCurrentState.colorMatrixChanged = false;
3083
Robert Carr1f0a16a2016-10-24 16:27:39 -07003084 mDrawingState.traverseInZOrder([](Layer* layer) {
3085 layer->commitChildList();
3086 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003087 mTransactionPending = false;
3088 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003089 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003090}
3091
Lloyd Pique32cbe282018-10-19 13:09:22 -07003092void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003093 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003094 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003095 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003096
Lloyd Pique32cbe282018-10-19 13:09:22 -07003097 auto display = displayDevice->getCompositionDisplay();
3098
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003099 Region aboveOpaqueLayers;
3100 Region aboveCoveredLayers;
3101 Region dirty;
3102
Mathias Agopian87baae12012-07-31 12:38:26 -07003103 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003104
Robert Carr2047fae2016-11-28 14:09:09 -08003105 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003106 // start with the whole surface at its current location
3107 const Layer::State& s(layer->getDrawingState());
3108
Jesse Hall01e29052013-02-19 16:13:35 -08003109 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003110 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003111 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003112 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003113
Mathias Agopianab028732010-03-16 16:41:46 -07003114 /*
3115 * opaqueRegion: area of a surface that is fully opaque.
3116 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003117 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003118
3119 /*
3120 * visibleRegion: area of a surface that is visible on screen
3121 * and not fully transparent. This is essentially the layer's
3122 * footprint minus the opaque regions above it.
3123 * Areas covered by a translucent surface are considered visible.
3124 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003125 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003126
3127 /*
3128 * coveredRegion: area of a surface that is covered by all
3129 * visible regions above it (which includes the translucent areas).
3130 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003131 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003132
Jesse Halla8026d22012-09-25 13:25:04 -07003133 /*
3134 * transparentRegion: area of a surface that is hinted to be completely
3135 * transparent. This is only used to tell when the layer has no visible
3136 * non-transparent regions and can be removed from the layer list. It
3137 * does not affect the visibleRegion of this layer or any layers
3138 * beneath it. The hint may not be correct if apps don't respect the
3139 * SurfaceView restrictions (which, sadly, some don't).
3140 */
3141 Region transparentRegion;
3142
Mathias Agopianab028732010-03-16 16:41:46 -07003143
3144 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003145 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003146 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003147 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003148
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003149 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003150 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003151 if (!visibleRegion.isEmpty()) {
3152 // Remove the transparent area from the visible region
3153 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003154 if (tr.preserveRects()) {
3155 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003156 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003157 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003158 // transformation too complex, can't do the
3159 // transparent region optimization.
3160 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003161 }
Mathias Agopianab028732010-03-16 16:41:46 -07003162 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003163
Mathias Agopianab028732010-03-16 16:41:46 -07003164 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003165 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003166 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003167 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003168 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003169 // the opaque region is the layer's footprint
3170 opaqueRegion = visibleRegion;
3171 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003172 }
3173 }
3174
Robert Carre5f4f692018-01-12 13:12:28 -08003175 if (visibleRegion.isEmpty()) {
3176 layer->clearVisibilityRegions();
3177 return;
3178 }
3179
Mathias Agopianab028732010-03-16 16:41:46 -07003180 // Clip the covered region to the visible region
3181 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3182
3183 // Update aboveCoveredLayers for next (lower) layer
3184 aboveCoveredLayers.orSelf(visibleRegion);
3185
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003186 // subtract the opaque region covered by the layers above us
3187 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003188
3189 // compute this layer's dirty region
3190 if (layer->contentDirty) {
3191 // we need to invalidate the whole region
3192 dirty = visibleRegion;
3193 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003194 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003195 layer->contentDirty = false;
3196 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003197 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003198 * the exposed region consists of two components:
3199 * 1) what's VISIBLE now and was COVERED before
3200 * 2) what's EXPOSED now less what was EXPOSED before
3201 *
3202 * note that (1) is conservative, we start with the whole
3203 * visible region but only keep what used to be covered by
3204 * something -- which mean it may have been exposed.
3205 *
3206 * (2) handles areas that were not covered by anything but got
3207 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003208 */
Mathias Agopianab028732010-03-16 16:41:46 -07003209 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003210 const Region oldVisibleRegion = layer->visibleRegion;
3211 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003212 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3213 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003214 }
3215 dirty.subtractSelf(aboveOpaqueLayers);
3216
3217 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003218 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003219
Mathias Agopianab028732010-03-16 16:41:46 -07003220 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003221 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003222
Jesse Halla8026d22012-09-25 13:25:04 -07003223 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003224 layer->setVisibleRegion(visibleRegion);
3225 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003226 layer->setVisibleNonTransparentRegion(
3227 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003228 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003229
Mathias Agopian87baae12012-07-31 12:38:26 -07003230 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003231}
3232
Chia-I Wuab0c3192017-08-01 11:29:00 -07003233void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003234 for (const auto& [token, displayDevice] : mDisplays) {
3235 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003236 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003237 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003238 }
3239 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003240}
3241
Daniel Solomon42d04562019-01-20 21:03:19 -08003242void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3243 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3244 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3245 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3246 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3247 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3248 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3249 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3250 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3251 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3252 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3253 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3254 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3255}
3256
Dan Stoza6b9454d2014-11-07 16:00:59 -08003257bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003258{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003259 ALOGV("handlePageFlip");
3260
Brian Andersond6927fb2016-07-23 23:37:30 -07003261 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003262
Mathias Agopian4fec8732012-06-29 14:12:52 -07003263 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003264 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003265 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003266
3267 // Store the set of layers that need updates. This set must not change as
3268 // buffers are being latched, as this could result in a deadlock.
3269 // Example: Two producers share the same command stream and:
3270 // 1.) Layer 0 is latched
3271 // 2.) Layer 0 gets a new frame
3272 // 2.) Layer 1 gets a new frame
3273 // 3.) Layer 1 is latched.
3274 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3275 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003276 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003277 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003278 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003279 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3280 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003281 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003282 } else {
3283 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003284 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003285 } else {
3286 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003287 }
Robert Carr2047fae2016-11-28 14:09:09 -08003288 });
3289
Lloyd Piquef2c79392018-12-20 16:23:33 -08003290 if (!mLayersWithQueuedFrames.empty()) {
3291 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3292 // writes to Layer current state. See also b/119481871
3293 Mutex::Autolock lock(mStateLock);
3294
3295 for (auto& layer : mLayersWithQueuedFrames) {
3296 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3297 layer->useSurfaceDamage();
3298 invalidateLayerStack(layer, dirty);
3299 if (layer->isBufferLatched()) {
3300 newDataLatched = true;
3301 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003302 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003303 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003304
Alec Mouri86770e52018-09-24 22:40:58 +00003305 // Clear the renderengine fence here...
3306 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3307 // clear instead of sp::clear.
3308 getBE().flushFence = Fence::NO_FENCE;
3309
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003310 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003311
Vishnu Nairde19f852018-12-18 16:11:53 -08003312 if (visibleRegions) {
3313 // Update input window info if the layer receives its first buffer.
3314 updateInputWindows();
3315 }
3316
Dan Stoza6b9454d2014-11-07 16:00:59 -08003317 // If we will need to wake up at some time in the future to deal with a
3318 // queued frame that shouldn't be displayed during this vsync period, wake
3319 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003320 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003321 signalLayerUpdate();
3322 }
3323
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003324 // enter boot animation on first buffer latch
3325 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3326 ALOGI("Enter boot animation");
3327 mBootStage = BootStage::BOOTANIMATION;
3328 }
3329
Dan Stoza6b9454d2014-11-07 16:00:59 -08003330 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003331 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003332}
3333
Mathias Agopianad456f92011-01-13 17:53:01 -08003334void SurfaceFlinger::invalidateHwcGeometry()
3335{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003336 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003337}
3338
Lloyd Pique32cbe282018-10-19 13:09:22 -07003339void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003340 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003341 auto display = displayDevice->getCompositionDisplay();
3342
Dan Stoza71433162014-02-04 16:22:36 -08003343 // We only need to actually compose the display if:
3344 // 1) It is being handled by hardware composer, which may need this to
3345 // keep its virtual display state machine in sync, or
3346 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003347 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003348 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003349 return;
3350 }
3351
Dan Stoza9e56aa02015-11-02 13:00:03 -08003352 ALOGV("doDisplayComposition");
Alec Mouri0f714832018-11-12 15:31:06 -08003353 base::unique_fd readyFence;
3354 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003355
3356 // swap buffers (presentation)
Alec Mouri0f714832018-11-12 15:31:06 -08003357 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003358}
3359
Alec Mouri0f714832018-11-12 15:31:06 -08003360bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3361 const Region& debugRegion, base::unique_fd* readyFence) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003362 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003363
Lloyd Pique32cbe282018-10-19 13:09:22 -07003364 auto display = displayDevice->getCompositionDisplay();
3365 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003366 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003367
3368 const Region bounds(displayState.bounds);
3369 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003370 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003371 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003372
Peiyong Lind3788632018-09-18 16:01:31 -07003373 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003374 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003375
Alec Mouri0f714832018-11-12 15:31:06 -08003376 renderengine::DisplaySettings clientCompositionDisplay;
3377 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3378 sp<GraphicBuffer> buf;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003379
Dan Stoza9e56aa02015-11-02 13:00:03 -08003380 if (hasClientComposition) {
3381 ALOGV("hasClientComposition");
3382
Alec Mouri0f714832018-11-12 15:31:06 -08003383 buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003384
3385 if (buf == nullptr) {
3386 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3387 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003388 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003389 return false;
3390 }
3391
Alec Mouri0f714832018-11-12 15:31:06 -08003392 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3393 clientCompositionDisplay.clip = displayState.scissor;
3394 const ui::Transform& displayTransform = displayState.transform;
3395 mat4 m;
3396 m[0][0] = displayTransform[0][0];
3397 m[0][1] = displayTransform[0][1];
3398 m[0][3] = displayTransform[0][2];
3399 m[1][0] = displayTransform[1][0];
3400 m[1][1] = displayTransform[1][1];
3401 m[1][3] = displayTransform[1][2];
3402 m[3][0] = displayTransform[2][0];
3403 m[3][1] = displayTransform[2][1];
3404 m[3][3] = displayTransform[2][2];
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003405
Alec Mouri0f714832018-11-12 15:31:06 -08003406 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003407
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003408 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003409 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003410 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003411 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003412 }
Alec Mouri0f714832018-11-12 15:31:06 -08003413 clientCompositionDisplay.outputDataspace = outputDataspace;
3414 clientCompositionDisplay.maxLuminance =
3415 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003416
Lloyd Pique441d5042018-10-18 16:49:51 -07003417 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003418 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003419 getHwComposer()
3420 .hasDisplayCapability(displayId,
3421 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003422
Peiyong Lind3788632018-09-18 16:01:31 -07003423 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003424 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3425 if (applyColorMatrix) {
Alec Mouri0f714832018-11-12 15:31:06 -08003426 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003427 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003428 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003429
Mathias Agopian85d751c2012-08-29 16:59:24 -07003430 /*
3431 * and then, render the layers targeted at the framebuffer
3432 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003433
Dan Stoza9e56aa02015-11-02 13:00:03 -08003434 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003435 bool firstLayer = true;
Alec Mouri0f714832018-11-12 15:31:06 -08003436 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003437 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mouri0f714832018-11-12 15:31:06 -08003438 const Region viewportRegion(displayState.viewport);
3439 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003440 ALOGV("Layer: %s", layer->getName().string());
3441 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003442 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003443 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003444 case HWC2::Composition::Cursor:
3445 case HWC2::Composition::Device:
3446 case HWC2::Composition::Sideband:
3447 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003448 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003449 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003450 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003451 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003452 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003453 // never clear the very first layer since we're
3454 // guaranteed the FB is already cleared
Alec Mouri0f714832018-11-12 15:31:06 -08003455 renderengine::LayerSettings layerSettings;
3456 Region dummyRegion;
3457 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3458 layerSettings);
3459
3460 if (prepared) {
3461 layerSettings.source.buffer.buffer = nullptr;
3462 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3463 layerSettings.alpha = half(0.0);
3464 layerSettings.disableBlending = true;
3465 clientCompositionLayers.push_back(layerSettings);
3466 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003467 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003468 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003469 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003470 case HWC2::Composition::Client: {
Alec Mouri0f714832018-11-12 15:31:06 -08003471 renderengine::LayerSettings layerSettings;
3472 bool prepared =
3473 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3474 if (prepared) {
3475 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003476 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003477 break;
3478 }
3479 default:
3480 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003481 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003482 } else {
3483 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003484 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003485 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003486 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003487
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003488 if (hasClientComposition) {
Alec Mouri0f714832018-11-12 15:31:06 -08003489 clientCompositionDisplay.clearRegion = clearRegion;
3490 if (!debugRegion.isEmpty()) {
3491 Region::const_iterator it = debugRegion.begin();
3492 Region::const_iterator end = debugRegion.end();
3493 while (it != end) {
3494 const Rect& rect = *it++;
3495 renderengine::LayerSettings layerSettings;
3496 layerSettings.source.buffer.buffer = nullptr;
3497 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3498 layerSettings.geometry.boundaries = rect.toFloatRect();
3499 layerSettings.alpha = half(1.0);
3500 clientCompositionLayers.push_back(layerSettings);
3501 }
3502 }
3503 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
3504 buf->getNativeBuffer(), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003505 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003506 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003507}
3508
Chia-I Wu28e3a252018-09-07 12:05:02 -07003509void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003510 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003511 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003512}
3513
Dan Stoza7d89d062015-04-30 13:29:25 -07003514status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003515 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003516 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003517 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003518 const sp<Layer>& parent,
3519 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003520{
Dan Stoza7d89d062015-04-30 13:29:25 -07003521 // add this layer to the current state list
3522 {
3523 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003524 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003525 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3526 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003527 return NO_MEMORY;
3528 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003529 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003530 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003531 } else if (parent == nullptr) {
3532 lbc->onRemovedFromCurrentState();
3533 } else if (parent->isRemovedFromCurrentState()) {
3534 parent->addChild(lbc);
3535 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003536 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003537 parent->addChild(lbc);
3538 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003539
Yiwei Zhang243b3782018-05-15 17:40:04 -07003540 if (gbc != nullptr) {
3541 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3542 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3543 mMaxGraphicBufferProducerListSize,
3544 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3545 mGraphicBufferProducerList.size(),
3546 mMaxGraphicBufferProducerListSize, mNumLayers);
3547 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003548 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003549 }
3550
Mathias Agopian96f08192010-06-02 23:28:45 -07003551 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003552 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003553
Dan Stoza7d89d062015-04-30 13:29:25 -07003554 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003555}
3556
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003557uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003558 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003559}
3560
Mathias Agopian3f844832013-08-07 21:24:32 -07003561uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003562 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003563}
3564
Mathias Agopian3f844832013-08-07 21:24:32 -07003565uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003566 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003567}
3568
3569uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003570 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003571 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003572 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003573 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003574 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003575 }
3576 return old;
3577}
3578
Marissa Wall713b63f2018-10-17 15:42:43 -07003579bool SurfaceFlinger::flushTransactionQueues() {
3580 Mutex::Autolock _l(mStateLock);
3581 auto it = mTransactionQueues.begin();
3582 while (it != mTransactionQueues.end()) {
3583 auto& [applyToken, transactionQueue] = *it;
3584
3585 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003586 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3587 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003588 break;
3589 }
chaviw273171b2018-12-26 11:46:30 -08003590 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003591 transactionQueue.pop();
3592 }
3593
3594 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3595 }
3596 return mTransactionQueues.empty();
3597}
3598
chaviwca27f252018-02-06 16:46:39 -08003599bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3600 for (const ComposerState& state : states) {
3601 // Here we need to check that the interface we're given is indeed
3602 // one of our own. A malicious client could give us a nullptr
3603 // IInterface, or one of its own or even one of our own but a
3604 // different type. All these situations would cause us to crash.
3605 if (state.client == nullptr) {
3606 return true;
3607 }
3608
3609 sp<IBinder> binder = IInterface::asBinder(state.client);
3610 if (binder == nullptr) {
3611 return true;
3612 }
3613
3614 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3615 return true;
3616 }
3617 }
3618 return false;
3619}
3620
Marissa Wall17b4e452018-12-26 16:32:34 -08003621bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3622 const Vector<ComposerState>& states) {
3623 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3624 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3625 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3626 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3627 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3628 return false;
3629 }
3630
Marissa Wall713b63f2018-10-17 15:42:43 -07003631 for (const ComposerState& state : states) {
3632 const layer_state_t& s = state.state;
3633 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3634 continue;
3635 }
3636 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003637 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003638 }
3639 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003640 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003641}
3642
3643void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3644 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003645 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003646 const InputWindowCommands& inputWindowCommands,
3647 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003648 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003649 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003650
chaviwca27f252018-02-06 16:46:39 -08003651 if (containsAnyInvalidClientState(states)) {
3652 return;
3653 }
3654
Marissa Wall713b63f2018-10-17 15:42:43 -07003655 // If its TransactionQueue already has a pending TransactionState or if it is pending
3656 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003657 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3658 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003659 setTransactionFlags(eTransactionNeeded);
3660 return;
3661 }
3662
chaviw273171b2018-12-26 11:46:30 -08003663 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003664}
3665
3666void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003667 const Vector<DisplayState>& displays, uint32_t flags,
3668 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003669 uint32_t transactionFlags = 0;
3670
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003671 if (flags & eAnimation) {
3672 // For window updates that are part of an animation we must wait for
3673 // previous animation "frames" to be handled.
3674 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003675 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003676 if (CC_UNLIKELY(err != NO_ERROR)) {
3677 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003678 // caller after a few seconds.
3679 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3680 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003681 mAnimTransactionPending = false;
3682 break;
3683 }
3684 }
3685 }
3686
chaviwca27f252018-02-06 16:46:39 -08003687 for (const DisplayState& display : displays) {
3688 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003689 }
3690
Marissa Walle2ffb422018-10-12 11:33:52 -07003691 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003692 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003693 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003694 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003695 // If the state doesn't require a traversal and there are callbacks, send them now
3696 if (!(clientStateFlags & eTraversalNeeded)) {
3697 mTransactionCompletedThread.sendCallbacks();
3698 }
3699 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003700
chaviw273171b2018-12-26 11:46:30 -08003701 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3702
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003703 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3704 // anyway. This can be used as a flush mechanism for previous async transactions.
3705 // Empty animation transaction can be used to simulate back-pressure, so also force a
3706 // transaction for empty animation transactions.
3707 if (transactionFlags == 0 &&
3708 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003709 transactionFlags = eTransactionNeeded;
3710 }
3711
Mathias Agopian386aa982011-11-07 21:58:03 -08003712 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003713 if (mInterceptor->isEnabled()) {
3714 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003715 }
Irvel468051e2016-06-13 16:44:44 -07003716
Mathias Agopian386aa982011-11-07 21:58:03 -08003717 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003718 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3719 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003720 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003721
3722 // if this is a synchronous transaction, wait for it to take effect
3723 // before returning.
3724 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003725 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003726 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003727 if (flags & eAnimation) {
3728 mAnimTransactionPending = true;
3729 }
3730 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003731 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3732 if (CC_UNLIKELY(err != NO_ERROR)) {
3733 // just in case something goes wrong in SF, return to the
3734 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003735 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3736 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003737 break;
3738 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003739 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003740 }
3741}
3742
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003743uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3744 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3745 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003746
Mathias Agopiane57f2922012-08-09 16:29:12 -07003747 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003748 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3749
3750 const uint32_t what = s.what;
3751 if (what & DisplayState::eSurfaceChanged) {
3752 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3753 state.surface = s.surface;
3754 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003755 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003756 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003757 if (what & DisplayState::eLayerStackChanged) {
3758 if (state.layerStack != s.layerStack) {
3759 state.layerStack = s.layerStack;
3760 flags |= eDisplayTransactionNeeded;
3761 }
3762 }
3763 if (what & DisplayState::eDisplayProjectionChanged) {
3764 if (state.orientation != s.orientation) {
3765 state.orientation = s.orientation;
3766 flags |= eDisplayTransactionNeeded;
3767 }
3768 if (state.frame != s.frame) {
3769 state.frame = s.frame;
3770 flags |= eDisplayTransactionNeeded;
3771 }
3772 if (state.viewport != s.viewport) {
3773 state.viewport = s.viewport;
3774 flags |= eDisplayTransactionNeeded;
3775 }
3776 }
3777 if (what & DisplayState::eDisplaySizeChanged) {
3778 if (state.width != s.width) {
3779 state.width = s.width;
3780 flags |= eDisplayTransactionNeeded;
3781 }
3782 if (state.height != s.height) {
3783 state.height = s.height;
3784 flags |= eDisplayTransactionNeeded;
3785 }
3786 }
3787
Mathias Agopiane57f2922012-08-09 16:29:12 -07003788 return flags;
3789}
3790
Robert Carrd4ae7f32018-06-07 16:10:57 -07003791bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3792 IPCThreadState* ipc = IPCThreadState::self();
3793 const int pid = ipc->getCallingPid();
3794 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003795 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003796 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003797 return false;
3798 }
3799 return true;
3800}
3801
chaviwca27f252018-02-06 16:46:39 -08003802uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3803 const layer_state_t& s = composerState.state;
3804 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3805
Mathias Agopian13127d82013-03-05 17:47:11 -08003806 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003807 if (layer == nullptr) {
3808 return 0;
3809 }
3810
chaviw8b3871a2017-11-01 17:41:01 -07003811 uint32_t flags = 0;
3812
Garfield Tan8a3083e2018-12-03 13:21:07 -08003813 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003814 bool geometryAppliesWithResize =
3815 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003816
3817 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3818 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003819 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003820 layer->pushPendingState();
3821 }
3822
chaviw8b3871a2017-11-01 17:41:01 -07003823 if (what & layer_state_t::ePositionChanged) {
3824 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3825 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003826 }
chaviw8b3871a2017-11-01 17:41:01 -07003827 }
3828 if (what & layer_state_t::eLayerChanged) {
3829 // NOTE: index needs to be calculated before we update the state
3830 const auto& p = layer->getParent();
3831 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003832 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003833 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003834 mCurrentState.layersSortedByZ.removeAt(idx);
3835 mCurrentState.layersSortedByZ.add(layer);
3836 // we need traversal (state changed)
3837 // AND transaction (list changed)
3838 flags |= eTransactionNeeded|eTraversalNeeded;
3839 }
chaviw8b3871a2017-11-01 17:41:01 -07003840 } else {
3841 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003842 flags |= eTransactionNeeded|eTraversalNeeded;
3843 }
3844 }
chaviw8b3871a2017-11-01 17:41:01 -07003845 }
3846 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003847 // NOTE: index needs to be calculated before we update the state
3848 const auto& p = layer->getParent();
3849 if (p == nullptr) {
3850 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3851 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3852 mCurrentState.layersSortedByZ.removeAt(idx);
3853 mCurrentState.layersSortedByZ.add(layer);
3854 // we need traversal (state changed)
3855 // AND transaction (list changed)
3856 flags |= eTransactionNeeded|eTraversalNeeded;
3857 }
3858 } else {
3859 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3860 flags |= eTransactionNeeded|eTraversalNeeded;
3861 }
chaviw8b3871a2017-11-01 17:41:01 -07003862 }
3863 }
3864 if (what & layer_state_t::eSizeChanged) {
3865 if (layer->setSize(s.w, s.h)) {
3866 flags |= eTraversalNeeded;
3867 }
3868 }
3869 if (what & layer_state_t::eAlphaChanged) {
3870 if (layer->setAlpha(s.alpha))
3871 flags |= eTraversalNeeded;
3872 }
3873 if (what & layer_state_t::eColorChanged) {
3874 if (layer->setColor(s.color))
3875 flags |= eTraversalNeeded;
3876 }
Peiyong Lind3788632018-09-18 16:01:31 -07003877 if (what & layer_state_t::eColorTransformChanged) {
3878 if (layer->setColorTransform(s.colorTransform)) {
3879 flags |= eTraversalNeeded;
3880 }
3881 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003882 if (what & layer_state_t::eBackgroundColorChanged) {
3883 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3884 flags |= eTraversalNeeded;
3885 }
3886 }
chaviw8b3871a2017-11-01 17:41:01 -07003887 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003888 // TODO: b/109894387
3889 //
3890 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3891 // rotation. To see the problem observe that if we have a square parent, and a child
3892 // of the same size, then we rotate the child 45 degrees around it's center, the child
3893 // must now be cropped to a non rectangular 8 sided region.
3894 //
3895 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3896 // private API, and the WindowManager only uses rotation in one case, which is on a top
3897 // level layer in which cropping is not an issue.
3898 //
3899 // However given that abuse of rotation matrices could lead to surfaces extending outside
3900 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3901 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3902 // transformations.
3903 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003904 flags |= eTraversalNeeded;
3905 }
3906 if (what & layer_state_t::eTransparentRegionChanged) {
3907 if (layer->setTransparentRegionHint(s.transparentRegion))
3908 flags |= eTraversalNeeded;
3909 }
3910 if (what & layer_state_t::eFlagsChanged) {
3911 if (layer->setFlags(s.flags, s.mask))
3912 flags |= eTraversalNeeded;
3913 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003914 if (what & layer_state_t::eCropChanged_legacy) {
3915 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003916 flags |= eTraversalNeeded;
3917 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003918 if (what & layer_state_t::eCornerRadiusChanged) {
3919 if (layer->setCornerRadius(s.cornerRadius))
3920 flags |= eTraversalNeeded;
3921 }
chaviw8b3871a2017-11-01 17:41:01 -07003922 if (what & layer_state_t::eLayerStackChanged) {
3923 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3924 // We only allow setting layer stacks for top level layers,
3925 // everything else inherits layer stack from its parent.
3926 if (layer->hasParent()) {
3927 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3928 layer->getName().string());
3929 } else if (idx < 0) {
3930 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3931 "that also does not appear in the top level layer list. Something"
3932 " has gone wrong.", layer->getName().string());
3933 } else if (layer->setLayerStack(s.layerStack)) {
3934 mCurrentState.layersSortedByZ.removeAt(idx);
3935 mCurrentState.layersSortedByZ.add(layer);
3936 // we need traversal (state changed)
3937 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003938 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003939 }
3940 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003941 if (what & layer_state_t::eDeferTransaction_legacy) {
3942 if (s.barrierHandle_legacy != nullptr) {
3943 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3944 } else if (s.barrierGbp_legacy != nullptr) {
3945 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003946 if (authenticateSurfaceTextureLocked(gbp)) {
3947 const auto& otherLayer =
3948 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003949 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003950 } else {
3951 ALOGE("Attempt to defer transaction to to an"
3952 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003953 }
3954 }
chaviw8b3871a2017-11-01 17:41:01 -07003955 // We don't trigger a traversal here because if no other state is
3956 // changed, we don't want this to cause any more work
3957 }
3958 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003959 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003960 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003961 if (!hadParent) {
3962 mCurrentState.layersSortedByZ.remove(layer);
3963 }
chaviw8b3871a2017-11-01 17:41:01 -07003964 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003965 }
chaviw8b3871a2017-11-01 17:41:01 -07003966 }
3967 if (what & layer_state_t::eReparentChildren) {
3968 if (layer->reparentChildren(s.reparentHandle)) {
3969 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003970 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003971 }
chaviw8b3871a2017-11-01 17:41:01 -07003972 if (what & layer_state_t::eDetachChildren) {
3973 layer->detachChildren();
3974 }
3975 if (what & layer_state_t::eOverrideScalingModeChanged) {
3976 layer->setOverrideScalingMode(s.overrideScalingMode);
3977 // We don't trigger a traversal here because if no other state is
3978 // changed, we don't want this to cause any more work
3979 }
Marissa Wall61c58622018-07-18 10:12:20 -07003980 if (what & layer_state_t::eTransformChanged) {
3981 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3982 }
3983 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3984 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3985 flags |= eTraversalNeeded;
3986 }
3987 if (what & layer_state_t::eCropChanged) {
3988 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3989 }
Marissa Wall861616d2018-10-22 12:52:23 -07003990 if (what & layer_state_t::eFrameChanged) {
3991 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3992 }
Marissa Wall61c58622018-07-18 10:12:20 -07003993 if (what & layer_state_t::eBufferChanged) {
3994 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3995 }
3996 if (what & layer_state_t::eAcquireFenceChanged) {
3997 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3998 }
3999 if (what & layer_state_t::eDataspaceChanged) {
4000 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4001 }
4002 if (what & layer_state_t::eHdrMetadataChanged) {
4003 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4004 }
4005 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4006 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4007 }
4008 if (what & layer_state_t::eApiChanged) {
4009 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4010 }
4011 if (what & layer_state_t::eSidebandStreamChanged) {
4012 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4013 }
Robert Carr720e5062018-07-30 17:45:14 -07004014 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004015 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
4016 layer->setInputInfo(s.inputInfo);
4017 flags |= eTraversalNeeded;
4018 } else {
4019 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4020 }
Robert Carr720e5062018-07-30 17:45:14 -07004021 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004022 if (what & layer_state_t::eMetadataChanged) {
4023 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4024 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004025 std::vector<sp<CallbackHandle>> callbackHandles;
4026 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
4027 mTransactionCompletedThread.run();
4028 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
4029 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4030 }
4031 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004032 if (what & layer_state_t::eCachedBufferChanged) {
4033 sp<GraphicBuffer> buffer =
4034 mBufferStateLayerCache.get(s.cachedBuffer.token, s.cachedBuffer.bufferId);
4035 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4036 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004037 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4038 // Do not put anything that updates layer state or modifies flags after
4039 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004040 return flags;
4041}
4042
chaviw273171b2018-12-26 11:46:30 -08004043uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4044 uint32_t flags = 0;
4045 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4046 flags |= eTraversalNeeded;
4047 }
4048
4049 mInputWindowCommands.merge(inputWindowCommands);
4050 return flags;
4051}
4052
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004053status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4054 uint32_t h, PixelFormat format, uint32_t flags,
4055 LayerMetadata metadata, sp<IBinder>* handle,
4056 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004057 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004058 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004059 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004060 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004061 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004062
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004063 status_t result = NO_ERROR;
4064
4065 sp<Layer> layer;
4066
Cody Northropbc755282017-03-31 12:00:08 -06004067 String8 uniqueName = getUniqueLayerName(name);
4068
Mathias Agopian3165cc22012-08-08 19:42:09 -07004069 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004070 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004071 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4072 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004073
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004074 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004075 case ISurfaceComposerClient::eFXSurfaceBufferState:
4076 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4077 break;
chaviw13fdc492017-06-27 12:40:18 -07004078 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004079 // check if buffer size is set for color layer.
4080 if (w > 0 || h > 0) {
4081 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4082 int(w), int(h));
4083 return BAD_VALUE;
4084 }
4085
chaviw13fdc492017-06-27 12:40:18 -07004086 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004087 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004088 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004089 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004090 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004091 // check if buffer size is set for container layer.
4092 if (w > 0 || h > 0) {
4093 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4094 int(w), int(h));
4095 return BAD_VALUE;
4096 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004097 result = createContainerLayer(client,
4098 uniqueName, w, h, flags,
4099 handle, &layer);
4100 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004101 default:
4102 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004103 break;
4104 }
4105
Dan Stoza7d89d062015-04-30 13:29:25 -07004106 if (result != NO_ERROR) {
4107 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004108 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004109
Chia-I Wuab0c3192017-08-01 11:29:00 -07004110 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4111 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004112 if (metadata.has(METADATA_WINDOW_TYPE)) {
4113 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4114 if (windowType == 441731) {
4115 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4116 layer->setPrimaryDisplayOnly();
4117 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004118 }
4119
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004120 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004121
Robert Carrb89ea9d2018-12-10 13:01:14 -08004122 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4123 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4124 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004125 if (result != NO_ERROR) {
4126 return result;
4127 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004128 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004129
4130 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004131 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004132}
4133
Cody Northropbc755282017-03-31 12:00:08 -06004134String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4135{
4136 bool matchFound = true;
4137 uint32_t dupeCounter = 0;
4138
4139 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4140 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4141
Dan Stoza436ccf32018-06-21 12:10:12 -07004142 // Grab the state lock since we're accessing mCurrentState
4143 Mutex::Autolock lock(mStateLock);
4144
Cody Northropbc755282017-03-31 12:00:08 -06004145 // Loop over layers until we're sure there is no matching name
4146 while (matchFound) {
4147 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004148 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004149 if (layer->getName() == uniqueName) {
4150 matchFound = true;
4151 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4152 }
4153 });
4154 }
4155
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004156 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4157 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004158
4159 return uniqueName;
4160}
4161
Marissa Wallfd668622018-05-10 10:21:13 -07004162status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4163 uint32_t w, uint32_t h, uint32_t flags,
4164 PixelFormat& format, sp<IBinder>* handle,
4165 sp<IGraphicBufferProducer>* gbp,
4166 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004167 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004168 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004169 case PIXEL_FORMAT_TRANSPARENT:
4170 case PIXEL_FORMAT_TRANSLUCENT:
4171 format = PIXEL_FORMAT_RGBA_8888;
4172 break;
4173 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004174 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004175 break;
4176 }
4177
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004178 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004179 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004180 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004181 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004182 *handle = layer->getHandle();
4183 *gbp = layer->getProducer();
4184 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004185 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004186
Marissa Wallfd668622018-05-10 10:21:13 -07004187 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004188 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004189}
4190
Marissa Wall61c58622018-07-18 10:12:20 -07004191status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4192 uint32_t w, uint32_t h, uint32_t flags,
4193 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004194 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004195 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004196 *handle = layer->getHandle();
4197 *outLayer = layer;
4198
4199 return NO_ERROR;
4200}
4201
chaviw13fdc492017-06-27 12:40:18 -07004202status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004203 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004204 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004205{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004206 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004207 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004208 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004209}
4210
Robert Carr6b3f6c52018-08-13 13:05:17 -07004211status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4212 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4213 sp<IBinder>* handle, sp<Layer>* outLayer)
4214{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004215 *outLayer =
4216 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004217 *handle = (*outLayer)->getHandle();
4218 return NO_ERROR;
4219}
4220
4221
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004222void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004223 mLayersPendingRemoval.add(layer);
4224 mLayersRemoved = true;
4225 setTransactionFlags(eTransactionNeeded);
4226}
4227
Robert Carr695d5282018-12-18 15:27:58 -08004228void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004229{
Robert Carr2e102c92018-10-23 12:11:15 -07004230 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004231 // If a layer has a parent, we allow it to out-live it's handle
4232 // with the idea that the parent holds a reference and will eventually
4233 // be cleaned up. However no one cleans up the top-level so we do so
4234 // here.
4235 if (layer->getParent() == nullptr) {
4236 mCurrentState.layersSortedByZ.remove(layer);
4237 }
4238 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004239 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004240}
4241
Mathias Agopianb60314a2012-04-10 22:09:54 -07004242// ---------------------------------------------------------------------------
4243
Andy McFadden13a082e2012-08-24 10:16:42 -07004244void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004245 const auto display = getDefaultDisplayDeviceLocked();
4246 if (!display) return;
4247
4248 const sp<IBinder> token = display->getDisplayToken().promote();
4249 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004250
Jesse Hall01e29052013-02-19 16:13:35 -08004251 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004252 Vector<ComposerState> state;
4253 Vector<DisplayState> displays;
4254 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004255 d.what = DisplayState::eDisplayProjectionChanged |
4256 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004257 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004258 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004259 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004260 d.frame.makeInvalid();
4261 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004262 d.width = 0;
4263 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004264 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004265 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004266
Dominik Laskowskie9774092018-12-11 10:04:24 -08004267 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004268
Dominik Laskowski83b88212018-12-11 13:34:06 -08004269 const nsecs_t vsyncPeriod = getVsyncPeriod();
4270 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004271
Brian Andersond0010582017-03-07 13:20:31 -08004272 // Use phase of 0 since phase is not known.
4273 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004274 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004275 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004276}
4277
4278void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004279 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004280 postMessageAsync(
4281 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004282}
4283
Dominik Laskowskie9774092018-12-11 10:04:24 -08004284void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004285 if (display->isVirtual()) {
4286 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004287 return;
4288 }
4289
Dominik Laskowski075d3172018-05-24 15:50:06 -07004290 const auto displayId = display->getId();
4291 LOG_ALWAYS_FATAL_IF(!displayId);
4292
Dominik Laskowski34157762018-10-31 13:07:19 -07004293 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004294
4295 int currentMode = display->getPowerMode();
4296 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004297 return;
4298 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004299
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004300 display->setPowerMode(mode);
4301
Lloyd Pique4dccc412018-01-22 17:21:36 -08004302 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004303 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004304 }
4305
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004306 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004307 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004308 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004309 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004310 if (mUseScheduler) {
4311 mScheduler->onScreenAcquired(mAppConnectionHandle);
4312 } else {
4313 mEventThread->onScreenAcquired();
4314 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004315 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004316 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004317
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004318 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004319 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004320 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004321
4322 struct sched_param param = {0};
4323 param.sched_priority = 1;
4324 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4325 ALOGW("Couldn't set SCHED_FIFO on display on");
4326 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004327 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004328 // Turn off the display
4329 struct sched_param param = {0};
4330 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4331 ALOGW("Couldn't set SCHED_OTHER on display off");
4332 }
4333
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004334 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004335 if (mUseScheduler) {
4336 mScheduler->disableHardwareVsync(true);
4337 } else {
4338 disableHardwareVsync(true); // also cancels any in-progress resync
4339 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004340 if (mUseScheduler) {
4341 mScheduler->onScreenReleased(mAppConnectionHandle);
4342 } else {
4343 mEventThread->onScreenReleased();
4344 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004345 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004346
Dominik Laskowski075d3172018-05-24 15:50:06 -07004347 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004348 mVisibleRegionsDirty = true;
4349 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004350 } else if (mode == HWC_POWER_MODE_DOZE ||
4351 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004352 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004353 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004354 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004355 if (mUseScheduler) {
4356 mScheduler->onScreenAcquired(mAppConnectionHandle);
4357 } else {
4358 mEventThread->onScreenAcquired();
4359 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004360 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004361 }
4362 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4363 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004364 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004365 if (mUseScheduler) {
4366 mScheduler->disableHardwareVsync(true);
4367 } else {
4368 disableHardwareVsync(true); // also cancels any in-progress resync
4369 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004370 if (mUseScheduler) {
4371 mScheduler->onScreenReleased(mAppConnectionHandle);
4372 } else {
4373 mEventThread->onScreenReleased();
4374 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004375 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004376 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004377 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004378 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004379 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004380 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004381
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004382 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004383 mTimeStats->setPowerMode(mode);
Ana Krulec4593b692019-01-11 22:07:25 -08004384 if (mUseScheduler && mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004385 // Update refresh rate stats.
4386 mRefreshRateStats->setPowerMode(mode);
4387 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004388 }
4389
Dominik Laskowski34157762018-10-31 13:07:19 -07004390 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004391}
4392
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004393void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004394 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004395 const auto display = getDisplayDevice(displayToken);
4396 if (!display) {
4397 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4398 displayToken.get());
4399 } else if (display->isVirtual()) {
4400 ALOGW("Attempt to set power mode %d for virtual display", mode);
4401 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004402 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004403 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004404 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004405}
4406
4407// ---------------------------------------------------------------------------
4408
Dominik Laskowskic2867142019-01-21 11:33:38 -08004409status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4410 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004411 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004412
Mathias Agopianbd115332013-04-18 16:41:04 -07004413 IPCThreadState* ipc = IPCThreadState::self();
4414 const int pid = ipc->getCallingPid();
4415 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004416
Mathias Agopianbd115332013-04-18 16:41:04 -07004417 if ((uid != AID_SHELL) &&
4418 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004419 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4420 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004421 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004422 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004423 // (this would indicate SF is stuck, but we want to be able to
4424 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004425 status_t err = mStateLock.timedLock(s2ns(1));
4426 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004427 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004428 StringAppendF(&result,
4429 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4430 "(no locks held)\n",
4431 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004432 }
4433
Dominik Laskowskic2867142019-01-21 11:33:38 -08004434 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004435
Dominik Laskowskic2867142019-01-21 11:33:38 -08004436 static const std::unordered_map<std::string, Dumper> dumpers = {
4437 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4438 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4439 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
4440 {"--dispsync"s, dumper([this](std::string& s) { mPrimaryDispSync->dump(s); })},
4441 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4442 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
4443 {"--frame-composition"s, dumper(&SurfaceFlinger::dumpFrameCompositionInfo)},
4444 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4445 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4446 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4447 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4448 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4449 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004450 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004451 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4452 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004453
Dominik Laskowskic2867142019-01-21 11:33:38 -08004454 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004455
Dominik Laskowskic2867142019-01-21 11:33:38 -08004456 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4457 (it->second)(args, asProto, result);
4458 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004459 if (asProto) {
4460 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4461 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4462 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004463 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004464 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004465 }
4466
Mathias Agopian9795c422009-08-26 16:36:26 -07004467 if (locked) {
4468 mStateLock.unlock();
4469 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004470 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004471 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004472 return NO_ERROR;
4473}
4474
Dominik Laskowskic2867142019-01-21 11:33:38 -08004475void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004476 mCurrentState.traverseInZOrder(
4477 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004478}
4479
Dominik Laskowskic2867142019-01-21 11:33:38 -08004480void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004481 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004482
Dominik Laskowskic2867142019-01-21 11:33:38 -08004483 if (args.size() > 1) {
4484 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004485 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004486 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004487 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004488 }
Robert Carr2047fae2016-11-28 14:09:09 -08004489 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004490 } else {
4491 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004492 }
4493}
4494
Dominik Laskowskic2867142019-01-21 11:33:38 -08004495void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004496 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004497 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004498 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004499 }
Robert Carr2047fae2016-11-28 14:09:09 -08004500 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004501
Svetoslavd85084b2014-03-20 10:28:31 -07004502 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004503}
4504
Dominik Laskowskic2867142019-01-21 11:33:38 -08004505void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4506 mTimeStats->parseArgs(asProto, args, result);
4507}
4508
Jamie Gennis6547ff42013-07-16 20:12:42 -07004509// This should only be called from the main thread. Otherwise it would need
4510// the lock and should use mCurrentState rather than mDrawingState.
4511void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004512 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004513 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004514 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004515
4516 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4517}
4518
Yiwei Zhang5434a782018-12-05 18:06:32 -08004519void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004520 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004521
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004522 if (isLayerTripleBufferingDisabled())
4523 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004524
Yiwei Zhang5434a782018-12-05 18:06:32 -08004525 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4526 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4527 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4528 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4529 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4530 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004531 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004532}
4533
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004534void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004535 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004536 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004537 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004538 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004539
4540 StringAppendF(&result, "Scheduler: %s\n\n", mUseScheduler ? "enabled" : "disabled");
4541
4542 if (mUseScheduler) {
4543 mScheduler->dump(mAppConnectionHandle, result);
4544 } else {
4545 mEventThread->dump(result);
4546 }
4547}
4548
Yiwei Zhang5434a782018-12-05 18:06:32 -08004549void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4550 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004551 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4552 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004553 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004554 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004555 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004556 }
David Sodman4a36e932017-11-07 14:29:47 -08004557 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004558 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004559 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004560 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4561 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004562}
4563
Dan Stozae77c7662016-05-13 11:37:28 -07004564void SurfaceFlinger::recordBufferingStats(const char* layerName,
4565 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004566 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4567 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004568 for (const auto& segment : history) {
4569 if (!segment.usedThirdBuffer) {
4570 stats.twoBufferTime += segment.totalTime;
4571 }
4572 if (segment.occupancyAverage < 1.0f) {
4573 stats.doubleBufferedTime += segment.totalTime;
4574 } else if (segment.occupancyAverage < 2.0f) {
4575 stats.tripleBufferedTime += segment.totalTime;
4576 }
4577 ++stats.numSegments;
4578 stats.totalTime += segment.totalTime;
4579 }
4580}
4581
Yiwei Zhang5434a782018-12-05 18:06:32 -08004582void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4583 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004584
4585 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4586 const size_t count = currentLayers.size();
4587 for (size_t i=0 ; i<count ; i++) {
4588 currentLayers[i]->dumpFrameEvents(result);
4589 }
4590}
4591
Yiwei Zhang5434a782018-12-05 18:06:32 -08004592void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004593 result.append("Buffering stats:\n");
4594 result.append(" [Layer name] <Active time> <Two buffer> "
4595 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004596 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004597 typedef std::tuple<std::string, float, float, float> BufferTuple;
4598 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004599 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004600 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004601 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004602 if (stats.numSegments == 0) {
4603 continue;
4604 }
4605 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4606 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4607 stats.totalTime;
4608 float doubleBufferRatio = static_cast<float>(
4609 stats.doubleBufferedTime) / stats.totalTime;
4610 float tripleBufferRatio = static_cast<float>(
4611 stats.tripleBufferedTime) / stats.totalTime;
4612 sorted.insert({activeTime, {name, twoBufferRatio,
4613 doubleBufferRatio, tripleBufferRatio}});
4614 }
4615 for (const auto& sortedPair : sorted) {
4616 float activeTime = sortedPair.first;
4617 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004618 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4619 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004620 }
4621 result.append("\n");
4622}
4623
Yiwei Zhang5434a782018-12-05 18:06:32 -08004624void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004625 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004626 const auto displayId = display->getId();
4627 if (!displayId) {
4628 continue;
4629 }
4630 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004631 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004632 continue;
4633 }
4634
Yiwei Zhang5434a782018-12-05 18:06:32 -08004635 StringAppendF(&result,
4636 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4637 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004638 uint8_t port;
4639 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004640 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004641 result.append("no identification data\n");
4642 continue;
4643 }
4644
4645 if (!isEdid(data)) {
4646 result.append("unknown identification data: ");
4647 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004648 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004649 }
4650 result.append("\n");
4651 continue;
4652 }
4653
4654 const auto edid = parseEdid(data);
4655 if (!edid) {
4656 result.append("invalid EDID: ");
4657 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004658 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004659 }
4660 result.append("\n");
4661 continue;
4662 }
4663
Yiwei Zhang5434a782018-12-05 18:06:32 -08004664 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004665 result.append(edid->displayName.data(), edid->displayName.length());
4666 result.append("\"\n");
4667 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004668}
4669
Yiwei Zhang5434a782018-12-05 18:06:32 -08004670void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4671 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4672 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4673 StringAppendF(&result, "DisplayColorSetting: %s\n",
4674 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004675
4676 // TODO: print out if wide-color mode is active or not
4677
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004678 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004679 const auto displayId = display->getId();
4680 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004681 continue;
4682 }
4683
Yiwei Zhang5434a782018-12-05 18:06:32 -08004684 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004685 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004686 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004687 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004688 }
4689
Lloyd Pique32cbe282018-10-19 13:09:22 -07004690 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004691 StringAppendF(&result, " Current color mode: %s (%d)\n",
4692 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004693 }
4694 result.append("\n");
4695}
4696
Yiwei Zhang5434a782018-12-05 18:06:32 -08004697void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004698 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004699 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4700 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004701 continue;
4702 }
4703
Dominik Laskowski05275f12018-11-01 15:03:24 -07004704 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004705 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4706 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004707 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004708 compositionInfo.dump(result, nullptr);
4709 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004710 }
4711 }
David Sodman7e4ae112018-02-09 15:02:28 -08004712}
4713
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004714LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004715 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004716 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4717 const State& state = useDrawing ? mDrawingState : mCurrentState;
4718 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004719 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004720 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004721 });
4722
4723 return layersProto;
4724}
4725
Lloyd Pique32cbe282018-10-19 13:09:22 -07004726LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004727 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004728
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004729 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004730 resolution->set_w(displayDevice.getWidth());
4731 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004732
Lloyd Pique32cbe282018-10-19 13:09:22 -07004733 auto display = displayDevice.getCompositionDisplay();
4734 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004735
Lloyd Pique32cbe282018-10-19 13:09:22 -07004736 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4737 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4738 layersProto.set_global_transform(displayState.orientation);
4739
4740 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004741 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004742 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004743 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004744 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004745 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004746 }
4747 });
4748
4749 return layersProto;
4750}
4751
Dominik Laskowskic2867142019-01-21 11:33:38 -08004752void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4753 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004754 Colorizer colorizer(colorize);
4755
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004756 // figure out if we're stuck somewhere
4757 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004758 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004759 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4760
4761 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004762 * Dump library configuration.
4763 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004764
4765 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004766 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004767 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004768 appendSfConfigString(result);
4769 appendUiConfigString(result);
4770 appendGuiConfigString(result);
4771 result.append("\n");
4772
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004773 result.append("\nDisplay identification data:\n");
4774 dumpDisplayIdentificationData(result);
4775
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004776 result.append("\nWide-Color information:\n");
4777 dumpWideColorInfo(result);
4778
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004779 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004780 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004781 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004782 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004783 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004784
Andy McFadden41d67d72014-04-25 16:58:34 -07004785 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004786 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004787 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004788 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004789 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004790
Dan Stozab90cf072015-03-05 11:05:59 -08004791 dumpStaticScreenStats(result);
4792 result.append("\n");
4793
Yiwei Zhang5434a782018-12-05 18:06:32 -08004794 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004795
Dan Stozae77c7662016-05-13 11:37:28 -07004796 dumpBufferingStats(result);
4797
Andy McFadden4803b742012-09-24 19:07:20 -07004798 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004799 * Dump the visible layer list
4800 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004801 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004802 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4803 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4804 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004805 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004806
Chia-I Wu2f884132018-09-13 15:17:58 -07004807 {
4808 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4809 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004810 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004811 result.append("\n");
4812 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004813
David Sodman7e4ae112018-02-09 15:02:28 -08004814 result.append("\nFrame-Composition information:\n");
4815 dumpFrameCompositionInfo(result);
4816 result.append("\n");
4817
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004818 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004819 * Dump Display state
4820 */
4821
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004822 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004823 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004824 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004825 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004826 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004827 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004828 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004829
4830 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004831 * Dump SurfaceFlinger global state
4832 */
4833
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004834 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004835 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004836 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004837
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004838 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004839
Dominik Laskowski075d3172018-05-24 15:50:06 -07004840 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004841 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4842 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004843 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4844 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004845 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004846 StringAppendF(&result,
4847 " transaction-flags : %08x\n"
4848 " gpu_to_cpu_unsupported : %d\n",
4849 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004850
Dominik Laskowski075d3172018-05-24 15:50:06 -07004851 if (const auto displayId = getInternalDisplayId();
4852 displayId && getHwComposer().isConnected(*displayId)) {
4853 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004854 StringAppendF(&result,
4855 " refresh-rate : %f fps\n"
4856 " x-dpi : %f\n"
4857 " y-dpi : %f\n",
4858 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4859 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004860 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004861
Yiwei Zhang5434a782018-12-05 18:06:32 -08004862 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004863
Dan Stozae22aec72016-08-01 13:20:59 -07004864 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004865 * Tracing state
4866 */
4867 mTracing.dump(result);
4868 result.append("\n");
4869
4870 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004871 * HWC layer minidump
4872 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004873 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004874 const auto displayId = display->getId();
4875 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004876 continue;
4877 }
4878
Yiwei Zhang5434a782018-12-05 18:06:32 -08004879 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004880 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004881 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004882 result.append("\n");
4883 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004884
4885 /*
4886 * Dump HWComposer state
4887 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004888 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004889 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004890 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004891 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004892 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004893 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004894
4895 /*
4896 * Dump gralloc state
4897 */
4898 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4899 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004900
4901 /*
4902 * Dump VrFlinger state if in use.
4903 */
4904 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4905 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004906 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004907 result.append("\n");
4908 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004909
4910 /**
4911 * Scheduler dump state.
4912 */
4913 if (mUseScheduler) {
4914 result.append("\nScheduler state:\n");
4915 result.append(mScheduler->doDump() + "\n");
4916 result.append(mRefreshRateStats->doDump() + "\n");
4917 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004918}
4919
Dominik Laskowski075d3172018-05-24 15:50:06 -07004920const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004921 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004922 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004923 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004924 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004925 }
4926 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004927
Dominik Laskowski34157762018-10-31 13:07:19 -07004928 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004929 static const Vector<sp<Layer>> empty;
4930 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004931}
4932
Keun young Park63f165f2012-08-31 10:53:36 -07004933bool SurfaceFlinger::startDdmConnection()
4934{
4935 void* libddmconnection_dso =
4936 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4937 if (!libddmconnection_dso) {
4938 return false;
4939 }
4940 void (*DdmConnection_start)(const char* name);
4941 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004942 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004943 if (!DdmConnection_start) {
4944 dlclose(libddmconnection_dso);
4945 return false;
4946 }
4947 (*DdmConnection_start)(getServiceName());
4948 return true;
4949}
4950
Chia-I Wu28f320b2018-05-03 11:02:56 -07004951void SurfaceFlinger::updateColorMatrixLocked() {
4952 mat4 colorMatrix;
4953 if (mGlobalSaturationFactor != 1.0f) {
4954 // Rec.709 luma coefficients
4955 float3 luminance{0.213f, 0.715f, 0.072f};
4956 luminance *= 1.0f - mGlobalSaturationFactor;
4957 mat4 saturationMatrix = mat4(
4958 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4959 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4960 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4961 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4962 );
4963 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4964 } else {
4965 colorMatrix = mClientColorMatrix * mDaltonizer();
4966 }
4967
4968 if (mCurrentState.colorMatrix != colorMatrix) {
4969 mCurrentState.colorMatrix = colorMatrix;
4970 mCurrentState.colorMatrixChanged = true;
4971 setTransactionFlags(eTransactionNeeded);
4972 }
4973}
4974
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004975status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004976#pragma clang diagnostic push
4977#pragma clang diagnostic error "-Wswitch-enum"
4978 switch (static_cast<ISurfaceComposerTag>(code)) {
4979 // These methods should at minimum make sure that the client requested
4980 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004981 case BOOT_FINISHED:
4982 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004983 case CREATE_DISPLAY:
4984 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004985 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004986 case GET_ACTIVE_COLOR_MODE:
4987 case GET_ANIMATION_FRAME_STATS:
4988 case GET_HDR_CAPABILITIES:
4989 case SET_ACTIVE_CONFIG:
4990 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004991 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004992 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004993 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004994 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4995 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004996 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4997 IPCThreadState* ipc = IPCThreadState::self();
4998 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4999 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005000 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005001 }
Robert Carr1db73f62016-12-21 12:58:51 -08005002 return OK;
5003 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005004 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005005 IPCThreadState* ipc = IPCThreadState::self();
5006 const int pid = ipc->getCallingPid();
5007 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005008 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5009 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005010 return PERMISSION_DENIED;
5011 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005012 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005013 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005014 // Used by apps to hook Choreographer to SurfaceFlinger.
5015 case CREATE_DISPLAY_EVENT_CONNECTION:
5016 // The following calls are currently used by clients that do not
5017 // request necessary permissions. However, they do not expose any secret
5018 // information, so it is OK to pass them.
5019 case AUTHENTICATE_SURFACE:
5020 case GET_ACTIVE_CONFIG:
5021 case GET_BUILT_IN_DISPLAY:
5022 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005023 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005024 case GET_DISPLAY_CONFIGS:
5025 case GET_DISPLAY_STATS:
5026 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5027 // Calling setTransactionState is safe, because you need to have been
5028 // granted a reference to Client* and Handle* to do anything with it.
5029 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005030 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005031 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005032 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005033 case GET_PROTECTED_CONTENT_SUPPORT:
5034 case CACHE_BUFFER:
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08005035 case UNCACHE_BUFFER:
5036 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005037 return OK;
5038 }
5039 case CAPTURE_LAYERS:
5040 case CAPTURE_SCREEN: {
5041 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005042 IPCThreadState* ipc = IPCThreadState::self();
5043 const int pid = ipc->getCallingPid();
5044 const int uid = ipc->getCallingUid();
5045 if ((uid != AID_GRAPHICS) &&
5046 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5047 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5048 return PERMISSION_DENIED;
5049 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005050 return OK;
5051 }
5052 // The following codes are deprecated and should never be allowed to access SF.
5053 case CONNECT_DISPLAY_UNUSED:
5054 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5055 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5056 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005057 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005058 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005059
5060 // These codes are used for the IBinder protocol to either interrogate the recipient
5061 // side of the transaction for its canonical interface descriptor or to dump its state.
5062 // We let them pass by default.
5063 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5064 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5065 code == IBinder::SYSPROPS_TRANSACTION) {
5066 return OK;
5067 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005068 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005069 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005070 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005071 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5072 return OK;
5073 }
5074 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5075 return PERMISSION_DENIED;
5076#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005077}
5078
Ana Krulec13be8ad2018-08-21 02:43:56 +00005079status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5080 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005081 status_t credentialCheck = CheckTransactCodeCredentials(code);
5082 if (credentialCheck != OK) {
5083 return credentialCheck;
5084 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005085
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005086 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5087 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005088 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005089 IPCThreadState* ipc = IPCThreadState::self();
5090 const int uid = ipc->getCallingUid();
5091 if (CC_UNLIKELY(uid != AID_SYSTEM
5092 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005093 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005094 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005095 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005096 return PERMISSION_DENIED;
5097 }
5098 int n;
5099 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005100 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005101 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005102 return NO_ERROR;
5103 case 1002: // SHOW_UPDATES
5104 n = data.readInt32();
5105 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005106 invalidateHwcGeometry();
5107 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005108 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005109 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005110 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005111 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005112 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005113 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005114 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005115 setTransactionFlags(
5116 eTransactionNeeded|
5117 eDisplayTransactionNeeded|
5118 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005119 return NO_ERROR;
5120 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005121 case 1006:{ // send empty update
5122 signalRefresh();
5123 return NO_ERROR;
5124 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005125 case 1008: // toggle use of hw composer
5126 n = data.readInt32();
5127 mDebugDisableHWC = n ? 1 : 0;
5128 invalidateHwcGeometry();
5129 repaintEverything();
5130 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005131 case 1009: // toggle use of transform hint
5132 n = data.readInt32();
5133 mDebugDisableTransformHint = n ? 1 : 0;
5134 invalidateHwcGeometry();
5135 repaintEverything();
5136 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005137 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005138 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005139 reply->writeInt32(0);
5140 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005141 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005142 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005143 return NO_ERROR;
5144 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005145 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005146 if (!display) {
5147 return NAME_NOT_FOUND;
5148 }
5149
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005150 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005151 return NO_ERROR;
5152 }
5153 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005154 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005155 // daltonize
5156 n = data.readInt32();
5157 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005158 case 1:
5159 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5160 break;
5161 case 2:
5162 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5163 break;
5164 case 3:
5165 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5166 break;
5167 default:
5168 mDaltonizer.setType(ColorBlindnessType::None);
5169 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005170 }
5171 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005172 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005173 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005174 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005175 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005176
5177 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005178 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005179 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005180 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005181 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005182 // apply a color matrix
5183 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005184 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005185 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005186 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005187 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005188 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005189 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005190 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005191 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005192 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005193 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005194
5195 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5196 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005197 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005198 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5199 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5200 }
5201
Chia-I Wu28f320b2018-05-03 11:02:56 -07005202 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005203 return NO_ERROR;
5204 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005205 // This is an experimental interface
5206 // Needs to be shifted to proper binder interface when we productize
5207 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005208 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005209 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005210 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005211 return NO_ERROR;
5212 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005213 case 1017: {
5214 n = data.readInt32();
5215 mForceFullDamage = static_cast<bool>(n);
5216 return NO_ERROR;
5217 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005218 case 1018: { // Modify Choreographer's phase offset
5219 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005220 if (mUseScheduler) {
5221 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5222 } else {
5223 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5224 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005225 return NO_ERROR;
5226 }
5227 case 1019: { // Modify SurfaceFlinger's phase offset
5228 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005229 if (mUseScheduler) {
5230 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5231 } else {
5232 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5233 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005234 return NO_ERROR;
5235 }
Irvel468051e2016-06-13 16:44:44 -07005236 case 1020: { // Layer updates interceptor
5237 n = data.readInt32();
5238 if (n) {
5239 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005240 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005241 }
5242 else{
5243 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005244 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005245 }
5246 return NO_ERROR;
5247 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005248 case 1021: { // Disable HWC virtual displays
5249 n = data.readInt32();
5250 mUseHwcVirtualDisplays = !n;
5251 return NO_ERROR;
5252 }
Romain Guy0147a172017-06-01 13:53:56 -07005253 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005254 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005255 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005256
Chia-I Wu28f320b2018-05-03 11:02:56 -07005257 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005258 return NO_ERROR;
5259 }
Romain Guy54f154a2017-10-24 21:40:32 +01005260 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005261 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005262 invalidateHwcGeometry();
5263 repaintEverything();
5264 return NO_ERROR;
5265 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005266 // Deprecate, use 1030 to check whether the device is color managed.
5267 case 1024: {
5268 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005269 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005270 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005271 n = data.readInt32();
5272 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005273 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005274 mTracing.enable();
5275 doTracing("tracing.enable");
5276 reply->writeInt32(NO_ERROR);
5277 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005278 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005279 status_t err = mTracing.disable();
5280 reply->writeInt32(err);
5281 }
5282 return NO_ERROR;
5283 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005284 case 1026: { // Get layer tracing status
5285 reply->writeBool(mTracing.isEnabled());
5286 return NO_ERROR;
5287 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005288 // Is a DisplayColorSetting supported?
5289 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005290 const auto display = getDefaultDisplayDevice();
5291 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005292 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005293 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005294
5295 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5296 switch (setting) {
5297 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005298 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005299 break;
5300 case DisplayColorSetting::UNMANAGED:
5301 reply->writeBool(true);
5302 break;
5303 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005304 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005305 break;
5306 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005307 reply->writeBool(
5308 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005309 break;
5310 }
5311 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005312 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005313 // Is VrFlinger active?
5314 case 1028: {
5315 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005316 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005317 return NO_ERROR;
5318 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005319 // Is device color managed?
5320 case 1030: {
5321 reply->writeBool(useColorManagement);
5322 return NO_ERROR;
5323 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005324 // Override default composition data space
5325 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5326 // && adb shell stop zygote && adb shell start zygote
5327 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5328 // adb shell stop zygote && adb shell start zygote
5329 case 1031: {
5330 Mutex::Autolock _l(mStateLock);
5331 n = data.readInt32();
5332 if (n) {
5333 n = data.readInt32();
5334 if (n) {
5335 Dataspace dataspace = static_cast<Dataspace>(n);
5336 if (!validateCompositionDataspace(dataspace)) {
5337 return BAD_VALUE;
5338 }
5339 mDefaultCompositionDataspace = dataspace;
5340 }
5341 n = data.readInt32();
5342 if (n) {
5343 Dataspace dataspace = static_cast<Dataspace>(n);
5344 if (!validateCompositionDataspace(dataspace)) {
5345 return BAD_VALUE;
5346 }
5347 mWideColorGamutCompositionDataspace = dataspace;
5348 }
5349 } else {
5350 // restore composition data space.
5351 mDefaultCompositionDataspace = defaultCompositionDataspace;
5352 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5353 }
5354 return NO_ERROR;
5355 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005356 }
5357 }
5358 return err;
5359}
5360
Steven Thomas6d8110b2017-08-31 18:24:21 -07005361void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005362 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005363 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005364}
5365
Ana Krulec7d1d6832018-12-27 11:10:09 -08005366void SurfaceFlinger::repaintEverythingForHWC() {
5367 mRepaintEverything = true;
5368 mEventQueue->invalidateForHWC();
5369}
5370
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005371// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5372class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005373public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005374 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5375 ~WindowDisconnector() {
5376 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005377 }
5378
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005379private:
5380 ANativeWindow* mWindow;
5381 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005382};
5383
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005384status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005385 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5386 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005387 uint32_t reqWidth, uint32_t reqHeight,
5388 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005389 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005390 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005391
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005392 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005393
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005394 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5395
Chia-I Wu20261cb2018-08-23 12:55:44 -07005396 sp<DisplayDevice> display;
5397 {
5398 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005399
Chia-I Wu20261cb2018-08-23 12:55:44 -07005400 display = getDisplayDeviceLocked(displayToken);
5401 if (!display) return BAD_VALUE;
5402
Chia-I Wucb023152018-08-28 12:57:23 -07005403 // set the requested width/height to the logical display viewport size
5404 // by default
5405 if (reqWidth == 0 || reqHeight == 0) {
5406 reqWidth = uint32_t(display->getViewport().width());
5407 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005408 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005409 }
5410
Peiyong Lin0e003c92018-09-17 11:09:51 -07005411 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5412 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005413
5414 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005415 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005416 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5417 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005418}
5419
5420status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005421 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5422 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005423 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005424 ATRACE_CALL();
5425
5426 class LayerRenderArea : public RenderArea {
5427 public:
Robert Carr578038f2018-03-09 12:25:24 -08005428 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005429 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5430 bool childrenOnly)
5431 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005432 mLayer(layer),
5433 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005434 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005435 mFlinger(flinger),
5436 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005437 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005438 Rect getBounds() const override {
5439 const Layer::State& layerState(mLayer->getDrawingState());
5440 return mLayer->getBufferSize(layerState);
5441 }
Marissa Wall61c58622018-07-18 10:12:20 -07005442 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005443 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005444 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005445 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005446 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005447 }
chaviwa76b2712017-09-20 12:02:26 -07005448 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005449 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005450 Rect getSourceCrop() const override {
5451 if (mCrop.isEmpty()) {
5452 return getBounds();
5453 } else {
5454 return mCrop;
5455 }
5456 }
Robert Carr578038f2018-03-09 12:25:24 -08005457 class ReparentForDrawing {
5458 public:
5459 const sp<Layer>& oldParent;
5460 const sp<Layer>& newParent;
5461
5462 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5463 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005464 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005465 }
Robert Carr15eae092018-03-23 13:43:53 -07005466 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005467 };
5468
5469 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005470 const Rect sourceCrop = getSourceCrop();
5471 // no need to check rotation because there is none
5472 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5473 sourceCrop.height() != getReqHeight();
5474
Robert Carr578038f2018-03-09 12:25:24 -08005475 if (!mChildrenOnly) {
5476 mTransform = mLayer->getTransform().inverse();
5477 drawLayers();
5478 } else {
5479 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005480 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005481 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5482 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005483
5484 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5485 drawLayers();
5486 }
5487 }
chaviwa76b2712017-09-20 12:02:26 -07005488
chaviwa76b2712017-09-20 12:02:26 -07005489 private:
chaviw7206d492017-11-10 16:16:12 -08005490 const sp<Layer> mLayer;
5491 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005492
5493 // In the "childrenOnly" case we reparent the children to a screenshot
5494 // layer which has no properties set and which does not draw.
5495 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005496 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005497 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005498
5499 SurfaceFlinger* mFlinger;
5500 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005501 };
5502
5503 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5504 auto parent = layerHandle->owner.promote();
5505
Robert Carr2e102c92018-10-23 12:11:15 -07005506 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005507 ALOGE("captureLayers called with a removed parent");
5508 return NAME_NOT_FOUND;
5509 }
5510
Robert Carr578038f2018-03-09 12:25:24 -08005511 const int uid = IPCThreadState::self()->getCallingUid();
5512 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005513 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005514 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5515 return PERMISSION_DENIED;
5516 }
5517
chaviw7206d492017-11-10 16:16:12 -08005518 Rect crop(sourceCrop);
5519 if (sourceCrop.width() <= 0) {
5520 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005521 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005522 }
5523
5524 if (sourceCrop.height() <= 0) {
5525 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005526 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005527 }
5528
5529 int32_t reqWidth = crop.width() * frameScale;
5530 int32_t reqHeight = crop.height() * frameScale;
5531
Chia-I Wu20261cb2018-08-23 12:55:44 -07005532 // really small crop or frameScale
5533 if (reqWidth <= 0) {
5534 reqWidth = 1;
5535 }
5536 if (reqHeight <= 0) {
5537 reqHeight = 1;
5538 }
5539
Peiyong Lin0e003c92018-09-17 11:09:51 -07005540 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005541
Robert Carr578038f2018-03-09 12:25:24 -08005542 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005543 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5544 if (!layer->isVisible()) {
5545 return;
Robert Carr578038f2018-03-09 12:25:24 -08005546 } else if (childrenOnly && layer == parent.get()) {
5547 return;
chaviwa76b2712017-09-20 12:02:26 -07005548 }
5549 visitor(layer);
5550 });
5551 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005552 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005553}
5554
5555status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5556 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005557 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005558 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005559 bool useIdentityTransform) {
5560 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005561
Peiyong Lin0e003c92018-09-17 11:09:51 -07005562 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005563 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5564 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005565 *outBuffer =
5566 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5567 static_cast<android_pixel_format>(reqPixelFormat), 1,
5568 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005569
5570 // This mutex protects syncFd and captureResult for communication of the return values from the
5571 // main thread back to this Binder thread
5572 std::mutex captureMutex;
5573 std::condition_variable captureCondition;
5574 std::unique_lock<std::mutex> captureLock(captureMutex);
5575 int syncFd = -1;
5576 std::optional<status_t> captureResult;
5577
Robert Carr03480e22018-01-04 16:02:06 -08005578 const int uid = IPCThreadState::self()->getCallingUid();
5579 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5580
Dominik Laskowski8c001672018-05-30 16:52:06 -07005581 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005582 // If there is a refresh pending, bug out early and tell the binder thread to try again
5583 // after the refresh.
5584 if (mRefreshPending) {
5585 ATRACE_NAME("Skipping screenshot for now");
5586 std::unique_lock<std::mutex> captureLock(captureMutex);
5587 captureResult = std::make_optional<status_t>(EAGAIN);
5588 captureCondition.notify_one();
5589 return;
5590 }
5591
5592 status_t result = NO_ERROR;
5593 int fd = -1;
5594 {
5595 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005596 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005597 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5598 useIdentityTransform, forSystem, &fd);
5599 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005600 }
5601
5602 {
5603 std::unique_lock<std::mutex> captureLock(captureMutex);
5604 syncFd = fd;
5605 captureResult = std::make_optional<status_t>(result);
5606 captureCondition.notify_one();
5607 }
5608 });
5609
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005610 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005611 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005612 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005613 while (*captureResult == EAGAIN) {
5614 captureResult.reset();
5615 result = postMessageAsync(message);
5616 if (result != NO_ERROR) {
5617 return result;
5618 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005619 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005620 }
5621 result = *captureResult;
5622 }
5623
5624 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005625 sync_wait(syncFd, -1);
5626 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005627 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005628
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005629 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005630}
5631
chaviwa76b2712017-09-20 12:02:26 -07005632void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005633 TraverseLayersFunction traverseLayers,
Alec Mouri0f714832018-11-12 15:31:06 -08005634 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5635 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005636 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005637
chaviwa76b2712017-09-20 12:02:26 -07005638 const auto reqWidth = renderArea.getReqWidth();
5639 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005640 const auto sourceCrop = renderArea.getSourceCrop();
5641 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005642
Alec Mouri0f714832018-11-12 15:31:06 -08005643 renderengine::DisplaySettings clientCompositionDisplay;
5644 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005645
Alec Mouri0f714832018-11-12 15:31:06 -08005646 // assume that bounds are never offset, and that they are the same as the
5647 // buffer bounds.
5648 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5649 ui::Transform transform = renderArea.getTransform();
5650 mat4 m;
5651 m[0][0] = transform[0][0];
5652 m[0][1] = transform[0][1];
5653 m[0][3] = transform[0][2];
5654 m[1][0] = transform[1][0];
5655 m[1][1] = transform[1][1];
5656 m[1][3] = transform[1][2];
5657 m[3][0] = transform[2][0];
5658 m[3][1] = transform[2][1];
5659 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005660
Alec Mouri0f714832018-11-12 15:31:06 -08005661 clientCompositionDisplay.globalTransform = m;
5662 mat4 rotMatrix;
5663 // Displacement for repositioning the clipping rectangle after rotating it
5664 // with the rotation hint.
5665 int displacementX = 0;
5666 int displacementY = 0;
5667 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5668 switch (rotation) {
5669 case ui::Transform::ROT_90:
5670 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5671 displacementX = reqWidth;
5672 break;
5673 case ui::Transform::ROT_180:
5674 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5675 displacementX = reqWidth;
5676 displacementY = reqHeight;
5677 break;
5678 case ui::Transform::ROT_270:
5679 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5680 displacementY = reqHeight;
5681 break;
5682 default:
5683 break;
5684 }
5685 // We need to transform the clipping window into the right spot.
5686 // First, rotate the clipping rectangle by the rotation hint to get the
5687 // right orientation
5688 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5689 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5690 const vec4 rotClipTL = rotMatrix * clipTL;
5691 const vec4 rotClipBR = rotMatrix * clipBR;
5692 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5693 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5694 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5695 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5696
5697 // Now reposition the clipping rectangle with the displacement vector
5698 // computed above.
5699 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5700
5701 clientCompositionDisplay.clip =
5702 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5703 newClipRight + displacementX, newClipBottom + displacementY);
5704
5705 // We need to perform the same transformation in layer space, so propagate
5706 // it to the global transform.
5707 mat4 clipTransform = displacementMat * rotMatrix;
5708 clientCompositionDisplay.globalTransform *= clipTransform;
5709 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5710 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005711
chaviw50da5042018-04-09 13:49:37 -07005712 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005713
Alec Mouri0f714832018-11-12 15:31:06 -08005714 renderengine::LayerSettings fillLayer;
5715 fillLayer.source.buffer.buffer = nullptr;
5716 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5717 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5718 fillLayer.alpha = half(alpha);
5719 clientCompositionLayers.push_back(fillLayer);
5720
5721 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005722 traverseLayers([&](Layer* layer) {
Alec Mouri0f714832018-11-12 15:31:06 -08005723 renderengine::LayerSettings layerSettings;
5724 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5725 layerSettings);
5726 if (prepared) {
5727 clientCompositionLayers.push_back(layerSettings);
5728 }
chaviwa76b2712017-09-20 12:02:26 -07005729 });
Alec Mouri0f714832018-11-12 15:31:06 -08005730
5731 clientCompositionDisplay.clearRegion = clearRegion;
5732 base::unique_fd drawFence;
5733 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
5734 &drawFence);
5735
5736 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005737}
5738
chaviwa76b2712017-09-20 12:02:26 -07005739status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5740 TraverseLayersFunction traverseLayers,
5741 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005742 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005743 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005744 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005745 ATRACE_CALL();
5746
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005747 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005748
5749 traverseLayers([&](Layer* layer) {
5750 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5751 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005752
Robert Carr03480e22018-01-04 16:02:06 -08005753 // We allow the system server to take screenshots of secure layers for
5754 // use in situations like the Screen-rotation animation and place
5755 // the impetus on WindowManager to not persist them.
5756 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005757 ALOGW("FB is protected: PERMISSION_DENIED");
5758 return PERMISSION_DENIED;
5759 }
Alec Mouri0f714832018-11-12 15:31:06 -08005760 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005761 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005762}
5763
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005764// ---------------------------------------------------------------------------
5765
Dan Stoza412903f2017-04-27 13:42:17 -07005766void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5767 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005768}
5769
Dan Stoza412903f2017-04-27 13:42:17 -07005770void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5771 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005772}
5773
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005774void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005775 const LayerVector::Visitor& visitor) {
5776 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005777 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005778 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005779 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005780 continue;
5781 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005782 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005783 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005784 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005785 return;
5786 }
chaviwa76b2712017-09-20 12:02:26 -07005787 if (!layer->isVisible()) {
5788 return;
5789 }
5790 visitor(layer);
5791 });
5792 }
5793}
5794
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005795}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005796
Lloyd Pique074e8122018-07-26 12:57:23 -07005797
Mathias Agopian3f844832013-08-07 21:24:32 -07005798#if defined(__gl_h_)
5799#error "don't include gl/gl.h in this file"
5800#endif
5801
5802#if defined(__gl2_h_)
5803#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005804#endif