blob: 96496f0e89e64280f41c7f2d990c967b60cf00b8 [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 Mouri79108df2019-02-04 19:33:44 +000017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080031#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Lloyd Pique70d91362018-10-18 16:02:55 -070040#include <compositionengine/CompositionEngine.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070041#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070042#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080043#include <compositionengine/Layer.h>
44#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070045#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070046#include <compositionengine/impl/OutputCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080047#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070049#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080051#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080052#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080053#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070054#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070055#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070056#include <ui/ColorSpace.h>
57#include <ui/DebugUtils.h>
58#include <ui/DisplayInfo.h>
59#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070060#include <ui/GraphicBufferAllocator.h>
61#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070062#include <ui/UiConfig.h>
Ady Abraham8164d482019-01-11 14:47:59 -080063#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070065#include <utils/String16.h>
66#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070067#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080068#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070069#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080070
Mathias Agopian921e6ac2012-07-23 23:11:29 -070071#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070072#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073
Robert Carr578038f2018-03-09 12:25:24 -080074#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070075#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070076#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020077#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020079#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080080#include "ContainerLayer.h"
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 Mouri79108df2019-02-04 19:33:44 +00001876 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001877 if (!dirtyRegion.isEmpty()) {
1878 // redraw the whole screen
Alec Mouri79108df2019-02-04 19:33:44 +00001879 doComposeSurfaces(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001880
Alec Mouri79108df2019-02-04 19:33:44 +00001881 // and draw the dirty region
1882 auto& engine(getRenderEngine());
1883 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
1884
1885 display->getRenderSurface()->queueBuffer();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001886 }
1887 }
1888
Lloyd Pique32cbe282018-10-19 13:09:22 -07001889 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001890
1891 if (mDebugRegion > 1) {
1892 usleep(mDebugRegion * 1000);
1893 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001894
Lloyd Pique32cbe282018-10-19 13:09:22 -07001895 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001896}
1897
Adrian Roos1e1a1282017-11-01 19:05:31 +01001898void SurfaceFlinger::doTracing(const char* where) {
1899 ATRACE_CALL();
1900 ATRACE_NAME(where);
1901 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001902 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001903 }
1904}
1905
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001906void SurfaceFlinger::logLayerStats() {
1907 ATRACE_CALL();
1908 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001909 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001910 if (display->isPrimary()) {
1911 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001912 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001913 }
1914 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001915
1916 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001917 }
1918}
1919
David Sodman2b406362017-12-15 13:33:47 -08001920void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001921{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001922 ATRACE_CALL();
1923 ALOGV("preComposition");
1924
David Sodman2b406362017-12-15 13:33:47 -08001925 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1926
Mathias Agopiancd60f992012-08-16 16:28:27 -07001927 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001928 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001929 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001930 needExtraInvalidate = true;
1931 }
Robert Carr2047fae2016-11-28 14:09:09 -08001932 });
1933
Mathias Agopiancd60f992012-08-16 16:28:27 -07001934 if (needExtraInvalidate) {
1935 signalLayerUpdate();
1936 }
1937}
1938
Ana Krulece588e312018-09-18 12:32:24 -07001939void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1940 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001941 // Update queue of past composite+present times and determine the
1942 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001943 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001944 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001945 while (!getBE().mCompositePresentTimes.empty()) {
1946 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001947 // Cached values should have been updated before calling this method,
1948 // which helps avoid duplicate syscalls.
1949 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1950 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1951 break;
1952 }
1953 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001954 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001955 }
1956
1957 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001958 while (getBE().mCompositePresentTimes.size() > 16) {
1959 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001960 }
1961
Ana Krulece588e312018-09-18 12:32:24 -07001962 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001963}
1964
Ana Krulece588e312018-09-18 12:32:24 -07001965void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1966 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001967 // Integer division and modulo round toward 0 not -inf, so we need to
1968 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001969 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1970 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1971 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001972
Ana Krulec757f63a2019-01-25 10:46:18 -08001973 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001974 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001975 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001976 }
1977
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001978 // Snap the latency to a value that removes scheduling jitter from the
1979 // composition and present times, which often have >1ms of jitter.
1980 // Reducing jitter is important if an app attempts to extrapolate
1981 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001982 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001983 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001984 nsecs_t bias = stats.vsyncPeriod / 2;
1985 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1986 nsecs_t snappedCompositeToPresentLatency =
1987 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001988
David Sodman99974d22017-11-28 12:04:33 -08001989 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001990 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1991 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001992 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001993}
1994
Ady Abraham8164d482019-01-11 14:47:59 -08001995// debug patch for b/119477596 - add stack guards to catch stack
1996// corruptions and disable clang optimizations.
1997// The code below is temporary and planned to be removed once stack
1998// corruptions are found.
1999#pragma clang optimize off
2000class StackGuard {
2001public:
2002 StackGuard(const char* name, const char* func, int line) {
2003 guarders.reserve(MIN_CAPACITY);
2004 guarders.push_back({this, name, func, line});
2005 validate();
2006 }
2007 ~StackGuard() {
2008 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
2009 if (i->guard == this) {
2010 guarders.erase(i);
2011 break;
2012 }
2013 }
2014 }
2015
2016 static void validate() {
2017 for (const auto& guard : guarders) {
2018 if (guard.guard->cookie != COOKIE_VALUE) {
2019 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
2020 CallStack stack(LOG_TAG);
2021 abort();
2022 }
2023 }
2024 }
2025
2026private:
2027 uint64_t cookie = COOKIE_VALUE;
2028 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
2029 static constexpr size_t MIN_CAPACITY = 16;
2030
2031 struct GuarderElement {
2032 StackGuard* guard;
2033 const char* name;
2034 const char* func;
2035 int line;
2036 };
2037
2038 static std::vector<GuarderElement> guarders;
2039};
2040std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2041
2042#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2043
2044#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002045void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002046{
Ady Abraham8164d482019-01-11 14:47:59 -08002047 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002048 ATRACE_CALL();
2049 ALOGV("postComposition");
2050
Brian Anderson3546a3f2016-07-14 11:51:14 -07002051 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002052 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002053 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002054 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002055 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002056 }
Ady Abraham8164d482019-01-11 14:47:59 -08002057 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002058
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002059 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002060 const auto displayDevice = getDefaultDisplayDeviceLocked();
2061 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002062
David Sodman73beded2017-11-15 11:56:06 -08002063 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002064 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002065 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2066
Lloyd Pique32cbe282018-10-19 13:09:22 -07002067 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002068 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002069 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2070 ->getRenderSurface()
2071 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002072 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002073 } else {
2074 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2075 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002076
Ady Abraham8164d482019-01-11 14:47:59 -08002077 ASSERT_ON_STACK_GUARD();
2078
David Sodman73beded2017-11-15 11:56:06 -08002079 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002080 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2081 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002082 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002083 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002084 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002085
Ana Krulece588e312018-09-18 12:32:24 -07002086 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002087 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002088 if (mUseScheduler) {
2089 mScheduler->getDisplayStatInfo(&stats);
2090 } else {
2091 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2092 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2093 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002094
Ady Abraham8164d482019-01-11 14:47:59 -08002095 ASSERT_ON_STACK_GUARD();
2096
David Sodman2b406362017-12-15 13:33:47 -08002097 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002098 // when we started doing work for this frame, but that should be okay
2099 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002100 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002101 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002102 DEFINE_STACK_GUARD(compositorTiming);
2103
Brian Andersond0010582017-03-07 13:20:31 -08002104 {
David Sodman99974d22017-11-28 12:04:33 -08002105 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002106 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002107 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002108
2109 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002110 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002111
Robert Carr2047fae2016-11-28 14:09:09 -08002112 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002113 bool frameLatched =
2114 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2115 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002116 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002117 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002118 recordBufferingStats(layer->getName().string(),
2119 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002120 }
Ady Abraham8164d482019-01-11 14:47:59 -08002121 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002122 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002123
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002124 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002125 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002126 if (mUseScheduler) {
2127 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002128 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002129 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002130 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2131 enableHardwareVsync();
2132 } else {
2133 disableHardwareVsync(false);
2134 }
Ady Abraham8164d482019-01-11 14:47:59 -08002135 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002136 }
2137 }
2138
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002139 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002140 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2141 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002142 if (mUseScheduler) {
2143 mScheduler->enableHardwareVsync();
2144 } else {
2145 enableHardwareVsync();
2146 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002147 }
2148 }
2149
Ady Abraham8164d482019-01-11 14:47:59 -08002150 ASSERT_ON_STACK_GUARD();
2151
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002152 if (mAnimCompositionPending) {
2153 mAnimCompositionPending = false;
2154
Brian Anderson4e606e32017-03-16 15:34:57 -07002155 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002156 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002157 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002158
2159 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002160 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002161 // The HWC doesn't support present fences, so use the refresh
2162 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002163 const nsecs_t presentTime =
2164 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002165 DEFINE_STACK_GUARD(presentTime);
2166
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002167 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002168 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002169 }
2170 mAnimFrameTracker.advanceFrame();
2171 }
Dan Stozab90cf072015-03-05 11:05:59 -08002172
Ady Abraham8164d482019-01-11 14:47:59 -08002173 ASSERT_ON_STACK_GUARD();
2174
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002175 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002176 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002177 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002178 }
2179
Ady Abraham8164d482019-01-11 14:47:59 -08002180 ASSERT_ON_STACK_GUARD();
2181
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002182 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002183
Ady Abraham8164d482019-01-11 14:47:59 -08002184 ASSERT_ON_STACK_GUARD();
2185
Lloyd Pique32cbe282018-10-19 13:09:22 -07002186 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2187 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002188 return;
2189 }
2190
2191 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002192 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002193 if (mHasPoweredOff) {
2194 mHasPoweredOff = false;
2195 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002196 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002197 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002198 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002199 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002200 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2201 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002202 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002203 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002204 }
David Sodman4a36e932017-11-07 14:29:47 -08002205 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002206
2207 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002208 }
David Sodman4a36e932017-11-07 14:29:47 -08002209 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002210 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002211
2212 {
2213 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002214 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002215 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002216 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002217 if (refillCount > 0) {
2218 const size_t offset = mTexturePool.size();
2219 mTexturePool.resize(mTexturePoolSize);
2220 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2221 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2222 }
Ady Abraham8164d482019-01-11 14:47:59 -08002223 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002224 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002225
Marissa Wallfda30bb2018-10-12 11:34:28 -07002226 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002227 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002228
2229 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002230}
Ady Abraham8164d482019-01-11 14:47:59 -08002231#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002232
2233void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002234 ATRACE_CALL();
2235 ALOGV("rebuildLayerStacks");
2236
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002237 // We need to clear these out now as these may be holding on to a
2238 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2239 // also holds a reference. When the set of visible layers is recomputed,
2240 // some layers may be destroyed if the only thing keeping them alive was
2241 // that list of visible layers associated with each display. The layer
2242 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2243 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2244 for (const auto& [token, display] : mDisplays) {
2245 getBE().mCompositionInfo[token].clear();
2246 }
2247
Mathias Agopiancd60f992012-08-16 16:28:27 -07002248 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002249 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002250 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002251 mVisibleRegionsDirty = false;
2252 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002253
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002254 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002255 const auto& displayDevice = pair.second;
2256 auto display = displayDevice->getCompositionDisplay();
2257 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002258 Region opaqueRegion;
2259 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002260 compositionengine::Output::OutputLayers layersSortedByZ;
2261 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002262 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002263 const ui::Transform& tr = displayState.transform;
2264 const Rect bounds = displayState.bounds;
2265 if (displayState.isEnabled) {
2266 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002267
Jeff Sharkey76488112017-02-27 14:15:18 -07002268 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002269 auto compositionLayer = layer->getCompositionLayer();
2270 if (compositionLayer == nullptr) {
2271 return;
2272 }
2273
Chia-I Wu83806892017-11-16 10:50:20 -08002274 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002275 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002276 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2277 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2278
Lloyd Piqueef36b002019-01-23 17:52:04 -08002279 if (display->belongsInOutput(layer->getLayerStack(),
2280 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002281 Region drawRegion(tr.transform(
2282 layer->visibleNonTransparentRegion));
2283 drawRegion.andSelf(bounds);
2284 if (!drawRegion.isEmpty()) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002285 layersSortedByZ.emplace_back(
2286 display->getOrCreateOutputLayer(layer->getCompositionLayer(),
2287 layerFE));
2288
2289 deprecated_layersSortedByZ.add(layer);
Jeff Sharkey76488112017-02-27 14:15:18 -07002290 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002291 // Clear out the HWC layer if this layer was
2292 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002293 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002294 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002295 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002296 // WM changes display->layerStack upon sleep/awake.
2297 // Here we make sure we delete the HWC layers even if
2298 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002299 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002300 }
2301
2302 // If a layer is not going to get a release fence because
2303 // it is invisible, but it is also going to release its
2304 // old buffer, add it to the list of layers needing
2305 // fences.
2306 if (hwcLayerDestroyed) {
2307 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2308 mLayersWithQueuedFrames.cend(), layer);
2309 if (found != mLayersWithQueuedFrames.cend()) {
2310 layersNeedingFences.add(layer);
2311 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002312 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002313 });
2314 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002315
2316 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2317
2318 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002319 displayDevice->setLayersNeedingFences(layersNeedingFences);
2320
2321 Region undefinedRegion{bounds};
2322 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2323
2324 display->editState().undefinedRegion = undefinedRegion;
2325 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002326 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002327 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002328}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002329
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002330// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002331// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002332// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002333// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002334// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002335// The returned HDR data space is one of
2336// - Dataspace::UNKNOWN
2337// - Dataspace::BT2020_HLG
2338// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002339Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2340 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002341 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002342 *outHdrDataSpace = Dataspace::UNKNOWN;
2343
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002344 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002345 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002346 case Dataspace::V0_SCRGB:
2347 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002348 case Dataspace::BT2020:
2349 case Dataspace::BT2020_ITU:
2350 case Dataspace::BT2020_LINEAR:
2351 case Dataspace::DISPLAY_BT2020:
2352 bestDataSpace = Dataspace::DISPLAY_BT2020;
2353 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002354 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002355 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002356 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002357 case Dataspace::BT2020_PQ:
2358 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002359 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002360 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002361 case Dataspace::BT2020_HLG:
2362 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002363 // When there's mixed PQ content and HLG content, we set the HDR
2364 // data space to be BT2020_PQ and convert HLG to PQ.
2365 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2366 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002367 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002368 break;
2369 default:
2370 break;
2371 }
Romain Guy54f154a2017-10-24 21:40:32 +01002372 }
2373
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002374 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002375}
2376
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002377// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002378void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2379 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002380 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2381 *outMode = ColorMode::NATIVE;
2382 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002383 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002384 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002385 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002386
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002387 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002388 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002389
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002390 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2391
Peiyong Lindfde5112018-06-05 10:58:41 -07002392 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002393 const bool isHdr =
2394 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002395 if (isHdr) {
2396 bestDataSpace = hdrDataSpace;
2397 }
2398
Chia-I Wu0d711262018-05-21 15:19:35 -07002399 RenderIntent intent;
2400 switch (mDisplayColorSetting) {
2401 case DisplayColorSetting::MANAGED:
2402 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002403 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002404 break;
2405 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002406 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002407 break;
2408 default: // vendor display color setting
2409 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2410 break;
2411 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002412
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002413 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002414}
2415
Lloyd Pique32cbe282018-10-19 13:09:22 -07002416void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2417 auto display = displayDevice->getCompositionDisplay();
2418 const auto& displayState = display->getState();
2419
Alec Mouri79108df2019-02-04 19:33:44 +00002420 bool dirty = !display->getPhysicalSpaceDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002421 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2422 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002423
David Sodmanfa9b2af2017-12-24 13:28:59 -08002424 // If nothing has changed (!dirty), don't recompose.
2425 // If something changed, but we don't currently have any visible layers,
2426 // and didn't when we last did a composition, then skip it this time.
2427 // The second rule does two things:
2428 // - When all layers are removed from a display, we'll emit one black
2429 // frame, then nothing more until we get new layers.
2430 // - When a display is created with a private layer stack, we won't
2431 // emit any black frames until a layer is added to the layer stack.
2432 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002433
Dominik Laskowski075d3172018-05-24 15:50:06 -07002434 const char flagPrefix[] = {'-', '+'};
2435 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002436 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2437 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2438 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2439 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002440
Lloyd Pique31cb2942018-10-19 17:23:03 -07002441 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002442
David Sodmanfa9b2af2017-12-24 13:28:59 -08002443 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002444 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002445 }
2446}
2447
Lloyd Pique32cbe282018-10-19 13:09:22 -07002448void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2449 auto display = displayDevice->getCompositionDisplay();
2450 const auto& displayState = display->getState();
2451
2452 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002453 return;
David Sodman2b406362017-12-15 13:33:47 -08002454 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002455
Lloyd Pique31cb2942018-10-19 17:23:03 -07002456 status_t result = display->getRenderSurface()->prepareFrame(
2457 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002458 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002459 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002460}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002461
Lloyd Pique32cbe282018-10-19 13:09:22 -07002462void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002463 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002464 ALOGV("doComposition");
2465
Lloyd Pique32cbe282018-10-19 13:09:22 -07002466 auto display = displayDevice->getCompositionDisplay();
2467 const auto& displayState = display->getState();
2468
2469 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002470 // transform the dirty region into this screen's coordinate space
Alec Mouri79108df2019-02-04 19:33:44 +00002471 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002472
David Sodmanfa9b2af2017-12-24 13:28:59 -08002473 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002474 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002475
Lloyd Pique32cbe282018-10-19 13:09:22 -07002476 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002477 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002478 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002479 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002480}
2481
David Sodmanfa9b2af2017-12-24 13:28:59 -08002482void SurfaceFlinger::postFrame()
2483{
2484 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002485 const auto display = getDefaultDisplayDeviceLocked();
2486 if (display && getHwComposer().isConnected(*display->getId())) {
2487 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002488 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2489 logFrameStats();
2490 }
2491 }
2492}
2493
Lloyd Pique32cbe282018-10-19 13:09:22 -07002494void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002495 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002496 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002497
Lloyd Pique32cbe282018-10-19 13:09:22 -07002498 auto display = displayDevice->getCompositionDisplay();
2499 const auto& displayState = display->getState();
2500 const auto displayId = display->getId();
2501
David Sodmanfa9b2af2017-12-24 13:28:59 -08002502 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002503
Lloyd Pique32cbe282018-10-19 13:09:22 -07002504 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002505 if (displayId) {
2506 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002507 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002508 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002509 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002510 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002511
Chia-I Wu7b549592017-11-15 09:14:57 -08002512 // The layer buffer from the previous frame (if any) is released
2513 // by HWC only when the release fence from this frame (if any) is
2514 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002515 if (displayId && layer->hasHwcLayer(*displayId)) {
2516 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2517 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002518 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002519
2520 // If the layer was client composited in the previous frame, we
2521 // need to merge with the previous client target acquire fence.
2522 // Since we do not track that, always merge with the current
2523 // client target acquire fence when it is available, even though
2524 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002525 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002526 releaseFence =
2527 Fence::merge("LayerRelease", releaseFence,
2528 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002529 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002530
David Sodman15094112018-10-11 09:39:37 -07002531 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002532 }
Chia-I Wu83806892017-11-16 10:50:20 -08002533
2534 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002535 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002536 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002537 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002538 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002539 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002540 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002541 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002542 }
2543 }
2544
Dominik Laskowski075d3172018-05-24 15:50:06 -07002545 if (displayId) {
2546 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002547 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002548 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002549}
2550
Mathias Agopian87baae12012-07-31 12:38:26 -07002551void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002552{
Mathias Agopian841cde52012-03-01 15:44:37 -08002553 ATRACE_CALL();
2554
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002555 // here we keep a copy of the drawing state (that is the state that's
2556 // going to be overwritten by handleTransactionLocked()) outside of
2557 // mStateLock so that the side-effects of the State assignment
2558 // don't happen with mStateLock held (which can cause deadlocks).
2559 State drawingState(mDrawingState);
2560
Mathias Agopianca4d3602011-05-19 15:38:14 -07002561 Mutex::Autolock _l(mStateLock);
2562 const nsecs_t now = systemTime();
2563 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002564
Mathias Agopianca4d3602011-05-19 15:38:14 -07002565 // Here we're guaranteed that some transaction flags are set
2566 // so we can call handleTransactionLocked() unconditionally.
2567 // We call getTransactionFlags(), which will also clear the flags,
2568 // with mStateLock held to guarantee that mCurrentState won't change
2569 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002570
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002571 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002572 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002573 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002574
Mathias Agopianca4d3602011-05-19 15:38:14 -07002575 mLastTransactionTime = systemTime() - now;
2576 mDebugInTransaction = 0;
2577 invalidateHwcGeometry();
2578 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002579}
2580
Lloyd Piqueba04e622017-12-14 17:11:26 -08002581void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2582 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002583 const std::optional<DisplayIdentificationInfo> info =
2584 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002585
Dominik Laskowski075d3172018-05-24 15:50:06 -07002586 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002587 continue;
2588 }
2589
Lloyd Piqueba04e622017-12-14 17:11:26 -08002590 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002591 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002592 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002593 mPhysicalDisplayTokens[info->id] = new BBinder();
2594 DisplayDeviceState state;
2595 state.displayId = info->id;
2596 state.isSecure = true; // All physical displays are currently considered secure.
2597 state.displayName = info->name;
2598 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2599 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002600 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002601 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002602 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002603
Dominik Laskowski075d3172018-05-24 15:50:06 -07002604 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2605 if (index >= 0) {
2606 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2607 mInterceptor->saveDisplayDeletion(state.sequenceId);
2608 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002609 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002610 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002611 }
2612
2613 processDisplayChangesLocked();
2614 }
2615
2616 mPendingHotplugEvents.clear();
2617}
2618
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002619void SurfaceFlinger::dispatchDisplayHotplugEvent(EventThread::DisplayType displayType,
2620 bool connected) {
2621 if (mUseScheduler) {
2622 mScheduler->hotplugReceived(mAppConnectionHandle, displayType, connected);
2623 mScheduler->hotplugReceived(mSfConnectionHandle, displayType, connected);
2624 } else {
2625 mEventThread->onHotplugReceived(displayType, connected);
2626 mSFEventThread->onHotplugReceived(displayType, connected);
2627 }
2628}
2629
Lloyd Pique99d3da52018-01-22 17:48:03 -08002630sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002631 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002632 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002633 const sp<IGraphicBufferProducer>& producer) {
2634 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002635 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002636 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002637 creationArgs.isSecure = state.isSecure;
2638 creationArgs.displaySurface = dispSurface;
2639 creationArgs.hasWideColorGamut = false;
2640 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002641
Dominik Laskowski075d3172018-05-24 15:50:06 -07002642 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2643 creationArgs.isPrimary = isInternalDisplay;
2644
2645 if (useColorManagement && displayId) {
2646 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002647 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002648 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002649 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002650 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002651
Dominik Laskowski7e045462018-05-30 13:02:02 -07002652 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002653 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002654 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002655 }
tangrobin6753a022018-08-10 10:58:54 +08002656 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002657
Dominik Laskowski075d3172018-05-24 15:50:06 -07002658 if (displayId) {
2659 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002660 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002661 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002662 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002663
Lloyd Pique90c115d2018-09-18 21:39:42 -07002664 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002665 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002666 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002667
Lloyd Pique99d3da52018-01-22 17:48:03 -08002668 // Make sure that composition can never be stalled by a virtual display
2669 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002670 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002671 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002672 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2673 }
2674
Dominik Laskowski075d3172018-05-24 15:50:06 -07002675 creationArgs.displayInstallOrientation =
2676 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002677
Lloyd Pique99d3da52018-01-22 17:48:03 -08002678 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002679 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002680
Lloyd Pique90c115d2018-09-18 21:39:42 -07002681 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002682
2683 if (maxFrameBufferAcquiredBuffers >= 3) {
2684 nativeWindowSurface->preallocateBuffers();
2685 }
2686
2687 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002688 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002689 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002690 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002691 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002692 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002693 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2694 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002695 if (!state.isVirtual()) {
2696 LOG_ALWAYS_FATAL_IF(!displayId);
2697 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002698 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002699
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002700 display->setLayerStack(state.layerStack);
2701 display->setProjection(state.orientation, state.viewport, state.frame);
2702 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002703
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002704 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002705}
2706
Lloyd Pique347200f2017-12-14 17:00:15 -08002707void SurfaceFlinger::processDisplayChangesLocked() {
2708 // here we take advantage of Vector's copy-on-write semantics to
2709 // improve performance by skipping the transaction entirely when
2710 // know that the lists are identical
2711 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2712 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2713 if (!curr.isIdenticalTo(draw)) {
2714 mVisibleRegionsDirty = true;
2715 const size_t cc = curr.size();
2716 size_t dc = draw.size();
2717
2718 // find the displays that were removed
2719 // (ie: in drawing state but not in current state)
2720 // also handle displays that changed
2721 // (ie: displays that are in both lists)
2722 for (size_t i = 0; i < dc;) {
2723 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2724 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002725 // Save display IDs before disconnecting.
2726 const auto internalDisplayId = getInternalDisplayId();
2727 const auto externalDisplayId = getExternalDisplayId();
2728
Lloyd Pique347200f2017-12-14 17:00:15 -08002729 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002730 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002731 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002732 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002733 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002734 dispatchDisplayHotplugEvent(EventThread::DisplayType::Primary, false);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002735 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002736 dispatchDisplayHotplugEvent(EventThread::DisplayType::External, false);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002737 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002738 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002739 } else {
2740 // this display is in both lists. see if something changed.
2741 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002742 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002743 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2744 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2745 if (state_binder != draw_binder) {
2746 // changing the surface is like destroying and
2747 // recreating the DisplayDevice, so we just remove it
2748 // from the drawing state, so that it get re-added
2749 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002750 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002751 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002752 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002753 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002754 mDrawingState.displays.removeItemsAt(i);
2755 dc--;
2756 // at this point we must loop to the next item
2757 continue;
2758 }
2759
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002760 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002761 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002762 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002763 }
2764 if ((state.orientation != draw[i].orientation) ||
2765 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002766 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002767 }
2768 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002769 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002770 }
2771 }
2772 }
2773 ++i;
2774 }
2775
2776 // find displays that were added
2777 // (ie: in current state but not in drawing state)
2778 for (size_t i = 0; i < cc; i++) {
2779 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2780 const DisplayDeviceState& state(curr[i]);
2781
Lloyd Pique542307f2018-10-19 13:24:08 -07002782 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002783 sp<IGraphicBufferProducer> producer;
2784 sp<IGraphicBufferProducer> bqProducer;
2785 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002786 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002787
Dominik Laskowski075d3172018-05-24 15:50:06 -07002788 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002789 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002790 // Virtual displays without a surface are dormant:
2791 // they have external state (layer stack, projection,
2792 // etc.) but no internal state (i.e. a DisplayDevice).
2793 if (state.surface != nullptr) {
2794 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002795 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002796 int width = 0;
2797 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2798 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2799 int height = 0;
2800 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2801 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2802 int intFormat = 0;
2803 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2804 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002805 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002806
Dominik Laskowski075d3172018-05-24 15:50:06 -07002807 displayId =
2808 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002809 }
2810
2811 // TODO: Plumb requested format back up to consumer
2812
2813 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002814 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002815 bqProducer, bqConsumer,
2816 state.displayName);
2817
2818 dispSurface = vds;
2819 producer = vds;
2820 }
2821 } else {
2822 ALOGE_IF(state.surface != nullptr,
2823 "adding a supported display, but rendering "
2824 "surface is provided (%p), ignoring it",
2825 state.surface.get());
2826
Dominik Laskowski075d3172018-05-24 15:50:06 -07002827 displayId = state.displayId;
2828 LOG_ALWAYS_FATAL_IF(!displayId);
2829 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002830 producer = bqProducer;
2831 }
2832
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002833 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002834 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002835 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002836 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002837 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002838 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002839 LOG_ALWAYS_FATAL_IF(!displayId);
2840
2841 if (displayId == getInternalDisplayId()) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002842 dispatchDisplayHotplugEvent(EventThread::DisplayType::Primary, true);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002843 } else if (displayId == getExternalDisplayId()) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002844 dispatchDisplayHotplugEvent(EventThread::DisplayType::External, true);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002845 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002846 }
2847 }
2848 }
2849 }
2850 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002851
2852 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002853}
2854
Mathias Agopian87baae12012-07-31 12:38:26 -07002855void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002856{
Dan Stoza7dde5992015-05-22 09:51:44 -07002857 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002858 mCurrentState.traverseInZOrder([](Layer* layer) {
2859 layer->notifyAvailableFrames();
2860 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002861
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002862 /*
2863 * Traversal of the children
2864 * (perform the transaction for each of them if needed)
2865 */
2866
Robert Carr720e5062018-07-30 17:45:14 -07002867 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002868 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002869 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002870 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002871 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002872
2873 const uint32_t flags = layer->doTransaction(0);
2874 if (flags & Layer::eVisibleRegion)
2875 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002876
2877 if (flags & Layer::eInputInfoChanged) {
2878 inputChanged = true;
2879 }
Robert Carr2047fae2016-11-28 14:09:09 -08002880 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002881 }
2882
2883 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002884 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002885 */
2886
Mathias Agopiane57f2922012-08-09 16:29:12 -07002887 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002888 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002889 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002890 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002891
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002892 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002893 // The transform hint might have changed for some layers
2894 // (either because a display has changed, or because a layer
2895 // as changed).
2896 //
2897 // Walk through all the layers in currentLayers,
2898 // and update their transform hint.
2899 //
2900 // If a layer is visible only on a single display, then that
2901 // display is used to calculate the hint, otherwise we use the
2902 // default display.
2903 //
2904 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2905 // the hint is set before we acquire a buffer from the surface texture.
2906 //
2907 // NOTE: layer transactions have taken place already, so we use their
2908 // drawing state. However, SurfaceFlinger's own transaction has not
2909 // happened yet, so we must use the current state layer list
2910 // (soon to become the drawing state list).
2911 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002912 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002913 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002914 bool first = true;
2915 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002916 // NOTE: we rely on the fact that layers are sorted by
2917 // layerStack first (so we don't have to traverse the list
2918 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002919 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002920 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002921 currentlayerStack = layerStack;
2922 // figure out if this layerstack is mirrored
2923 // (more than one display) if so, pick the default display,
2924 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002925 hintDisplay = nullptr;
2926 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002927 if (display->getCompositionDisplay()
2928 ->belongsInOutput(layer->getLayerStack(),
2929 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002930 if (hintDisplay) {
2931 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002932 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002933 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002934 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002935 }
2936 }
2937 }
2938 }
Chet Haase91d25932013-04-11 15:24:55 -07002939
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002940 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002941 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2942 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002943
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002944 // could be null when this layer is using a layerStack
2945 // that is not visible on any display. Also can occur at
2946 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002947 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002948 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002949
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002950 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002951 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002952 if (hintDisplay) {
2953 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002954 }
Robert Carr2047fae2016-11-28 14:09:09 -08002955
2956 first = false;
2957 });
Mathias Agopian84300952012-11-21 16:02:13 -08002958 }
2959
2960
Mathias Agopian3559b072012-08-15 13:46:03 -07002961 /*
2962 * Perform our own transaction if needed
2963 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002964
2965 if (mLayersAdded) {
2966 mLayersAdded = false;
2967 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002968 mVisibleRegionsDirty = true;
2969 }
2970
2971 // some layers might have been removed, so
2972 // we need to update the regions they're exposing.
2973 if (mLayersRemoved) {
2974 mLayersRemoved = false;
2975 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002976 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002977 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002978 // this layer is not visible anymore
2979 // TODO: we could traverse the tree from front to back and
2980 // compute the actual visible region
2981 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002982 Region visibleReg;
2983 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002984 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002985 }
Robert Carr2047fae2016-11-28 14:09:09 -08002986 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002987 }
2988
2989 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002990
Vishnu Nairde19f852018-12-18 16:11:53 -08002991 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002992 updateInputWindows();
2993 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002994 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002995
Riley Andrews03414a12014-07-01 14:22:59 -07002996 updateCursorAsync();
2997}
2998
Robert Carr720e5062018-07-30 17:45:14 -07002999void SurfaceFlinger::updateInputWindows() {
3000 ATRACE_CALL();
3001
Vishnu Nairde19f852018-12-18 16:11:53 -08003002 if (mInputFlinger == nullptr) {
3003 return;
3004 }
3005
Robert Carr720e5062018-07-30 17:45:14 -07003006 Vector<InputWindowInfo> inputHandles;
3007
3008 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
3009 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08003010 // When calculating the screen bounds we ignore the transparent region since it may
3011 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08003012 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07003013 }
3014 });
3015 mInputFlinger->setInputWindows(inputHandles);
3016}
3017
chaviwfbe5d9c2018-12-26 12:23:37 -08003018void SurfaceFlinger::executeInputWindowCommands() {
3019 if (!mInputFlinger) {
3020 return;
3021 }
3022
3023 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3024 if (transferTouchFocusCommand.fromToken != nullptr &&
3025 transferTouchFocusCommand.toToken != nullptr &&
3026 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3027 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3028 transferTouchFocusCommand.toToken);
3029 }
3030 }
3031
3032 mInputWindowCommands.clear();
3033}
3034
Riley Andrews03414a12014-07-01 14:22:59 -07003035void SurfaceFlinger::updateCursorAsync()
3036{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003037 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003038 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003039 continue;
3040 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003041
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003042 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3043 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003044 }
3045 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003046}
3047
chaviw61626f22018-11-15 16:26:27 -08003048void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3049 if (layer->hasReadyFrame()) {
3050 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3051 if (layer->shouldPresentNow(expectedPresentTime)) {
3052 bool ignored = false;
3053 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3054 }
3055 }
3056 layer->releasePendingBuffer(systemTime());
3057}
3058
Mathias Agopian4fec8732012-06-29 14:12:52 -07003059void SurfaceFlinger::commitTransaction()
3060{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003061 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003062 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003063 for (const auto& l : mLayersPendingRemoval) {
3064 recordBufferingStats(l->getName().string(),
3065 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003066
3067 // We need to release the HWC layers when the Layer is removed
3068 // from the current state otherwise the HWC layer just continues
3069 // showing at its last configured state until we eventually
3070 // abandon the buffer queue.
3071 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003072 l->destroyHwcLayersForAllDisplays();
3073 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003074 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003075 }
3076 mLayersPendingRemoval.clear();
3077 }
3078
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003079 // If this transaction is part of a window animation then the next frame
3080 // we composite should be considered an animation as well.
3081 mAnimCompositionPending = mAnimTransactionPending;
3082
Mathias Agopian4fec8732012-06-29 14:12:52 -07003083 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003084 // clear the "changed" flags in current state
3085 mCurrentState.colorMatrixChanged = false;
3086
Robert Carr1f0a16a2016-10-24 16:27:39 -07003087 mDrawingState.traverseInZOrder([](Layer* layer) {
3088 layer->commitChildList();
3089 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003090 mTransactionPending = false;
3091 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003092 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003093}
3094
Lloyd Pique32cbe282018-10-19 13:09:22 -07003095void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003096 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003097 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003098 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003099
Lloyd Pique32cbe282018-10-19 13:09:22 -07003100 auto display = displayDevice->getCompositionDisplay();
3101
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003102 Region aboveOpaqueLayers;
3103 Region aboveCoveredLayers;
3104 Region dirty;
3105
Mathias Agopian87baae12012-07-31 12:38:26 -07003106 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003107
Robert Carr2047fae2016-11-28 14:09:09 -08003108 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003109 // start with the whole surface at its current location
3110 const Layer::State& s(layer->getDrawingState());
3111
Jesse Hall01e29052013-02-19 16:13:35 -08003112 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003113 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003114 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003115 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003116
Mathias Agopianab028732010-03-16 16:41:46 -07003117 /*
3118 * opaqueRegion: area of a surface that is fully opaque.
3119 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003120 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003121
3122 /*
3123 * visibleRegion: area of a surface that is visible on screen
3124 * and not fully transparent. This is essentially the layer's
3125 * footprint minus the opaque regions above it.
3126 * Areas covered by a translucent surface are considered visible.
3127 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003128 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003129
3130 /*
3131 * coveredRegion: area of a surface that is covered by all
3132 * visible regions above it (which includes the translucent areas).
3133 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003134 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003135
Jesse Halla8026d22012-09-25 13:25:04 -07003136 /*
3137 * transparentRegion: area of a surface that is hinted to be completely
3138 * transparent. This is only used to tell when the layer has no visible
3139 * non-transparent regions and can be removed from the layer list. It
3140 * does not affect the visibleRegion of this layer or any layers
3141 * beneath it. The hint may not be correct if apps don't respect the
3142 * SurfaceView restrictions (which, sadly, some don't).
3143 */
3144 Region transparentRegion;
3145
Mathias Agopianab028732010-03-16 16:41:46 -07003146
3147 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003148 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003149 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003150 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003151
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003152 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003153 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003154 if (!visibleRegion.isEmpty()) {
3155 // Remove the transparent area from the visible region
3156 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003157 if (tr.preserveRects()) {
3158 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003159 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003160 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003161 // transformation too complex, can't do the
3162 // transparent region optimization.
3163 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003164 }
Mathias Agopianab028732010-03-16 16:41:46 -07003165 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003166
Mathias Agopianab028732010-03-16 16:41:46 -07003167 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003168 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003169 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003170 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003171 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003172 // the opaque region is the layer's footprint
3173 opaqueRegion = visibleRegion;
3174 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003175 }
3176 }
3177
Robert Carre5f4f692018-01-12 13:12:28 -08003178 if (visibleRegion.isEmpty()) {
3179 layer->clearVisibilityRegions();
3180 return;
3181 }
3182
Mathias Agopianab028732010-03-16 16:41:46 -07003183 // Clip the covered region to the visible region
3184 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3185
3186 // Update aboveCoveredLayers for next (lower) layer
3187 aboveCoveredLayers.orSelf(visibleRegion);
3188
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003189 // subtract the opaque region covered by the layers above us
3190 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003191
3192 // compute this layer's dirty region
3193 if (layer->contentDirty) {
3194 // we need to invalidate the whole region
3195 dirty = visibleRegion;
3196 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003197 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003198 layer->contentDirty = false;
3199 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003200 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003201 * the exposed region consists of two components:
3202 * 1) what's VISIBLE now and was COVERED before
3203 * 2) what's EXPOSED now less what was EXPOSED before
3204 *
3205 * note that (1) is conservative, we start with the whole
3206 * visible region but only keep what used to be covered by
3207 * something -- which mean it may have been exposed.
3208 *
3209 * (2) handles areas that were not covered by anything but got
3210 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003211 */
Mathias Agopianab028732010-03-16 16:41:46 -07003212 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003213 const Region oldVisibleRegion = layer->visibleRegion;
3214 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003215 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3216 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003217 }
3218 dirty.subtractSelf(aboveOpaqueLayers);
3219
3220 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003221 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003222
Mathias Agopianab028732010-03-16 16:41:46 -07003223 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003224 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003225
Jesse Halla8026d22012-09-25 13:25:04 -07003226 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003227 layer->setVisibleRegion(visibleRegion);
3228 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003229 layer->setVisibleNonTransparentRegion(
3230 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003231 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003232
Mathias Agopian87baae12012-07-31 12:38:26 -07003233 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003234}
3235
Chia-I Wuab0c3192017-08-01 11:29:00 -07003236void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003237 for (const auto& [token, displayDevice] : mDisplays) {
3238 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003239 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003240 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003241 }
3242 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003243}
3244
Daniel Solomon42d04562019-01-20 21:03:19 -08003245void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3246 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3247 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3248 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3249 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3250 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3251 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3252 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3253 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3254 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3255 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3256 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3257 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3258}
3259
Dan Stoza6b9454d2014-11-07 16:00:59 -08003260bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003261{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003262 ALOGV("handlePageFlip");
3263
Brian Andersond6927fb2016-07-23 23:37:30 -07003264 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003265
Mathias Agopian4fec8732012-06-29 14:12:52 -07003266 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003267 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003268 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003269
3270 // Store the set of layers that need updates. This set must not change as
3271 // buffers are being latched, as this could result in a deadlock.
3272 // Example: Two producers share the same command stream and:
3273 // 1.) Layer 0 is latched
3274 // 2.) Layer 0 gets a new frame
3275 // 2.) Layer 1 gets a new frame
3276 // 3.) Layer 1 is latched.
3277 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3278 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003279 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003280 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003281 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003282 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3283 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003284 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003285 } else {
3286 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003287 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003288 } else {
3289 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003290 }
Robert Carr2047fae2016-11-28 14:09:09 -08003291 });
3292
Lloyd Piquef2c79392018-12-20 16:23:33 -08003293 if (!mLayersWithQueuedFrames.empty()) {
3294 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3295 // writes to Layer current state. See also b/119481871
3296 Mutex::Autolock lock(mStateLock);
3297
3298 for (auto& layer : mLayersWithQueuedFrames) {
3299 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3300 layer->useSurfaceDamage();
3301 invalidateLayerStack(layer, dirty);
3302 if (layer->isBufferLatched()) {
3303 newDataLatched = true;
3304 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003305 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003306 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003307
Alec Mouri86770e52018-09-24 22:40:58 +00003308 // Clear the renderengine fence here...
3309 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3310 // clear instead of sp::clear.
3311 getBE().flushFence = Fence::NO_FENCE;
3312
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003313 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003314
Vishnu Nairde19f852018-12-18 16:11:53 -08003315 if (visibleRegions) {
3316 // Update input window info if the layer receives its first buffer.
3317 updateInputWindows();
3318 }
3319
Dan Stoza6b9454d2014-11-07 16:00:59 -08003320 // If we will need to wake up at some time in the future to deal with a
3321 // queued frame that shouldn't be displayed during this vsync period, wake
3322 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003323 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003324 signalLayerUpdate();
3325 }
3326
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003327 // enter boot animation on first buffer latch
3328 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3329 ALOGI("Enter boot animation");
3330 mBootStage = BootStage::BOOTANIMATION;
3331 }
3332
Dan Stoza6b9454d2014-11-07 16:00:59 -08003333 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003334 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003335}
3336
Mathias Agopianad456f92011-01-13 17:53:01 -08003337void SurfaceFlinger::invalidateHwcGeometry()
3338{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003339 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003340}
3341
Lloyd Pique32cbe282018-10-19 13:09:22 -07003342void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003343 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003344 auto display = displayDevice->getCompositionDisplay();
3345
Dan Stoza71433162014-02-04 16:22:36 -08003346 // We only need to actually compose the display if:
3347 // 1) It is being handled by hardware composer, which may need this to
3348 // keep its virtual display state machine in sync, or
3349 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003350 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003351 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003352 return;
3353 }
3354
Dan Stoza9e56aa02015-11-02 13:00:03 -08003355 ALOGV("doDisplayComposition");
Alec Mouri79108df2019-02-04 19:33:44 +00003356 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003357
3358 // swap buffers (presentation)
Alec Mouri79108df2019-02-04 19:33:44 +00003359 display->getRenderSurface()->queueBuffer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003360}
3361
Alec Mouri79108df2019-02-04 19:33:44 +00003362bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003363 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003364
Lloyd Pique32cbe282018-10-19 13:09:22 -07003365 auto display = displayDevice->getCompositionDisplay();
3366 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003367 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003368
3369 const Region bounds(displayState.bounds);
3370 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003371 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003372 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003373
Peiyong Lind3788632018-09-18 16:01:31 -07003374 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003375 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003376
Alec Mouri79108df2019-02-04 19:33:44 +00003377 // Framebuffer will live in this scope for GPU composition.
3378 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003379
Dan Stoza9e56aa02015-11-02 13:00:03 -08003380 if (hasClientComposition) {
3381 ALOGV("hasClientComposition");
3382
Alec Mouri79108df2019-02-04 19:33:44 +00003383 sp<GraphicBuffer> 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 Mouri79108df2019-02-04 19:33:44 +00003392 // Bind the framebuffer in this scope.
3393 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3394 buf->getNativeBuffer());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003395
Alec Mouri79108df2019-02-04 19:33:44 +00003396 if (fbo->getStatus() != NO_ERROR) {
3397 ALOGW("Binding buffer for display [%s] failed with status: %d",
3398 displayDevice->getDisplayName().c_str(), fbo->getStatus());
3399 return false;
3400 }
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003401
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003402 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003403 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003404 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003405 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003406 }
Alec Mouri79108df2019-02-04 19:33:44 +00003407 getRenderEngine().setOutputDataSpace(outputDataspace);
3408 getRenderEngine().setDisplayMaxLuminance(
3409 profile->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003410
Lloyd Pique441d5042018-10-18 16:49:51 -07003411 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003412 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003413 getHwComposer()
3414 .hasDisplayCapability(displayId,
3415 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003416
Peiyong Lind3788632018-09-18 16:01:31 -07003417 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003418 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3419 if (applyColorMatrix) {
Alec Mouri79108df2019-02-04 19:33:44 +00003420 colorMatrix = mDrawingState.colorMatrix;
3421 }
3422
3423 display->getRenderSurface()->setViewportAndProjection();
3424
3425 // Never touch the framebuffer if we don't have any framebuffer layers
3426 if (hasDeviceComposition) {
3427 // when using overlays, we assume a fully transparent framebuffer
3428 // NOTE: we could reduce how much we need to clear, for instance
3429 // remove where there are opaque FB layers. however, on some
3430 // GPUs doing a "clean slate" clear might be more efficient.
3431 // We'll revisit later if needed.
3432 getRenderEngine().clearWithColor(0, 0, 0, 0);
3433 } else {
3434 // we start with the whole screen area and remove the scissor part
3435 // we're left with the letterbox region
3436 // (common case is that letterbox ends-up being empty)
3437 const Region letterbox = bounds.subtract(displayState.scissor);
3438
3439 // compute the area to clear
3440 const Region region = displayState.undefinedRegion.merge(letterbox);
3441
3442 // screen is already cleared here
3443 if (!region.isEmpty()) {
3444 // can happen with SurfaceView
3445 drawWormhole(region);
3446 }
3447 }
3448
3449 const Rect& bounds = displayState.bounds;
3450 const Rect& scissor = displayState.scissor;
3451 if (scissor != bounds) {
3452 // scissor doesn't match the screen's dimensions, so we
3453 // need to clear everything outside of it and enable
3454 // the GL scissor so we don't draw anything where we shouldn't
3455
3456 // enable scissor for this frame
3457 getRenderEngine().setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003458 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003459 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003460
Mathias Agopian85d751c2012-08-29 16:59:24 -07003461 /*
3462 * and then, render the layers targeted at the framebuffer
3463 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003464
Dan Stoza9e56aa02015-11-02 13:00:03 -08003465 ALOGV("Rendering client layers");
Alec Mouri79108df2019-02-04 19:33:44 +00003466 const ui::Transform& displayTransform = displayState.transform;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003467 bool firstLayer = true;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003468 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mouri79108df2019-02-04 19:33:44 +00003469 const Region clip(bounds.intersect(displayTransform.transform(layer->visibleRegion)));
David Sodmanc1498e62018-09-12 14:36:26 -07003470 ALOGV("Layer: %s", layer->getName().string());
3471 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003472 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003473 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003474 case HWC2::Composition::Cursor:
3475 case HWC2::Composition::Device:
3476 case HWC2::Composition::Sideband:
3477 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003478 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003479 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003480 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003481 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003482 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003483 // never clear the very first layer since we're
3484 // guaranteed the FB is already cleared
Alec Mouri79108df2019-02-04 19:33:44 +00003485 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003486 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003487 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003488 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003489 case HWC2::Composition::Client: {
Alec Mouri79108df2019-02-04 19:33:44 +00003490 if (layer->hasColorTransform()) {
3491 mat4 tmpMatrix;
3492 if (applyColorMatrix) {
3493 tmpMatrix = mDrawingState.colorMatrix;
3494 }
3495 tmpMatrix *= layer->getColorTransform();
3496 getRenderEngine().setColorTransform(tmpMatrix);
3497 } else {
3498 getRenderEngine().setColorTransform(colorMatrix);
Peiyong Lind3788632018-09-18 16:01:31 -07003499 }
Alec Mouri79108df2019-02-04 19:33:44 +00003500 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003501 break;
3502 }
3503 default:
3504 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003505 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003506 } else {
3507 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003508 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003509 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003510 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003511
Alec Mouri79108df2019-02-04 19:33:44 +00003512 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003513 if (hasClientComposition) {
Alec Mouri79108df2019-02-04 19:33:44 +00003514 getRenderEngine().setColorTransform(mat4());
3515 getRenderEngine().disableScissor();
3516 display->getRenderSurface()->finishBuffer();
3517 // Clear out error flags here so that we don't wait until next
3518 // composition to log.
3519 getRenderEngine().checkErrors();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003520 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003521 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003522}
3523
Chia-I Wu28e3a252018-09-07 12:05:02 -07003524void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003525 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003526 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003527}
3528
Dan Stoza7d89d062015-04-30 13:29:25 -07003529status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003530 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003531 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003532 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003533 const sp<Layer>& parent,
3534 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003535{
Dan Stoza7d89d062015-04-30 13:29:25 -07003536 // add this layer to the current state list
3537 {
3538 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003539 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003540 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3541 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003542 return NO_MEMORY;
3543 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003544 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003545 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003546 } else if (parent == nullptr) {
3547 lbc->onRemovedFromCurrentState();
3548 } else if (parent->isRemovedFromCurrentState()) {
3549 parent->addChild(lbc);
3550 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003551 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003552 parent->addChild(lbc);
3553 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003554
Yiwei Zhang243b3782018-05-15 17:40:04 -07003555 if (gbc != nullptr) {
3556 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3557 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3558 mMaxGraphicBufferProducerListSize,
3559 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3560 mGraphicBufferProducerList.size(),
3561 mMaxGraphicBufferProducerListSize, mNumLayers);
3562 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003563 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003564 }
3565
Mathias Agopian96f08192010-06-02 23:28:45 -07003566 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003567 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003568
Dan Stoza7d89d062015-04-30 13:29:25 -07003569 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003570}
3571
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003572uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003573 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003574}
3575
Mathias Agopian3f844832013-08-07 21:24:32 -07003576uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003577 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003578}
3579
Mathias Agopian3f844832013-08-07 21:24:32 -07003580uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003581 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003582}
3583
3584uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003585 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003586 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003587 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003588 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003589 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003590 }
3591 return old;
3592}
3593
Marissa Wall713b63f2018-10-17 15:42:43 -07003594bool SurfaceFlinger::flushTransactionQueues() {
3595 Mutex::Autolock _l(mStateLock);
3596 auto it = mTransactionQueues.begin();
3597 while (it != mTransactionQueues.end()) {
3598 auto& [applyToken, transactionQueue] = *it;
3599
3600 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003601 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3602 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003603 break;
3604 }
chaviw273171b2018-12-26 11:46:30 -08003605 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003606 transactionQueue.pop();
3607 }
3608
3609 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3610 }
3611 return mTransactionQueues.empty();
3612}
3613
chaviwca27f252018-02-06 16:46:39 -08003614bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3615 for (const ComposerState& state : states) {
3616 // Here we need to check that the interface we're given is indeed
3617 // one of our own. A malicious client could give us a nullptr
3618 // IInterface, or one of its own or even one of our own but a
3619 // different type. All these situations would cause us to crash.
3620 if (state.client == nullptr) {
3621 return true;
3622 }
3623
3624 sp<IBinder> binder = IInterface::asBinder(state.client);
3625 if (binder == nullptr) {
3626 return true;
3627 }
3628
3629 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3630 return true;
3631 }
3632 }
3633 return false;
3634}
3635
Marissa Wall17b4e452018-12-26 16:32:34 -08003636bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3637 const Vector<ComposerState>& states) {
3638 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3639 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3640 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3641 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3642 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3643 return false;
3644 }
3645
Marissa Wall713b63f2018-10-17 15:42:43 -07003646 for (const ComposerState& state : states) {
3647 const layer_state_t& s = state.state;
3648 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3649 continue;
3650 }
3651 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003652 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003653 }
3654 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003655 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003656}
3657
3658void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3659 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003660 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003661 const InputWindowCommands& inputWindowCommands,
3662 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003663 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003664 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003665
chaviwca27f252018-02-06 16:46:39 -08003666 if (containsAnyInvalidClientState(states)) {
3667 return;
3668 }
3669
Marissa Wall713b63f2018-10-17 15:42:43 -07003670 // If its TransactionQueue already has a pending TransactionState or if it is pending
3671 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003672 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3673 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003674 setTransactionFlags(eTransactionNeeded);
3675 return;
3676 }
3677
chaviw273171b2018-12-26 11:46:30 -08003678 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003679}
3680
3681void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003682 const Vector<DisplayState>& displays, uint32_t flags,
3683 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003684 uint32_t transactionFlags = 0;
3685
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003686 if (flags & eAnimation) {
3687 // For window updates that are part of an animation we must wait for
3688 // previous animation "frames" to be handled.
3689 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003690 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003691 if (CC_UNLIKELY(err != NO_ERROR)) {
3692 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003693 // caller after a few seconds.
3694 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3695 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003696 mAnimTransactionPending = false;
3697 break;
3698 }
3699 }
3700 }
3701
chaviwca27f252018-02-06 16:46:39 -08003702 for (const DisplayState& display : displays) {
3703 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003704 }
3705
Marissa Walle2ffb422018-10-12 11:33:52 -07003706 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003707 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003708 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003709 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003710 // If the state doesn't require a traversal and there are callbacks, send them now
3711 if (!(clientStateFlags & eTraversalNeeded)) {
3712 mTransactionCompletedThread.sendCallbacks();
3713 }
3714 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003715
chaviw273171b2018-12-26 11:46:30 -08003716 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3717
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003718 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3719 // anyway. This can be used as a flush mechanism for previous async transactions.
3720 // Empty animation transaction can be used to simulate back-pressure, so also force a
3721 // transaction for empty animation transactions.
3722 if (transactionFlags == 0 &&
3723 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003724 transactionFlags = eTransactionNeeded;
3725 }
3726
Mathias Agopian386aa982011-11-07 21:58:03 -08003727 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003728 if (mInterceptor->isEnabled()) {
3729 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003730 }
Irvel468051e2016-06-13 16:44:44 -07003731
Mathias Agopian386aa982011-11-07 21:58:03 -08003732 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003733 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3734 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003735 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003736
3737 // if this is a synchronous transaction, wait for it to take effect
3738 // before returning.
3739 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003740 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003741 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003742 if (flags & eAnimation) {
3743 mAnimTransactionPending = true;
3744 }
3745 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003746 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3747 if (CC_UNLIKELY(err != NO_ERROR)) {
3748 // just in case something goes wrong in SF, return to the
3749 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003750 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3751 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003752 break;
3753 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003754 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003755 }
3756}
3757
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003758uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3759 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3760 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003761
Mathias Agopiane57f2922012-08-09 16:29:12 -07003762 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003763 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3764
3765 const uint32_t what = s.what;
3766 if (what & DisplayState::eSurfaceChanged) {
3767 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3768 state.surface = s.surface;
3769 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003770 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003771 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003772 if (what & DisplayState::eLayerStackChanged) {
3773 if (state.layerStack != s.layerStack) {
3774 state.layerStack = s.layerStack;
3775 flags |= eDisplayTransactionNeeded;
3776 }
3777 }
3778 if (what & DisplayState::eDisplayProjectionChanged) {
3779 if (state.orientation != s.orientation) {
3780 state.orientation = s.orientation;
3781 flags |= eDisplayTransactionNeeded;
3782 }
3783 if (state.frame != s.frame) {
3784 state.frame = s.frame;
3785 flags |= eDisplayTransactionNeeded;
3786 }
3787 if (state.viewport != s.viewport) {
3788 state.viewport = s.viewport;
3789 flags |= eDisplayTransactionNeeded;
3790 }
3791 }
3792 if (what & DisplayState::eDisplaySizeChanged) {
3793 if (state.width != s.width) {
3794 state.width = s.width;
3795 flags |= eDisplayTransactionNeeded;
3796 }
3797 if (state.height != s.height) {
3798 state.height = s.height;
3799 flags |= eDisplayTransactionNeeded;
3800 }
3801 }
3802
Mathias Agopiane57f2922012-08-09 16:29:12 -07003803 return flags;
3804}
3805
Robert Carrd4ae7f32018-06-07 16:10:57 -07003806bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3807 IPCThreadState* ipc = IPCThreadState::self();
3808 const int pid = ipc->getCallingPid();
3809 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003810 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003811 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003812 return false;
3813 }
3814 return true;
3815}
3816
chaviwca27f252018-02-06 16:46:39 -08003817uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3818 const layer_state_t& s = composerState.state;
3819 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3820
Mathias Agopian13127d82013-03-05 17:47:11 -08003821 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003822 if (layer == nullptr) {
3823 return 0;
3824 }
3825
chaviw8b3871a2017-11-01 17:41:01 -07003826 uint32_t flags = 0;
3827
Garfield Tan8a3083e2018-12-03 13:21:07 -08003828 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003829 bool geometryAppliesWithResize =
3830 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003831
3832 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3833 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003834 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003835 layer->pushPendingState();
3836 }
3837
chaviw8b3871a2017-11-01 17:41:01 -07003838 if (what & layer_state_t::ePositionChanged) {
3839 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3840 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003841 }
chaviw8b3871a2017-11-01 17:41:01 -07003842 }
3843 if (what & layer_state_t::eLayerChanged) {
3844 // NOTE: index needs to be calculated before we update the state
3845 const auto& p = layer->getParent();
3846 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003847 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003848 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003849 mCurrentState.layersSortedByZ.removeAt(idx);
3850 mCurrentState.layersSortedByZ.add(layer);
3851 // we need traversal (state changed)
3852 // AND transaction (list changed)
3853 flags |= eTransactionNeeded|eTraversalNeeded;
3854 }
chaviw8b3871a2017-11-01 17:41:01 -07003855 } else {
3856 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003857 flags |= eTransactionNeeded|eTraversalNeeded;
3858 }
3859 }
chaviw8b3871a2017-11-01 17:41:01 -07003860 }
3861 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003862 // NOTE: index needs to be calculated before we update the state
3863 const auto& p = layer->getParent();
3864 if (p == nullptr) {
3865 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3866 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3867 mCurrentState.layersSortedByZ.removeAt(idx);
3868 mCurrentState.layersSortedByZ.add(layer);
3869 // we need traversal (state changed)
3870 // AND transaction (list changed)
3871 flags |= eTransactionNeeded|eTraversalNeeded;
3872 }
3873 } else {
3874 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3875 flags |= eTransactionNeeded|eTraversalNeeded;
3876 }
chaviw8b3871a2017-11-01 17:41:01 -07003877 }
3878 }
3879 if (what & layer_state_t::eSizeChanged) {
3880 if (layer->setSize(s.w, s.h)) {
3881 flags |= eTraversalNeeded;
3882 }
3883 }
3884 if (what & layer_state_t::eAlphaChanged) {
3885 if (layer->setAlpha(s.alpha))
3886 flags |= eTraversalNeeded;
3887 }
3888 if (what & layer_state_t::eColorChanged) {
3889 if (layer->setColor(s.color))
3890 flags |= eTraversalNeeded;
3891 }
Peiyong Lind3788632018-09-18 16:01:31 -07003892 if (what & layer_state_t::eColorTransformChanged) {
3893 if (layer->setColorTransform(s.colorTransform)) {
3894 flags |= eTraversalNeeded;
3895 }
3896 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003897 if (what & layer_state_t::eBackgroundColorChanged) {
3898 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3899 flags |= eTraversalNeeded;
3900 }
3901 }
chaviw8b3871a2017-11-01 17:41:01 -07003902 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003903 // TODO: b/109894387
3904 //
3905 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3906 // rotation. To see the problem observe that if we have a square parent, and a child
3907 // of the same size, then we rotate the child 45 degrees around it's center, the child
3908 // must now be cropped to a non rectangular 8 sided region.
3909 //
3910 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3911 // private API, and the WindowManager only uses rotation in one case, which is on a top
3912 // level layer in which cropping is not an issue.
3913 //
3914 // However given that abuse of rotation matrices could lead to surfaces extending outside
3915 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3916 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3917 // transformations.
3918 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003919 flags |= eTraversalNeeded;
3920 }
3921 if (what & layer_state_t::eTransparentRegionChanged) {
3922 if (layer->setTransparentRegionHint(s.transparentRegion))
3923 flags |= eTraversalNeeded;
3924 }
3925 if (what & layer_state_t::eFlagsChanged) {
3926 if (layer->setFlags(s.flags, s.mask))
3927 flags |= eTraversalNeeded;
3928 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003929 if (what & layer_state_t::eCropChanged_legacy) {
3930 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003931 flags |= eTraversalNeeded;
3932 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003933 if (what & layer_state_t::eCornerRadiusChanged) {
3934 if (layer->setCornerRadius(s.cornerRadius))
3935 flags |= eTraversalNeeded;
3936 }
chaviw8b3871a2017-11-01 17:41:01 -07003937 if (what & layer_state_t::eLayerStackChanged) {
3938 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3939 // We only allow setting layer stacks for top level layers,
3940 // everything else inherits layer stack from its parent.
3941 if (layer->hasParent()) {
3942 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3943 layer->getName().string());
3944 } else if (idx < 0) {
3945 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3946 "that also does not appear in the top level layer list. Something"
3947 " has gone wrong.", layer->getName().string());
3948 } else if (layer->setLayerStack(s.layerStack)) {
3949 mCurrentState.layersSortedByZ.removeAt(idx);
3950 mCurrentState.layersSortedByZ.add(layer);
3951 // we need traversal (state changed)
3952 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003953 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003954 }
3955 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003956 if (what & layer_state_t::eDeferTransaction_legacy) {
3957 if (s.barrierHandle_legacy != nullptr) {
3958 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3959 } else if (s.barrierGbp_legacy != nullptr) {
3960 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003961 if (authenticateSurfaceTextureLocked(gbp)) {
3962 const auto& otherLayer =
3963 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003964 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003965 } else {
3966 ALOGE("Attempt to defer transaction to to an"
3967 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003968 }
3969 }
chaviw8b3871a2017-11-01 17:41:01 -07003970 // We don't trigger a traversal here because if no other state is
3971 // changed, we don't want this to cause any more work
3972 }
3973 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003974 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003975 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003976 if (!hadParent) {
3977 mCurrentState.layersSortedByZ.remove(layer);
3978 }
chaviw8b3871a2017-11-01 17:41:01 -07003979 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003980 }
chaviw8b3871a2017-11-01 17:41:01 -07003981 }
3982 if (what & layer_state_t::eReparentChildren) {
3983 if (layer->reparentChildren(s.reparentHandle)) {
3984 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003985 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003986 }
chaviw8b3871a2017-11-01 17:41:01 -07003987 if (what & layer_state_t::eDetachChildren) {
3988 layer->detachChildren();
3989 }
3990 if (what & layer_state_t::eOverrideScalingModeChanged) {
3991 layer->setOverrideScalingMode(s.overrideScalingMode);
3992 // We don't trigger a traversal here because if no other state is
3993 // changed, we don't want this to cause any more work
3994 }
Marissa Wall61c58622018-07-18 10:12:20 -07003995 if (what & layer_state_t::eTransformChanged) {
3996 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3997 }
3998 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3999 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4000 flags |= eTraversalNeeded;
4001 }
4002 if (what & layer_state_t::eCropChanged) {
4003 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4004 }
Marissa Wall861616d2018-10-22 12:52:23 -07004005 if (what & layer_state_t::eFrameChanged) {
4006 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4007 }
Marissa Wall61c58622018-07-18 10:12:20 -07004008 if (what & layer_state_t::eBufferChanged) {
4009 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
4010 }
4011 if (what & layer_state_t::eAcquireFenceChanged) {
4012 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4013 }
4014 if (what & layer_state_t::eDataspaceChanged) {
4015 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4016 }
4017 if (what & layer_state_t::eHdrMetadataChanged) {
4018 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4019 }
4020 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4021 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4022 }
4023 if (what & layer_state_t::eApiChanged) {
4024 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4025 }
4026 if (what & layer_state_t::eSidebandStreamChanged) {
4027 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4028 }
Robert Carr720e5062018-07-30 17:45:14 -07004029 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004030 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
4031 layer->setInputInfo(s.inputInfo);
4032 flags |= eTraversalNeeded;
4033 } else {
4034 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4035 }
Robert Carr720e5062018-07-30 17:45:14 -07004036 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004037 if (what & layer_state_t::eMetadataChanged) {
4038 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4039 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004040 std::vector<sp<CallbackHandle>> callbackHandles;
4041 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
4042 mTransactionCompletedThread.run();
4043 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
4044 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4045 }
4046 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004047 if (what & layer_state_t::eCachedBufferChanged) {
4048 sp<GraphicBuffer> buffer =
4049 mBufferStateLayerCache.get(s.cachedBuffer.token, s.cachedBuffer.bufferId);
4050 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4051 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004052 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4053 // Do not put anything that updates layer state or modifies flags after
4054 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004055 return flags;
4056}
4057
chaviw273171b2018-12-26 11:46:30 -08004058uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4059 uint32_t flags = 0;
4060 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4061 flags |= eTraversalNeeded;
4062 }
4063
4064 mInputWindowCommands.merge(inputWindowCommands);
4065 return flags;
4066}
4067
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004068status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4069 uint32_t h, PixelFormat format, uint32_t flags,
4070 LayerMetadata metadata, sp<IBinder>* handle,
4071 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004072 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004073 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004074 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004075 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004076 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004077
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004078 status_t result = NO_ERROR;
4079
4080 sp<Layer> layer;
4081
Cody Northropbc755282017-03-31 12:00:08 -06004082 String8 uniqueName = getUniqueLayerName(name);
4083
Mathias Agopian3165cc22012-08-08 19:42:09 -07004084 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004085 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004086 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4087 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004088
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004089 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004090 case ISurfaceComposerClient::eFXSurfaceBufferState:
4091 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4092 break;
chaviw13fdc492017-06-27 12:40:18 -07004093 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004094 // check if buffer size is set for color layer.
4095 if (w > 0 || h > 0) {
4096 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4097 int(w), int(h));
4098 return BAD_VALUE;
4099 }
4100
chaviw13fdc492017-06-27 12:40:18 -07004101 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004102 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004103 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004104 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004105 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004106 // check if buffer size is set for container layer.
4107 if (w > 0 || h > 0) {
4108 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4109 int(w), int(h));
4110 return BAD_VALUE;
4111 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004112 result = createContainerLayer(client,
4113 uniqueName, w, h, flags,
4114 handle, &layer);
4115 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004116 default:
4117 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004118 break;
4119 }
4120
Dan Stoza7d89d062015-04-30 13:29:25 -07004121 if (result != NO_ERROR) {
4122 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004123 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004124
Chia-I Wuab0c3192017-08-01 11:29:00 -07004125 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4126 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004127 if (metadata.has(METADATA_WINDOW_TYPE)) {
4128 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4129 if (windowType == 441731) {
4130 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4131 layer->setPrimaryDisplayOnly();
4132 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004133 }
4134
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004135 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004136
Robert Carrb89ea9d2018-12-10 13:01:14 -08004137 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4138 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4139 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004140 if (result != NO_ERROR) {
4141 return result;
4142 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004143 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004144
4145 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004146 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004147}
4148
Cody Northropbc755282017-03-31 12:00:08 -06004149String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4150{
4151 bool matchFound = true;
4152 uint32_t dupeCounter = 0;
4153
4154 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4155 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4156
Dan Stoza436ccf32018-06-21 12:10:12 -07004157 // Grab the state lock since we're accessing mCurrentState
4158 Mutex::Autolock lock(mStateLock);
4159
Cody Northropbc755282017-03-31 12:00:08 -06004160 // Loop over layers until we're sure there is no matching name
4161 while (matchFound) {
4162 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004163 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004164 if (layer->getName() == uniqueName) {
4165 matchFound = true;
4166 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4167 }
4168 });
4169 }
4170
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004171 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4172 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004173
4174 return uniqueName;
4175}
4176
Marissa Wallfd668622018-05-10 10:21:13 -07004177status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4178 uint32_t w, uint32_t h, uint32_t flags,
4179 PixelFormat& format, sp<IBinder>* handle,
4180 sp<IGraphicBufferProducer>* gbp,
4181 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004182 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004183 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004184 case PIXEL_FORMAT_TRANSPARENT:
4185 case PIXEL_FORMAT_TRANSLUCENT:
4186 format = PIXEL_FORMAT_RGBA_8888;
4187 break;
4188 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004189 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004190 break;
4191 }
4192
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004193 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004194 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004195 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004196 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004197 *handle = layer->getHandle();
4198 *gbp = layer->getProducer();
4199 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004200 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004201
Marissa Wallfd668622018-05-10 10:21:13 -07004202 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004203 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004204}
4205
Marissa Wall61c58622018-07-18 10:12:20 -07004206status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4207 uint32_t w, uint32_t h, uint32_t flags,
4208 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004209 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004210 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004211 *handle = layer->getHandle();
4212 *outLayer = layer;
4213
4214 return NO_ERROR;
4215}
4216
chaviw13fdc492017-06-27 12:40:18 -07004217status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004218 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004219 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004220{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004221 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004222 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004223 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004224}
4225
Robert Carr6b3f6c52018-08-13 13:05:17 -07004226status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4227 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4228 sp<IBinder>* handle, sp<Layer>* outLayer)
4229{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004230 *outLayer =
4231 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004232 *handle = (*outLayer)->getHandle();
4233 return NO_ERROR;
4234}
4235
4236
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004237void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004238 mLayersPendingRemoval.add(layer);
4239 mLayersRemoved = true;
4240 setTransactionFlags(eTransactionNeeded);
4241}
4242
Robert Carr695d5282018-12-18 15:27:58 -08004243void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004244{
Robert Carr2e102c92018-10-23 12:11:15 -07004245 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004246 // If a layer has a parent, we allow it to out-live it's handle
4247 // with the idea that the parent holds a reference and will eventually
4248 // be cleaned up. However no one cleans up the top-level so we do so
4249 // here.
4250 if (layer->getParent() == nullptr) {
4251 mCurrentState.layersSortedByZ.remove(layer);
4252 }
4253 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004254 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004255}
4256
Mathias Agopianb60314a2012-04-10 22:09:54 -07004257// ---------------------------------------------------------------------------
4258
Andy McFadden13a082e2012-08-24 10:16:42 -07004259void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004260 const auto display = getDefaultDisplayDeviceLocked();
4261 if (!display) return;
4262
4263 const sp<IBinder> token = display->getDisplayToken().promote();
4264 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004265
Jesse Hall01e29052013-02-19 16:13:35 -08004266 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004267 Vector<ComposerState> state;
4268 Vector<DisplayState> displays;
4269 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004270 d.what = DisplayState::eDisplayProjectionChanged |
4271 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004272 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004273 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004274 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004275 d.frame.makeInvalid();
4276 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004277 d.width = 0;
4278 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004279 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004280 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004281
Dominik Laskowskie9774092018-12-11 10:04:24 -08004282 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004283
Dominik Laskowski83b88212018-12-11 13:34:06 -08004284 const nsecs_t vsyncPeriod = getVsyncPeriod();
4285 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004286
Brian Andersond0010582017-03-07 13:20:31 -08004287 // Use phase of 0 since phase is not known.
4288 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004289 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004290 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004291}
4292
4293void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004294 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004295 postMessageAsync(
4296 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004297}
4298
Dominik Laskowskie9774092018-12-11 10:04:24 -08004299void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004300 if (display->isVirtual()) {
4301 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004302 return;
4303 }
4304
Dominik Laskowski075d3172018-05-24 15:50:06 -07004305 const auto displayId = display->getId();
4306 LOG_ALWAYS_FATAL_IF(!displayId);
4307
Dominik Laskowski34157762018-10-31 13:07:19 -07004308 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004309
4310 int currentMode = display->getPowerMode();
4311 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004312 return;
4313 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004314
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004315 display->setPowerMode(mode);
4316
Lloyd Pique4dccc412018-01-22 17:21:36 -08004317 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004318 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004319 }
4320
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004321 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004322 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004323 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004324 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004325 if (mUseScheduler) {
4326 mScheduler->onScreenAcquired(mAppConnectionHandle);
4327 } else {
4328 mEventThread->onScreenAcquired();
4329 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004330 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004331 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004332
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004333 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004334 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004335 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004336
4337 struct sched_param param = {0};
4338 param.sched_priority = 1;
4339 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4340 ALOGW("Couldn't set SCHED_FIFO on display on");
4341 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004342 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004343 // Turn off the display
4344 struct sched_param param = {0};
4345 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4346 ALOGW("Couldn't set SCHED_OTHER on display off");
4347 }
4348
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004349 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004350 if (mUseScheduler) {
4351 mScheduler->disableHardwareVsync(true);
4352 } else {
4353 disableHardwareVsync(true); // also cancels any in-progress resync
4354 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004355 if (mUseScheduler) {
4356 mScheduler->onScreenReleased(mAppConnectionHandle);
4357 } else {
4358 mEventThread->onScreenReleased();
4359 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004360 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004361
Dominik Laskowski075d3172018-05-24 15:50:06 -07004362 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004363 mVisibleRegionsDirty = true;
4364 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004365 } else if (mode == HWC_POWER_MODE_DOZE ||
4366 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004367 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004368 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004369 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004370 if (mUseScheduler) {
4371 mScheduler->onScreenAcquired(mAppConnectionHandle);
4372 } else {
4373 mEventThread->onScreenAcquired();
4374 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004375 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004376 }
4377 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4378 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004379 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004380 if (mUseScheduler) {
4381 mScheduler->disableHardwareVsync(true);
4382 } else {
4383 disableHardwareVsync(true); // also cancels any in-progress resync
4384 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004385 if (mUseScheduler) {
4386 mScheduler->onScreenReleased(mAppConnectionHandle);
4387 } else {
4388 mEventThread->onScreenReleased();
4389 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004390 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004391 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004392 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004393 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004394 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004395 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004396
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004397 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004398 mTimeStats->setPowerMode(mode);
Ana Krulec4593b692019-01-11 22:07:25 -08004399 if (mUseScheduler && mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004400 // Update refresh rate stats.
4401 mRefreshRateStats->setPowerMode(mode);
4402 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004403 }
4404
Dominik Laskowski34157762018-10-31 13:07:19 -07004405 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004406}
4407
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004408void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004409 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004410 const auto display = getDisplayDevice(displayToken);
4411 if (!display) {
4412 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4413 displayToken.get());
4414 } else if (display->isVirtual()) {
4415 ALOGW("Attempt to set power mode %d for virtual display", mode);
4416 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004417 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004418 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004419 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004420}
4421
4422// ---------------------------------------------------------------------------
4423
Dominik Laskowskic2867142019-01-21 11:33:38 -08004424status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4425 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004426 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004427
Mathias Agopianbd115332013-04-18 16:41:04 -07004428 IPCThreadState* ipc = IPCThreadState::self();
4429 const int pid = ipc->getCallingPid();
4430 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004431
Mathias Agopianbd115332013-04-18 16:41:04 -07004432 if ((uid != AID_SHELL) &&
4433 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004434 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4435 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004436 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004437 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004438 // (this would indicate SF is stuck, but we want to be able to
4439 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004440 status_t err = mStateLock.timedLock(s2ns(1));
4441 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004442 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004443 StringAppendF(&result,
4444 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4445 "(no locks held)\n",
4446 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004447 }
4448
Dominik Laskowskic2867142019-01-21 11:33:38 -08004449 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004450
Dominik Laskowskic2867142019-01-21 11:33:38 -08004451 static const std::unordered_map<std::string, Dumper> dumpers = {
4452 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4453 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4454 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
4455 {"--dispsync"s, dumper([this](std::string& s) { mPrimaryDispSync->dump(s); })},
4456 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4457 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
4458 {"--frame-composition"s, dumper(&SurfaceFlinger::dumpFrameCompositionInfo)},
4459 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4460 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4461 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4462 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4463 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4464 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004465 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004466 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4467 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004468
Dominik Laskowskic2867142019-01-21 11:33:38 -08004469 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004470
Dominik Laskowskic2867142019-01-21 11:33:38 -08004471 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4472 (it->second)(args, asProto, result);
4473 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004474 if (asProto) {
4475 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4476 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4477 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004478 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004479 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004480 }
4481
Mathias Agopian9795c422009-08-26 16:36:26 -07004482 if (locked) {
4483 mStateLock.unlock();
4484 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004485 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004486 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004487 return NO_ERROR;
4488}
4489
Dominik Laskowskic2867142019-01-21 11:33:38 -08004490void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004491 mCurrentState.traverseInZOrder(
4492 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004493}
4494
Dominik Laskowskic2867142019-01-21 11:33:38 -08004495void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004496 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004497
Dominik Laskowskic2867142019-01-21 11:33:38 -08004498 if (args.size() > 1) {
4499 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004500 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004501 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004502 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004503 }
Robert Carr2047fae2016-11-28 14:09:09 -08004504 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004505 } else {
4506 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004507 }
4508}
4509
Dominik Laskowskic2867142019-01-21 11:33:38 -08004510void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004511 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004512 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004513 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004514 }
Robert Carr2047fae2016-11-28 14:09:09 -08004515 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004516
Svetoslavd85084b2014-03-20 10:28:31 -07004517 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004518}
4519
Dominik Laskowskic2867142019-01-21 11:33:38 -08004520void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4521 mTimeStats->parseArgs(asProto, args, result);
4522}
4523
Jamie Gennis6547ff42013-07-16 20:12:42 -07004524// This should only be called from the main thread. Otherwise it would need
4525// the lock and should use mCurrentState rather than mDrawingState.
4526void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004527 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004528 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004529 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004530
4531 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4532}
4533
Yiwei Zhang5434a782018-12-05 18:06:32 -08004534void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004535 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004536
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004537 if (isLayerTripleBufferingDisabled())
4538 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004539
Yiwei Zhang5434a782018-12-05 18:06:32 -08004540 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4541 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4542 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4543 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4544 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4545 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004546 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004547}
4548
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004549void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004550 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004551 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004552 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004553 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004554
4555 StringAppendF(&result, "Scheduler: %s\n\n", mUseScheduler ? "enabled" : "disabled");
4556
4557 if (mUseScheduler) {
4558 mScheduler->dump(mAppConnectionHandle, result);
4559 } else {
4560 mEventThread->dump(result);
4561 }
4562}
4563
Yiwei Zhang5434a782018-12-05 18:06:32 -08004564void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4565 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004566 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4567 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004568 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004569 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004570 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004571 }
David Sodman4a36e932017-11-07 14:29:47 -08004572 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004573 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004574 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004575 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4576 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004577}
4578
Dan Stozae77c7662016-05-13 11:37:28 -07004579void SurfaceFlinger::recordBufferingStats(const char* layerName,
4580 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004581 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4582 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004583 for (const auto& segment : history) {
4584 if (!segment.usedThirdBuffer) {
4585 stats.twoBufferTime += segment.totalTime;
4586 }
4587 if (segment.occupancyAverage < 1.0f) {
4588 stats.doubleBufferedTime += segment.totalTime;
4589 } else if (segment.occupancyAverage < 2.0f) {
4590 stats.tripleBufferedTime += segment.totalTime;
4591 }
4592 ++stats.numSegments;
4593 stats.totalTime += segment.totalTime;
4594 }
4595}
4596
Yiwei Zhang5434a782018-12-05 18:06:32 -08004597void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4598 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004599
4600 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4601 const size_t count = currentLayers.size();
4602 for (size_t i=0 ; i<count ; i++) {
4603 currentLayers[i]->dumpFrameEvents(result);
4604 }
4605}
4606
Yiwei Zhang5434a782018-12-05 18:06:32 -08004607void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004608 result.append("Buffering stats:\n");
4609 result.append(" [Layer name] <Active time> <Two buffer> "
4610 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004611 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004612 typedef std::tuple<std::string, float, float, float> BufferTuple;
4613 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004614 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004615 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004616 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004617 if (stats.numSegments == 0) {
4618 continue;
4619 }
4620 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4621 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4622 stats.totalTime;
4623 float doubleBufferRatio = static_cast<float>(
4624 stats.doubleBufferedTime) / stats.totalTime;
4625 float tripleBufferRatio = static_cast<float>(
4626 stats.tripleBufferedTime) / stats.totalTime;
4627 sorted.insert({activeTime, {name, twoBufferRatio,
4628 doubleBufferRatio, tripleBufferRatio}});
4629 }
4630 for (const auto& sortedPair : sorted) {
4631 float activeTime = sortedPair.first;
4632 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004633 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4634 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004635 }
4636 result.append("\n");
4637}
4638
Yiwei Zhang5434a782018-12-05 18:06:32 -08004639void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004640 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004641 const auto displayId = display->getId();
4642 if (!displayId) {
4643 continue;
4644 }
4645 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004646 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004647 continue;
4648 }
4649
Yiwei Zhang5434a782018-12-05 18:06:32 -08004650 StringAppendF(&result,
4651 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4652 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004653 uint8_t port;
4654 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004655 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004656 result.append("no identification data\n");
4657 continue;
4658 }
4659
4660 if (!isEdid(data)) {
4661 result.append("unknown identification data: ");
4662 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004663 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004664 }
4665 result.append("\n");
4666 continue;
4667 }
4668
4669 const auto edid = parseEdid(data);
4670 if (!edid) {
4671 result.append("invalid EDID: ");
4672 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004673 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004674 }
4675 result.append("\n");
4676 continue;
4677 }
4678
Yiwei Zhang5434a782018-12-05 18:06:32 -08004679 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004680 result.append(edid->displayName.data(), edid->displayName.length());
4681 result.append("\"\n");
4682 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004683}
4684
Yiwei Zhang5434a782018-12-05 18:06:32 -08004685void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4686 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4687 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4688 StringAppendF(&result, "DisplayColorSetting: %s\n",
4689 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004690
4691 // TODO: print out if wide-color mode is active or not
4692
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004693 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004694 const auto displayId = display->getId();
4695 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004696 continue;
4697 }
4698
Yiwei Zhang5434a782018-12-05 18:06:32 -08004699 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004700 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004701 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004702 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004703 }
4704
Lloyd Pique32cbe282018-10-19 13:09:22 -07004705 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004706 StringAppendF(&result, " Current color mode: %s (%d)\n",
4707 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004708 }
4709 result.append("\n");
4710}
4711
Yiwei Zhang5434a782018-12-05 18:06:32 -08004712void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004713 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004714 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4715 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004716 continue;
4717 }
4718
Dominik Laskowski05275f12018-11-01 15:03:24 -07004719 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004720 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4721 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004722 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004723 compositionInfo.dump(result, nullptr);
4724 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004725 }
4726 }
David Sodman7e4ae112018-02-09 15:02:28 -08004727}
4728
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004729LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004730 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004731 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4732 const State& state = useDrawing ? mDrawingState : mCurrentState;
4733 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004734 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004735 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004736 });
4737
4738 return layersProto;
4739}
4740
Lloyd Pique32cbe282018-10-19 13:09:22 -07004741LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004742 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004743
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004744 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004745 resolution->set_w(displayDevice.getWidth());
4746 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004747
Lloyd Pique32cbe282018-10-19 13:09:22 -07004748 auto display = displayDevice.getCompositionDisplay();
4749 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004750
Lloyd Pique32cbe282018-10-19 13:09:22 -07004751 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4752 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4753 layersProto.set_global_transform(displayState.orientation);
4754
4755 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004756 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004757 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004758 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004759 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004760 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004761 }
4762 });
4763
4764 return layersProto;
4765}
4766
Dominik Laskowskic2867142019-01-21 11:33:38 -08004767void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4768 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004769 Colorizer colorizer(colorize);
4770
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004771 // figure out if we're stuck somewhere
4772 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004773 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004774 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4775
4776 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004777 * Dump library configuration.
4778 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004779
4780 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004781 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004782 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004783 appendSfConfigString(result);
4784 appendUiConfigString(result);
4785 appendGuiConfigString(result);
4786 result.append("\n");
4787
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004788 result.append("\nDisplay identification data:\n");
4789 dumpDisplayIdentificationData(result);
4790
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004791 result.append("\nWide-Color information:\n");
4792 dumpWideColorInfo(result);
4793
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004794 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004795 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004796 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004797 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004798 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004799
Andy McFadden41d67d72014-04-25 16:58:34 -07004800 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004801 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004802 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004803 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004804 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004805
Dan Stozab90cf072015-03-05 11:05:59 -08004806 dumpStaticScreenStats(result);
4807 result.append("\n");
4808
Yiwei Zhang5434a782018-12-05 18:06:32 -08004809 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004810
Dan Stozae77c7662016-05-13 11:37:28 -07004811 dumpBufferingStats(result);
4812
Andy McFadden4803b742012-09-24 19:07:20 -07004813 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004814 * Dump the visible layer list
4815 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004816 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004817 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4818 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4819 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004820 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004821
Chia-I Wu2f884132018-09-13 15:17:58 -07004822 {
4823 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4824 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004825 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004826 result.append("\n");
4827 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004828
David Sodman7e4ae112018-02-09 15:02:28 -08004829 result.append("\nFrame-Composition information:\n");
4830 dumpFrameCompositionInfo(result);
4831 result.append("\n");
4832
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004833 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004834 * Dump Display state
4835 */
4836
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004837 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004838 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004839 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004840 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004841 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004842 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004843 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004844
4845 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004846 * Dump SurfaceFlinger global state
4847 */
4848
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004849 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004850 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004851 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004852
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004853 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004854
Dominik Laskowski075d3172018-05-24 15:50:06 -07004855 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004856 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4857 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004858 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4859 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004860 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004861 StringAppendF(&result,
4862 " transaction-flags : %08x\n"
4863 " gpu_to_cpu_unsupported : %d\n",
4864 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004865
Dominik Laskowski075d3172018-05-24 15:50:06 -07004866 if (const auto displayId = getInternalDisplayId();
4867 displayId && getHwComposer().isConnected(*displayId)) {
4868 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004869 StringAppendF(&result,
4870 " refresh-rate : %f fps\n"
4871 " x-dpi : %f\n"
4872 " y-dpi : %f\n",
4873 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4874 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004875 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004876
Yiwei Zhang5434a782018-12-05 18:06:32 -08004877 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004878
Dan Stozae22aec72016-08-01 13:20:59 -07004879 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004880 * Tracing state
4881 */
4882 mTracing.dump(result);
4883 result.append("\n");
4884
4885 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004886 * HWC layer minidump
4887 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004888 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004889 const auto displayId = display->getId();
4890 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004891 continue;
4892 }
4893
Yiwei Zhang5434a782018-12-05 18:06:32 -08004894 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004895 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004896 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004897 result.append("\n");
4898 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004899
4900 /*
4901 * Dump HWComposer state
4902 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004903 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004904 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004905 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004906 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004907 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004908 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004909
4910 /*
4911 * Dump gralloc state
4912 */
4913 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4914 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004915
4916 /*
4917 * Dump VrFlinger state if in use.
4918 */
4919 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4920 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004921 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004922 result.append("\n");
4923 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004924
4925 /**
4926 * Scheduler dump state.
4927 */
4928 if (mUseScheduler) {
4929 result.append("\nScheduler state:\n");
4930 result.append(mScheduler->doDump() + "\n");
4931 result.append(mRefreshRateStats->doDump() + "\n");
4932 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004933}
4934
Dominik Laskowski075d3172018-05-24 15:50:06 -07004935const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004936 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004937 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004938 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004939 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004940 }
4941 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004942
Dominik Laskowski34157762018-10-31 13:07:19 -07004943 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004944 static const Vector<sp<Layer>> empty;
4945 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004946}
4947
Keun young Park63f165f2012-08-31 10:53:36 -07004948bool SurfaceFlinger::startDdmConnection()
4949{
4950 void* libddmconnection_dso =
4951 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4952 if (!libddmconnection_dso) {
4953 return false;
4954 }
4955 void (*DdmConnection_start)(const char* name);
4956 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004957 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004958 if (!DdmConnection_start) {
4959 dlclose(libddmconnection_dso);
4960 return false;
4961 }
4962 (*DdmConnection_start)(getServiceName());
4963 return true;
4964}
4965
Chia-I Wu28f320b2018-05-03 11:02:56 -07004966void SurfaceFlinger::updateColorMatrixLocked() {
4967 mat4 colorMatrix;
4968 if (mGlobalSaturationFactor != 1.0f) {
4969 // Rec.709 luma coefficients
4970 float3 luminance{0.213f, 0.715f, 0.072f};
4971 luminance *= 1.0f - mGlobalSaturationFactor;
4972 mat4 saturationMatrix = mat4(
4973 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4974 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4975 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4976 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4977 );
4978 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4979 } else {
4980 colorMatrix = mClientColorMatrix * mDaltonizer();
4981 }
4982
4983 if (mCurrentState.colorMatrix != colorMatrix) {
4984 mCurrentState.colorMatrix = colorMatrix;
4985 mCurrentState.colorMatrixChanged = true;
4986 setTransactionFlags(eTransactionNeeded);
4987 }
4988}
4989
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004990status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004991#pragma clang diagnostic push
4992#pragma clang diagnostic error "-Wswitch-enum"
4993 switch (static_cast<ISurfaceComposerTag>(code)) {
4994 // These methods should at minimum make sure that the client requested
4995 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004996 case BOOT_FINISHED:
4997 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004998 case CREATE_DISPLAY:
4999 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005000 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005001 case GET_ACTIVE_COLOR_MODE:
5002 case GET_ANIMATION_FRAME_STATS:
5003 case GET_HDR_CAPABILITIES:
5004 case SET_ACTIVE_CONFIG:
5005 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005006 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005007 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005008 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005009 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
5010 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005011 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5012 IPCThreadState* ipc = IPCThreadState::self();
5013 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5014 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005015 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005016 }
Robert Carr1db73f62016-12-21 12:58:51 -08005017 return OK;
5018 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005019 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005020 IPCThreadState* ipc = IPCThreadState::self();
5021 const int pid = ipc->getCallingPid();
5022 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005023 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5024 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005025 return PERMISSION_DENIED;
5026 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005027 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005028 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005029 // Used by apps to hook Choreographer to SurfaceFlinger.
5030 case CREATE_DISPLAY_EVENT_CONNECTION:
5031 // The following calls are currently used by clients that do not
5032 // request necessary permissions. However, they do not expose any secret
5033 // information, so it is OK to pass them.
5034 case AUTHENTICATE_SURFACE:
5035 case GET_ACTIVE_CONFIG:
5036 case GET_BUILT_IN_DISPLAY:
5037 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005038 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005039 case GET_DISPLAY_CONFIGS:
5040 case GET_DISPLAY_STATS:
5041 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5042 // Calling setTransactionState is safe, because you need to have been
5043 // granted a reference to Client* and Handle* to do anything with it.
5044 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005045 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005046 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005047 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005048 case GET_PROTECTED_CONTENT_SUPPORT:
5049 case CACHE_BUFFER:
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08005050 case UNCACHE_BUFFER:
5051 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005052 return OK;
5053 }
5054 case CAPTURE_LAYERS:
5055 case CAPTURE_SCREEN: {
5056 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005057 IPCThreadState* ipc = IPCThreadState::self();
5058 const int pid = ipc->getCallingPid();
5059 const int uid = ipc->getCallingUid();
5060 if ((uid != AID_GRAPHICS) &&
5061 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5062 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5063 return PERMISSION_DENIED;
5064 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005065 return OK;
5066 }
5067 // The following codes are deprecated and should never be allowed to access SF.
5068 case CONNECT_DISPLAY_UNUSED:
5069 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5070 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5071 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005072 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005073 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005074
5075 // These codes are used for the IBinder protocol to either interrogate the recipient
5076 // side of the transaction for its canonical interface descriptor or to dump its state.
5077 // We let them pass by default.
5078 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5079 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5080 code == IBinder::SYSPROPS_TRANSACTION) {
5081 return OK;
5082 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005083 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005084 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005085 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005086 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5087 return OK;
5088 }
5089 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5090 return PERMISSION_DENIED;
5091#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005092}
5093
Ana Krulec13be8ad2018-08-21 02:43:56 +00005094status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5095 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005096 status_t credentialCheck = CheckTransactCodeCredentials(code);
5097 if (credentialCheck != OK) {
5098 return credentialCheck;
5099 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005100
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005101 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5102 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005103 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005104 IPCThreadState* ipc = IPCThreadState::self();
5105 const int uid = ipc->getCallingUid();
5106 if (CC_UNLIKELY(uid != AID_SYSTEM
5107 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005108 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005109 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005110 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005111 return PERMISSION_DENIED;
5112 }
5113 int n;
5114 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005115 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005116 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005117 return NO_ERROR;
5118 case 1002: // SHOW_UPDATES
5119 n = data.readInt32();
5120 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005121 invalidateHwcGeometry();
5122 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005123 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005124 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005125 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005126 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005127 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005128 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005129 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005130 setTransactionFlags(
5131 eTransactionNeeded|
5132 eDisplayTransactionNeeded|
5133 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005134 return NO_ERROR;
5135 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005136 case 1006:{ // send empty update
5137 signalRefresh();
5138 return NO_ERROR;
5139 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005140 case 1008: // toggle use of hw composer
5141 n = data.readInt32();
5142 mDebugDisableHWC = n ? 1 : 0;
5143 invalidateHwcGeometry();
5144 repaintEverything();
5145 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005146 case 1009: // toggle use of transform hint
5147 n = data.readInt32();
5148 mDebugDisableTransformHint = n ? 1 : 0;
5149 invalidateHwcGeometry();
5150 repaintEverything();
5151 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005152 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005153 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005154 reply->writeInt32(0);
5155 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005156 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005157 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005158 return NO_ERROR;
5159 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005160 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005161 if (!display) {
5162 return NAME_NOT_FOUND;
5163 }
5164
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005165 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005166 return NO_ERROR;
5167 }
5168 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005169 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005170 // daltonize
5171 n = data.readInt32();
5172 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005173 case 1:
5174 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5175 break;
5176 case 2:
5177 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5178 break;
5179 case 3:
5180 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5181 break;
5182 default:
5183 mDaltonizer.setType(ColorBlindnessType::None);
5184 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005185 }
5186 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005187 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005188 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005189 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005190 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005191
5192 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005193 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005194 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005195 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005196 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005197 // apply a color matrix
5198 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005199 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005200 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005201 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005202 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005203 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005204 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005205 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005206 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005207 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005208 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005209
5210 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5211 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005212 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005213 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5214 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5215 }
5216
Chia-I Wu28f320b2018-05-03 11:02:56 -07005217 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005218 return NO_ERROR;
5219 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005220 // This is an experimental interface
5221 // Needs to be shifted to proper binder interface when we productize
5222 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005223 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005224 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005225 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005226 return NO_ERROR;
5227 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005228 case 1017: {
5229 n = data.readInt32();
5230 mForceFullDamage = static_cast<bool>(n);
5231 return NO_ERROR;
5232 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005233 case 1018: { // Modify Choreographer's phase offset
5234 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005235 if (mUseScheduler) {
5236 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5237 } else {
5238 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5239 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005240 return NO_ERROR;
5241 }
5242 case 1019: { // Modify SurfaceFlinger's phase offset
5243 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005244 if (mUseScheduler) {
5245 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5246 } else {
5247 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5248 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005249 return NO_ERROR;
5250 }
Irvel468051e2016-06-13 16:44:44 -07005251 case 1020: { // Layer updates interceptor
5252 n = data.readInt32();
5253 if (n) {
5254 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005255 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005256 }
5257 else{
5258 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005259 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005260 }
5261 return NO_ERROR;
5262 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005263 case 1021: { // Disable HWC virtual displays
5264 n = data.readInt32();
5265 mUseHwcVirtualDisplays = !n;
5266 return NO_ERROR;
5267 }
Romain Guy0147a172017-06-01 13:53:56 -07005268 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005269 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005270 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005271
Chia-I Wu28f320b2018-05-03 11:02:56 -07005272 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005273 return NO_ERROR;
5274 }
Romain Guy54f154a2017-10-24 21:40:32 +01005275 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005276 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005277 invalidateHwcGeometry();
5278 repaintEverything();
5279 return NO_ERROR;
5280 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005281 // Deprecate, use 1030 to check whether the device is color managed.
5282 case 1024: {
5283 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005284 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005285 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005286 n = data.readInt32();
5287 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005288 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005289 mTracing.enable();
5290 doTracing("tracing.enable");
5291 reply->writeInt32(NO_ERROR);
5292 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005293 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005294 status_t err = mTracing.disable();
5295 reply->writeInt32(err);
5296 }
5297 return NO_ERROR;
5298 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005299 case 1026: { // Get layer tracing status
5300 reply->writeBool(mTracing.isEnabled());
5301 return NO_ERROR;
5302 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005303 // Is a DisplayColorSetting supported?
5304 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005305 const auto display = getDefaultDisplayDevice();
5306 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005307 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005308 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005309
5310 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5311 switch (setting) {
5312 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005313 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005314 break;
5315 case DisplayColorSetting::UNMANAGED:
5316 reply->writeBool(true);
5317 break;
5318 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005319 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005320 break;
5321 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005322 reply->writeBool(
5323 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005324 break;
5325 }
5326 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005327 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005328 // Is VrFlinger active?
5329 case 1028: {
5330 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005331 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005332 return NO_ERROR;
5333 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005334 // Is device color managed?
5335 case 1030: {
5336 reply->writeBool(useColorManagement);
5337 return NO_ERROR;
5338 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005339 // Override default composition data space
5340 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5341 // && adb shell stop zygote && adb shell start zygote
5342 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5343 // adb shell stop zygote && adb shell start zygote
5344 case 1031: {
5345 Mutex::Autolock _l(mStateLock);
5346 n = data.readInt32();
5347 if (n) {
5348 n = data.readInt32();
5349 if (n) {
5350 Dataspace dataspace = static_cast<Dataspace>(n);
5351 if (!validateCompositionDataspace(dataspace)) {
5352 return BAD_VALUE;
5353 }
5354 mDefaultCompositionDataspace = dataspace;
5355 }
5356 n = data.readInt32();
5357 if (n) {
5358 Dataspace dataspace = static_cast<Dataspace>(n);
5359 if (!validateCompositionDataspace(dataspace)) {
5360 return BAD_VALUE;
5361 }
5362 mWideColorGamutCompositionDataspace = dataspace;
5363 }
5364 } else {
5365 // restore composition data space.
5366 mDefaultCompositionDataspace = defaultCompositionDataspace;
5367 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5368 }
5369 return NO_ERROR;
5370 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005371 }
5372 }
5373 return err;
5374}
5375
Steven Thomas6d8110b2017-08-31 18:24:21 -07005376void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005377 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005378 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005379}
5380
Ana Krulec7d1d6832018-12-27 11:10:09 -08005381void SurfaceFlinger::repaintEverythingForHWC() {
5382 mRepaintEverything = true;
5383 mEventQueue->invalidateForHWC();
5384}
5385
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005386// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5387class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005388public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005389 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5390 ~WindowDisconnector() {
5391 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005392 }
5393
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005394private:
5395 ANativeWindow* mWindow;
5396 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005397};
5398
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005399status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005400 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5401 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005402 uint32_t reqWidth, uint32_t reqHeight,
5403 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005404 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005405 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005406
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005407 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005408
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005409 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5410
Chia-I Wu20261cb2018-08-23 12:55:44 -07005411 sp<DisplayDevice> display;
5412 {
5413 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005414
Chia-I Wu20261cb2018-08-23 12:55:44 -07005415 display = getDisplayDeviceLocked(displayToken);
5416 if (!display) return BAD_VALUE;
5417
Chia-I Wucb023152018-08-28 12:57:23 -07005418 // set the requested width/height to the logical display viewport size
5419 // by default
5420 if (reqWidth == 0 || reqHeight == 0) {
5421 reqWidth = uint32_t(display->getViewport().width());
5422 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005423 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005424 }
5425
Peiyong Lin0e003c92018-09-17 11:09:51 -07005426 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5427 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005428
5429 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005430 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005431 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5432 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005433}
5434
5435status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005436 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5437 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005438 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005439 ATRACE_CALL();
5440
5441 class LayerRenderArea : public RenderArea {
5442 public:
Robert Carr578038f2018-03-09 12:25:24 -08005443 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005444 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5445 bool childrenOnly)
5446 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005447 mLayer(layer),
5448 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005449 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005450 mFlinger(flinger),
5451 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005452 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005453 Rect getBounds() const override {
5454 const Layer::State& layerState(mLayer->getDrawingState());
5455 return mLayer->getBufferSize(layerState);
5456 }
Marissa Wall61c58622018-07-18 10:12:20 -07005457 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005458 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005459 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005460 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005461 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005462 }
chaviwa76b2712017-09-20 12:02:26 -07005463 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005464 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005465 Rect getSourceCrop() const override {
5466 if (mCrop.isEmpty()) {
5467 return getBounds();
5468 } else {
5469 return mCrop;
5470 }
5471 }
Robert Carr578038f2018-03-09 12:25:24 -08005472 class ReparentForDrawing {
5473 public:
5474 const sp<Layer>& oldParent;
5475 const sp<Layer>& newParent;
5476
5477 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5478 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005479 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005480 }
Robert Carr15eae092018-03-23 13:43:53 -07005481 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005482 };
5483
5484 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005485 const Rect sourceCrop = getSourceCrop();
5486 // no need to check rotation because there is none
5487 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5488 sourceCrop.height() != getReqHeight();
5489
Robert Carr578038f2018-03-09 12:25:24 -08005490 if (!mChildrenOnly) {
5491 mTransform = mLayer->getTransform().inverse();
5492 drawLayers();
5493 } else {
5494 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005495 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005496 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5497 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005498
5499 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5500 drawLayers();
5501 }
5502 }
chaviwa76b2712017-09-20 12:02:26 -07005503
chaviwa76b2712017-09-20 12:02:26 -07005504 private:
chaviw7206d492017-11-10 16:16:12 -08005505 const sp<Layer> mLayer;
5506 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005507
5508 // In the "childrenOnly" case we reparent the children to a screenshot
5509 // layer which has no properties set and which does not draw.
5510 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005511 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005512 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005513
5514 SurfaceFlinger* mFlinger;
5515 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005516 };
5517
5518 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5519 auto parent = layerHandle->owner.promote();
5520
Robert Carr2e102c92018-10-23 12:11:15 -07005521 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005522 ALOGE("captureLayers called with a removed parent");
5523 return NAME_NOT_FOUND;
5524 }
5525
Robert Carr578038f2018-03-09 12:25:24 -08005526 const int uid = IPCThreadState::self()->getCallingUid();
5527 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005528 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005529 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5530 return PERMISSION_DENIED;
5531 }
5532
chaviw7206d492017-11-10 16:16:12 -08005533 Rect crop(sourceCrop);
5534 if (sourceCrop.width() <= 0) {
5535 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005536 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005537 }
5538
5539 if (sourceCrop.height() <= 0) {
5540 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005541 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005542 }
5543
5544 int32_t reqWidth = crop.width() * frameScale;
5545 int32_t reqHeight = crop.height() * frameScale;
5546
Chia-I Wu20261cb2018-08-23 12:55:44 -07005547 // really small crop or frameScale
5548 if (reqWidth <= 0) {
5549 reqWidth = 1;
5550 }
5551 if (reqHeight <= 0) {
5552 reqHeight = 1;
5553 }
5554
Peiyong Lin0e003c92018-09-17 11:09:51 -07005555 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005556
Robert Carr578038f2018-03-09 12:25:24 -08005557 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005558 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5559 if (!layer->isVisible()) {
5560 return;
Robert Carr578038f2018-03-09 12:25:24 -08005561 } else if (childrenOnly && layer == parent.get()) {
5562 return;
chaviwa76b2712017-09-20 12:02:26 -07005563 }
5564 visitor(layer);
5565 });
5566 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005567 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005568}
5569
5570status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5571 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005572 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005573 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005574 bool useIdentityTransform) {
5575 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005576
Peiyong Lin0e003c92018-09-17 11:09:51 -07005577 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005578 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5579 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005580 *outBuffer =
5581 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5582 static_cast<android_pixel_format>(reqPixelFormat), 1,
5583 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005584
5585 // This mutex protects syncFd and captureResult for communication of the return values from the
5586 // main thread back to this Binder thread
5587 std::mutex captureMutex;
5588 std::condition_variable captureCondition;
5589 std::unique_lock<std::mutex> captureLock(captureMutex);
5590 int syncFd = -1;
5591 std::optional<status_t> captureResult;
5592
Robert Carr03480e22018-01-04 16:02:06 -08005593 const int uid = IPCThreadState::self()->getCallingUid();
5594 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5595
Dominik Laskowski8c001672018-05-30 16:52:06 -07005596 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005597 // If there is a refresh pending, bug out early and tell the binder thread to try again
5598 // after the refresh.
5599 if (mRefreshPending) {
5600 ATRACE_NAME("Skipping screenshot for now");
5601 std::unique_lock<std::mutex> captureLock(captureMutex);
5602 captureResult = std::make_optional<status_t>(EAGAIN);
5603 captureCondition.notify_one();
5604 return;
5605 }
5606
5607 status_t result = NO_ERROR;
5608 int fd = -1;
5609 {
5610 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005611 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005612 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5613 useIdentityTransform, forSystem, &fd);
5614 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005615 }
5616
5617 {
5618 std::unique_lock<std::mutex> captureLock(captureMutex);
5619 syncFd = fd;
5620 captureResult = std::make_optional<status_t>(result);
5621 captureCondition.notify_one();
5622 }
5623 });
5624
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005625 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005626 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005627 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005628 while (*captureResult == EAGAIN) {
5629 captureResult.reset();
5630 result = postMessageAsync(message);
5631 if (result != NO_ERROR) {
5632 return result;
5633 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005634 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005635 }
5636 result = *captureResult;
5637 }
5638
5639 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005640 sync_wait(syncFd, -1);
5641 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005642 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005643
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005644 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005645}
5646
chaviwa76b2712017-09-20 12:02:26 -07005647void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005648 TraverseLayersFunction traverseLayers,
Alec Mouri79108df2019-02-04 19:33:44 +00005649 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005650 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005651
Alec Mouri79108df2019-02-04 19:33:44 +00005652 auto& engine(getRenderEngine());
5653
chaviwa76b2712017-09-20 12:02:26 -07005654 const auto reqWidth = renderArea.getReqWidth();
5655 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005656 const auto sourceCrop = renderArea.getSourceCrop();
5657 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005658
Alec Mouri79108df2019-02-04 19:33:44 +00005659 engine.setOutputDataSpace(renderArea.getReqDataSpace());
5660 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005661
Alec Mouri79108df2019-02-04 19:33:44 +00005662 // make sure to clear all GL error flags
5663 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005664
Alec Mouri79108df2019-02-04 19:33:44 +00005665 // set-up our viewport
5666 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
5667 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005668
chaviw50da5042018-04-09 13:49:37 -07005669 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Alec Mouri79108df2019-02-04 19:33:44 +00005670 // redraw the screen entirely...
5671 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005672
chaviwa76b2712017-09-20 12:02:26 -07005673 traverseLayers([&](Layer* layer) {
Alec Mouri79108df2019-02-04 19:33:44 +00005674 engine.setColorTransform(layer->getColorTransform());
5675 layer->draw(renderArea, useIdentityTransform);
5676 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005677 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005678}
5679
chaviwa76b2712017-09-20 12:02:26 -07005680status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5681 TraverseLayersFunction traverseLayers,
5682 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005683 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005684 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005685 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005686 ATRACE_CALL();
5687
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005688 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005689
5690 traverseLayers([&](Layer* layer) {
5691 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5692 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005693
Robert Carr03480e22018-01-04 16:02:06 -08005694 // We allow the system server to take screenshots of secure layers for
5695 // use in situations like the Screen-rotation animation and place
5696 // the impetus on WindowManager to not persist them.
5697 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005698 ALOGW("FB is protected: PERMISSION_DENIED");
5699 return PERMISSION_DENIED;
5700 }
Alec Mouri79108df2019-02-04 19:33:44 +00005701 auto& engine(getRenderEngine());
5702
5703 // this binds the given EGLImage as a framebuffer for the
5704 // duration of this scope.
5705 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
5706 if (bufferBond.getStatus() != NO_ERROR) {
5707 ALOGE("got ANWB binding error while taking screenshot");
5708 return INVALID_OPERATION;
5709 }
5710
5711 // this will in fact render into our dequeued buffer
5712 // via an FBO, which means we didn't have to create
5713 // an EGLSurface and therefore we're not
5714 // dependent on the context's EGLConfig.
5715 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
5716
5717 base::unique_fd syncFd = engine.flush();
5718 if (syncFd < 0) {
5719 engine.finish();
5720 }
5721 *outSyncFd = syncFd.release();
5722
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005723 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005724}
5725
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005726// ---------------------------------------------------------------------------
5727
Dan Stoza412903f2017-04-27 13:42:17 -07005728void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5729 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005730}
5731
Dan Stoza412903f2017-04-27 13:42:17 -07005732void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5733 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005734}
5735
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005736void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005737 const LayerVector::Visitor& visitor) {
5738 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005739 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005740 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005741 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005742 continue;
5743 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005744 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005745 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005746 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005747 return;
5748 }
chaviwa76b2712017-09-20 12:02:26 -07005749 if (!layer->isVisible()) {
5750 return;
5751 }
5752 visitor(layer);
5753 });
5754 }
5755}
5756
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005757}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005758
Lloyd Pique074e8122018-07-26 12:57:23 -07005759
Mathias Agopian3f844832013-08-07 21:24:32 -07005760#if defined(__gl_h_)
5761#error "don't include gl/gl.h in this file"
5762#endif
5763
5764#if defined(__gl2_h_)
5765#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005766#endif