blob: 2fea060793e4843c426bf08040011aa4a97257c2 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Alec Mouri0f714832018-11-12 15:31:06 -080017//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080031#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Lloyd Pique70d91362018-10-18 16:02:55 -070040#include <compositionengine/CompositionEngine.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070041#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070042#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080043#include <compositionengine/Layer.h>
44#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070045#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070046#include <compositionengine/impl/OutputCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080047#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070049#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080051#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080052#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080053#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070054#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070055#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070056#include <ui/ColorSpace.h>
57#include <ui/DebugUtils.h>
58#include <ui/DisplayInfo.h>
59#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070060#include <ui/GraphicBufferAllocator.h>
61#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070062#include <ui/UiConfig.h>
Ady Abraham8164d482019-01-11 14:47:59 -080063#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070065#include <utils/String16.h>
66#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070067#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080068#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070069#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080070
Mathias Agopian921e6ac2012-07-23 23:11:29 -070071#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070072#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073
Robert Carr578038f2018-03-09 12:25:24 -080074#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070075#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070076#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020077#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020079#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080080#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080081#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080082#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070084#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080085#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070086#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070087#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080088#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070089#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080090
Steven Thomasb02664d2017-07-26 18:48:28 -070091#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070092#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070093#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070094#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070095#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070096#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070097#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070098#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070099#include "Scheduler/EventControlThread.h"
100#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700101#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700102#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700103#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800104#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700105
Mathias Agopianff2ed702013-09-01 21:36:12 -0700106#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700107
David Sodman7e4ae112018-02-09 15:02:28 -0800108#include "android-base/stringprintf.h"
109
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900110#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800111#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700112#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800113#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900114#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900115
chaviw1d044282017-09-27 12:19:28 -0700116#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900117#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700118
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800119namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700120
Jaesoo Lee43518572017-01-23 19:03:16 +0900121using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900122using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900123using namespace android::sysprop;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800124using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700125using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700126using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800127using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700128using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700129using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900130
Steven Thomasb02664d2017-07-26 18:48:28 -0700131namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700132
133#pragma clang diagnostic push
134#pragma clang diagnostic error "-Wswitch-enum"
135
136bool isWideColorMode(const ColorMode colorMode) {
137 switch (colorMode) {
138 case ColorMode::DISPLAY_P3:
139 case ColorMode::ADOBE_RGB:
140 case ColorMode::DCI_P3:
141 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700142 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700143 case ColorMode::BT2100_PQ:
144 case ColorMode::BT2100_HLG:
145 return true;
146 case ColorMode::NATIVE:
147 case ColorMode::STANDARD_BT601_625:
148 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
149 case ColorMode::STANDARD_BT601_525:
150 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
151 case ColorMode::STANDARD_BT709:
152 case ColorMode::SRGB:
153 return false;
154 }
155 return false;
156}
157
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700158ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
159 switch (rotation) {
160 case ISurfaceComposer::eRotateNone:
161 return ui::Transform::ROT_0;
162 case ISurfaceComposer::eRotate90:
163 return ui::Transform::ROT_90;
164 case ISurfaceComposer::eRotate180:
165 return ui::Transform::ROT_180;
166 case ISurfaceComposer::eRotate270:
167 return ui::Transform::ROT_270;
168 }
169 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
170 return ui::Transform::ROT_0;
171}
172
Peiyong Linfca547f2018-07-09 13:03:33 -0700173#pragma clang diagnostic pop
174
Steven Thomasb02664d2017-07-26 18:48:28 -0700175class ConditionalLock {
176public:
177 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
178 if (lock) {
179 mMutex.lock();
180 }
181 }
182 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
183private:
184 Mutex& mMutex;
185 bool mLocked;
186};
Peiyong Linfca547f2018-07-09 13:03:33 -0700187
Peiyong Lin9d846a52018-11-05 13:18:20 -0800188// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
189bool validateCompositionDataspace(Dataspace dataspace) {
190 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
191}
192
Steven Thomasb02664d2017-07-26 18:48:28 -0700193} // namespace anonymous
194
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800195// ---------------------------------------------------------------------------
196
Mathias Agopian99b49842011-06-27 16:05:52 -0700197const String16 sHardwareTest("android.permission.HARDWARE_TEST");
198const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
199const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
200const String16 sDump("android.permission.DUMP");
201
Daniel Solomon42d04562019-01-20 21:03:19 -0800202constexpr float kSrgbRedX = 0.4123f;
203constexpr float kSrgbRedY = 0.2126f;
204constexpr float kSrgbRedZ = 0.0193f;
205constexpr float kSrgbGreenX = 0.3576f;
206constexpr float kSrgbGreenY = 0.7152f;
207constexpr float kSrgbGreenZ = 0.1192f;
208constexpr float kSrgbBlueX = 0.1805f;
209constexpr float kSrgbBlueY = 0.0722f;
210constexpr float kSrgbBlueZ = 0.9506f;
211constexpr float kSrgbWhiteX = 0.9505f;
212constexpr float kSrgbWhiteY = 1.0000f;
213constexpr float kSrgbWhiteZ = 1.0891f;
214
Mathias Agopian99b49842011-06-27 16:05:52 -0700215// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700216int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700217bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800218uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800219bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800220bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800221int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600222bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700223int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700224bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700225bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700226Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
227ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
228Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
229ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700230
Kalle Raitaa099a242017-01-11 11:17:29 -0800231std::string getHwcServiceName() {
232 char value[PROPERTY_VALUE_MAX] = {};
233 property_get("debug.sf.hwc_service_name", value, "default");
234 ALOGI("Using HWComposer service: '%s'", value);
235 return std::string(value);
236}
237
238bool useTrebleTestingOverride() {
239 char value[PROPERTY_VALUE_MAX] = {};
240 property_get("debug.sf.treble_testing_override", value, "false");
241 ALOGI("Treble testing override: '%s'", value);
242 return std::string(value) == "true";
243}
244
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800245std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
246 switch(displayColorSetting) {
247 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700248 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800249 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700250 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800251 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700252 return std::string("Enhanced");
253 default:
254 return std::string("Unknown ") +
255 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800256 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800257}
258
David Sodmanbc815282017-11-05 18:57:52 -0800259SurfaceFlingerBE::SurfaceFlingerBE()
260 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800261 mFrameBuckets(),
262 mTotalTime(0),
263 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800264 mComposerSequenceId(0) {
265}
266
Lloyd Pique90c115d2018-09-18 21:39:42 -0700267SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
268 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800269 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700270 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700271 mTransactionPending(false),
272 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700273 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700274 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800275 mBootTime(systemTime()),
Ana Krulec757f63a2019-01-25 10:46:18 -0800276 mPhaseOffsets{getFactory().createPhaseOffsets()},
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800277 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800278 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800279 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800280 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800281 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700282 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700283 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700284 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700285 mDebugInTransaction(0),
286 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700287 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800288 mTimeStats(factory.createTimeStats()),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700289 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700290 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800291 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800292 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800293 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700294 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700295 mMainThreadId(std::this_thread::get_id()),
296 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800297
Lloyd Pique90c115d2018-09-18 21:39:42 -0700298SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
299 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800300 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800301
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900302 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800303
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900304 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700305
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900306 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700307
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800309
Steven Thomas050b2c82017-03-06 11:45:16 -0800310 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900311 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800312
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900313 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800314
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900315 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700316
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900317 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600318
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900319 mDefaultCompositionDataspace =
320 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
321 mWideColorGamutCompositionDataspace =
322 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
323 defaultCompositionDataspace = mDefaultCompositionDataspace;
324 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
325 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
326 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
327 wideColorGamutCompositionPixelFormat =
328 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700329
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900330 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800331
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900332 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
333 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
334 switch (tmpPrimaryDisplayOrientation) {
335 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700336 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800337 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900338 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700339 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800340 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900341 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700342 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800343 break;
344 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700345 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800346 break;
347 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700348 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800349
Lloyd Pique90c115d2018-09-18 21:39:42 -0700350 mPrimaryDispSync =
351 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
352 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700353
Daniel Solomon42d04562019-01-20 21:03:19 -0800354 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
355 if (surfaceFlingerConfigsServiceV1_2) {
356 surfaceFlingerConfigsServiceV1_2->getDisplayNativePrimaries(
357 [&](auto tmpPrimaries) {
358 memcpy(&mInternalDisplayPrimaries, &tmpPrimaries, sizeof(ui::DisplayPrimaries));
359 });
360 } else {
361 initDefaultDisplayNativePrimaries();
362 }
363
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800364 // debugging stuff...
365 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700366
Mathias Agopianb4b17302013-03-20 18:36:41 -0700367 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700368 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700369
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800370 property_get("debug.sf.showupdates", value, "0");
371 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700372
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700373 property_get("debug.sf.ddms", value, "0");
374 mDebugDDMS = atoi(value);
375 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700376 if (!startDdmConnection()) {
377 // start failed, and DDMS debugging not enabled
378 mDebugDDMS = 0;
379 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700380 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700381 ALOGI_IF(mDebugRegion, "showupdates enabled");
382 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700383
384 property_get("debug.sf.disable_backpressure", value, "0");
385 mPropagateBackpressure = !atoi(value);
386 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700387
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800388 property_get("debug.sf.enable_hwc_vds", value, "0");
389 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800390 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800391
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800392 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800393 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800394 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700395
Yiwei Zhang243b3782018-05-15 17:40:04 -0700396 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700397 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
398 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
399
Ana Krulec98b5b242018-08-10 15:03:23 -0700400 property_get("debug.sf.use_scheduler", value, "0");
401 mUseScheduler = atoi(value);
402
Ana Krulec757f63a2019-01-25 10:46:18 -0800403 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
404 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700405
Romain Guy11d63f42017-07-20 12:47:14 -0700406 // We should be reading 'persist.sys.sf.color_saturation' here
407 // but since /data may be encrypted, we need to wait until after vold
408 // comes online to attempt to read the property. The property is
409 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800410
411 if (useTrebleTestingOverride()) {
412 // Without the override SurfaceFlinger cannot connect to HIDL
413 // services that are not listed in the manifests. Considered
414 // deriving the setting from the set service name, but it
415 // would be brittle if the name that's not 'default' is used
416 // for production purposes later on.
417 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
418 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800419}
420
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800421void SurfaceFlinger::onFirstRef()
422{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800423 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800424}
425
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800426SurfaceFlinger::~SurfaceFlinger()
427{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800428}
429
Dan Stozac7014012014-02-14 15:03:43 -0800430void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800431{
432 // the window manager died on us. prepare its eulogy.
433
Andy McFadden13a082e2012-08-24 10:16:42 -0700434 // restore initial conditions (default device unblank, etc)
435 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800436
437 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700438 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800439}
440
Robert Carr1db73f62016-12-21 12:58:51 -0800441static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700442 status_t err = client->initCheck();
443 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800444 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800445 }
Robert Carr1db73f62016-12-21 12:58:51 -0800446 return nullptr;
447}
448
449sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
450 return initClient(new Client(this));
451}
452
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700453sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
454 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700455{
456 class DisplayToken : public BBinder {
457 sp<SurfaceFlinger> flinger;
458 virtual ~DisplayToken() {
459 // no more references, this display must be terminated
460 Mutex::Autolock _l(flinger->mStateLock);
461 flinger->mCurrentState.displays.removeItem(this);
462 flinger->setTransactionFlags(eDisplayTransactionNeeded);
463 }
464 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700465 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700466 : flinger(flinger) {
467 }
468 };
469
470 sp<BBinder> token = new DisplayToken(this);
471
472 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700473 // Display ID is assigned when virtual display is allocated by HWC.
474 DisplayDeviceState state;
475 state.isSecure = secure;
476 state.displayName = displayName;
477 mCurrentState.displays.add(token, state);
478 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700479 return token;
480}
481
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700482void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700483 Mutex::Autolock _l(mStateLock);
484
Dominik Laskowski075d3172018-05-24 15:50:06 -0700485 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
486 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700487 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700488 return;
489 }
490
Dominik Laskowski075d3172018-05-24 15:50:06 -0700491 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
492 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700493 ALOGE("destroyDisplay called for non-virtual display");
494 return;
495 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700496 mInterceptor->saveDisplayDeletion(state.sequenceId);
497 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700498 setTransactionFlags(eDisplayTransactionNeeded);
499}
500
Mathias Agopiane57f2922012-08-09 16:29:12 -0700501sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700502 std::optional<DisplayId> displayId;
503
504 if (id == HWC_DISPLAY_PRIMARY) {
505 displayId = getInternalDisplayId();
506 } else if (id == HWC_DISPLAY_EXTERNAL) {
507 displayId = getExternalDisplayId();
508 }
509
510 if (!displayId) {
511 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800512 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700513 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700514
515 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700516}
517
Ady Abraham37965d42018-11-01 13:43:32 -0700518status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
519 if (!outGetColorManagement) {
520 return BAD_VALUE;
521 }
522 *outGetColorManagement = useColorManagement;
523 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700524}
525
Lloyd Pique441d5042018-10-18 16:49:51 -0700526HWComposer& SurfaceFlinger::getHwComposer() const {
527 return mCompositionEngine->getHwComposer();
528}
529
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700530renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
531 return mCompositionEngine->getRenderEngine();
532}
533
Lloyd Pique70d91362018-10-18 16:02:55 -0700534compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
535 return *mCompositionEngine.get();
536}
537
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800538void SurfaceFlinger::bootFinished()
539{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700540 if (mStartPropertySetThread->join() != NO_ERROR) {
541 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800542 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800543 const nsecs_t now = systemTime();
544 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000545 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700546
547 // wait patiently for the window manager death
548 const String16 name("window");
549 sp<IBinder> window(defaultServiceManager()->getService(name));
550 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700551 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700552 }
Robert Carr720e5062018-07-30 17:45:14 -0700553 sp<IBinder> input(defaultServiceManager()->getService(
554 String16("inputflinger")));
555 if (input == nullptr) {
556 ALOGE("Failed to link to input service");
557 } else {
558 mInputFlinger = interface_cast<IInputFlinger>(input);
559 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700560
Steven Thomas050b2c82017-03-06 11:45:16 -0800561 if (mVrFlinger) {
562 mVrFlinger->OnBootFinished();
563 }
564
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700565 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700566 // formerly we would just kill the process, but we now ask it to exit so it
567 // can choose where to stop the animation.
568 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700569
570 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
571 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
572 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700573
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800574 postMessageAsync(new LambdaMessage([this] {
575 readPersistentProperties();
576 mBootStage = BootStage::FINISHED;
577 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800578}
579
Dan Stoza436ccf32018-06-21 12:10:12 -0700580uint32_t SurfaceFlinger::getNewTexture() {
581 {
582 std::lock_guard lock(mTexturePoolMutex);
583 if (!mTexturePool.empty()) {
584 uint32_t name = mTexturePool.back();
585 mTexturePool.pop_back();
586 ATRACE_INT("TexturePoolSize", mTexturePool.size());
587 return name;
588 }
589
590 // The pool was too small, so increase it for the future
591 ++mTexturePoolSize;
592 }
593
594 // The pool was empty, so we need to get a new texture name directly using a
595 // blocking call to the main thread
596 uint32_t name = 0;
597 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
598 return name;
599}
600
Mathias Agopian3f844832013-08-07 21:24:32 -0700601void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700602 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700603}
604
Wei Wangf9b05ee2017-07-19 20:59:39 -0700605// Do not call property_set on main thread which will be blocked by init
606// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700607void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700608 ALOGI( "SurfaceFlinger's main thread ready to run. "
609 "Initializing graphics H/W...");
610
Ana Krulec757f63a2019-01-25 10:46:18 -0800611 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900612
Steven Thomasb02664d2017-07-26 18:48:28 -0700613 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800614
Dominik Laskowski83b88212018-12-11 13:34:06 -0800615 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -0800616
Steven Thomasb02664d2017-07-26 18:48:28 -0700617 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700618 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700619 mScheduler = getFactory().createScheduler([this](bool enabled) {
620 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
621 });
Ana Krulec757f63a2019-01-25 10:46:18 -0800622 // TODO(b/113612090): Currently we assume that if scheduler is turned on, then the refresh
623 // rate is 90. Once b/122905403 is completed, this should be updated accordingly.
624 mPhaseOffsets->setRefreshRateType(
625 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700626
Ana Krulec98b5b242018-08-10 15:03:23 -0700627 mAppConnectionHandle =
Ana Krulec757f63a2019-01-25 10:46:18 -0800628 mScheduler->createConnection("appConnection", mPhaseOffsets->getCurrentAppOffset(),
Dominik Laskowskif654d572018-12-20 11:03:06 -0800629 resyncCallback,
Ana Krulec98b5b242018-08-10 15:03:23 -0700630 impl::EventThread::InterceptVSyncsCallback());
631 mSfConnectionHandle =
Ana Krulec757f63a2019-01-25 10:46:18 -0800632 mScheduler->createConnection("sfConnection", mPhaseOffsets->getCurrentSfOffset(),
Dominik Laskowskif654d572018-12-20 11:03:06 -0800633 resyncCallback, [this](nsecs_t timestamp) {
Ana Krulec98b5b242018-08-10 15:03:23 -0700634 mInterceptor->saveVSyncEvent(timestamp);
635 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800636
Ana Krulec98b5b242018-08-10 15:03:23 -0700637 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700638 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
639 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700640 } else {
641 mEventThreadSource =
642 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800643 mPhaseOffsets->getCurrentAppOffset(), true, "app");
Ana Krulec98b5b242018-08-10 15:03:23 -0700644 mEventThread =
645 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700646 impl::EventThread::InterceptVSyncsCallback(),
647 "appEventThread");
648 mSfEventThreadSource =
649 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800650 mPhaseOffsets->getCurrentSfOffset(), true, "sf");
Ana Krulec98b5b242018-08-10 15:03:23 -0700651
652 mSFEventThread =
653 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700654 [this](nsecs_t timestamp) {
655 mInterceptor->saveVSyncEvent(timestamp);
656 },
657 "sfEventThread");
Dominik Laskowskif654d572018-12-20 11:03:06 -0800658 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Ana Krulec98b5b242018-08-10 15:03:23 -0700659 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
660 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800661
Steven Thomasb02664d2017-07-26 18:48:28 -0700662 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700663 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700664 renderEngineFeature |= (useColorManagement ?
665 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700666 renderEngineFeature |= (useContextPriority ?
667 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700668
669 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700670 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700671 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700672 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700673
674 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
675 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700676 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
677 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800678 // Process any initial hotplug and resulting display changes.
679 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700680 const auto display = getDefaultDisplayDeviceLocked();
681 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700682 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700683 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800684
Steven Thomas050b2c82017-03-06 11:45:16 -0800685 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700686 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700687 // This callback is called from the vr flinger dispatch thread. We
688 // need to call signalTransaction(), which requires holding
689 // mStateLock when we're not on the main thread. Acquiring
690 // mStateLock from the vr flinger dispatch thread might trigger a
691 // deadlock in surface flinger (see b/66916578), so post a message
692 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700693 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700694 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
695 mVrFlingerRequestsDisplay = requestDisplay;
696 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700697 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800698 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700699 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
700 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700701 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700702 .value_or(0),
703 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800704 if (!mVrFlinger) {
705 ALOGE("Failed to start vrflinger");
706 }
707 }
708
Lloyd Pique90c115d2018-09-18 21:39:42 -0700709 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700710 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700711
Mathias Agopian92a979a2012-08-02 18:32:23 -0700712 // initialize our drawing state
713 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700714
Andy McFadden13a082e2012-08-24 10:16:42 -0700715 // set initial conditions (e.g. unblank default device)
716 initializeDisplays();
717
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700718 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700719
Wei Wangf9b05ee2017-07-19 20:59:39 -0700720 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700721
722 const bool presentFenceReliable =
723 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
724 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700725
726 if (mStartPropertySetThread->Start() != NO_ERROR) {
727 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800728 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800729
Ana Krulec7d1d6832018-12-27 11:10:09 -0800730 if (mUseScheduler) {
Ana Krulec757f63a2019-01-25 10:46:18 -0800731 mScheduler->setExpiredIdleTimerCallback([this]() {
732 mPhaseOffsets->setRefreshRateType(
733 scheduler::RefreshRateConfigs::RefreshRateType::DEFAULT);
734 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
735 mVsyncModulator.setPhaseOffsets(early, gl, late);
736 setRefreshRateTo(60.f /* fps */);
737 });
738 mScheduler->setResetIdleTimerCallback([this]() {
739 mPhaseOffsets->setRefreshRateType(
740 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
741 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
742 mVsyncModulator.setPhaseOffsets(early, gl, late);
743 setRefreshRateTo(90.f /* fps */);
744 });
Ana Krulecb43429d2019-01-09 14:28:51 -0800745 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(
746 getHwComposer().getConfigs(*display->getId()));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800747 }
748
Dan Stoza9e56aa02015-11-02 13:00:03 -0800749 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700750}
751
Romain Guy11d63f42017-07-20 12:47:14 -0700752void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700753 Mutex::Autolock _l(mStateLock);
754
Romain Guy11d63f42017-07-20 12:47:14 -0700755 char value[PROPERTY_VALUE_MAX];
756
757 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800758 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700759 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800760 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100761
762 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700763 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700764}
765
Mathias Agopiana67e4182012-06-19 17:26:12 -0700766void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800767 // Start boot animation service by setting a property mailbox
768 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700769 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800770 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700771 if (mStartPropertySetThread->join() != NO_ERROR) {
772 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800773 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700774}
775
Mathias Agopian875d8e12013-06-07 15:35:48 -0700776size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700777 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700778}
779
Mathias Agopian875d8e12013-06-07 15:35:48 -0700780size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700781 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700782}
783
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800784// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800785
Jamie Gennis582270d2011-08-17 18:19:00 -0700786bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800787 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800788 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800789 return authenticateSurfaceTextureLocked(bufferProducer);
790}
791
792bool SurfaceFlinger::authenticateSurfaceTextureLocked(
793 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800794 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800795 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800796}
797
Brian Anderson6b376712017-04-04 10:51:39 -0700798status_t SurfaceFlinger::getSupportedFrameTimestamps(
799 std::vector<FrameEvent>* outSupported) const {
800 *outSupported = {
801 FrameEvent::REQUESTED_PRESENT,
802 FrameEvent::ACQUIRE,
803 FrameEvent::LATCH,
804 FrameEvent::FIRST_REFRESH_START,
805 FrameEvent::LAST_REFRESH_START,
806 FrameEvent::GPU_COMPOSITION_DONE,
807 FrameEvent::DEQUEUE_READY,
808 FrameEvent::RELEASE,
809 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700810 ConditionalLock _l(mStateLock,
811 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700812 if (!getHwComposer().hasCapability(
813 HWC2::Capability::PresentFenceIsNotReliable)) {
814 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
815 }
816 return NO_ERROR;
817}
818
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700819status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
820 Vector<DisplayInfo>* configs) {
821 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700822 return BAD_VALUE;
823 }
824
Dominik Laskowski075d3172018-05-24 15:50:06 -0700825 const auto displayId = getPhysicalDisplayId(displayToken);
826 if (!displayId) {
827 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700828 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700829
Mathias Agopian8b736f12012-08-13 17:54:26 -0700830 // TODO: Not sure if display density should handled by SF any longer
831 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700832 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700833 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700834 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800835 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700836 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700837 }
838 return density;
839 }
840 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700841 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700842 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700843 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700844 return getDensityFromProperty("ro.sf.lcd_density"); }
845 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700846
Dan Stoza7f7da322014-05-02 15:26:25 -0700847 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700848
Steven Thomas6d8110b2017-08-31 18:24:21 -0700849 ConditionalLock _l(mStateLock,
850 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700851 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700852 DisplayInfo info = DisplayInfo();
853
Dan Stoza9e56aa02015-11-02 13:00:03 -0800854 float xdpi = hwConfig->getDpiX();
855 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700856
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700857 info.w = hwConfig->getWidth();
858 info.h = hwConfig->getHeight();
859 // Default display viewport to display width and height
860 info.viewportW = info.w;
861 info.viewportH = info.h;
862
Dominik Laskowski075d3172018-05-24 15:50:06 -0700863 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700864 // The density of the device is provided by a build property
865 float density = Density::getBuildDensity() / 160.0f;
866 if (density == 0) {
867 // the build doesn't provide a density -- this is wrong!
868 // use xdpi instead
869 ALOGE("ro.sf.lcd_density must be defined as a build property");
870 density = xdpi / 160.0f;
871 }
872 if (Density::getEmuDensity()) {
873 // if "qemu.sf.lcd_density" is specified, it overrides everything
874 xdpi = ydpi = density = Density::getEmuDensity();
875 density /= 160.0f;
876 }
877 info.density = density;
878
879 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700880 const auto display = getDefaultDisplayDeviceLocked();
881 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700882
883 // This is for screenrecord
884 const Rect viewport = display->getViewport();
885 if (viewport.isValid()) {
886 info.viewportW = uint32_t(viewport.getWidth());
887 info.viewportH = uint32_t(viewport.getHeight());
888 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700889 } else {
890 // TODO: where should this value come from?
891 static const int TV_DENSITY = 213;
892 info.density = TV_DENSITY / 160.0f;
893 info.orientation = 0;
894 }
895
Dan Stoza7f7da322014-05-02 15:26:25 -0700896 info.xdpi = xdpi;
897 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800898 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800899 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800900
Andy McFadden91b2ca82014-06-13 14:04:23 -0700901 // This is how far in advance a buffer must be queued for
902 // presentation at a given time. If you want a buffer to appear
903 // on the screen at time N, you must submit the buffer before
904 // (N - presentationDeadline).
905 //
906 // Normally it's one full refresh period (to give SF a chance to
907 // latch the buffer), but this can be reduced by configuring a
908 // DispSync offset. Any additional delays introduced by the hardware
909 // composer or panel must be accounted for here.
910 //
911 // We add an additional 1ms to allow for processing time and
912 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800913 info.presentationDeadline =
914 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700915
916 // All non-virtual displays are currently considered secure.
917 info.secure = true;
918
Dominik Laskowski075d3172018-05-24 15:50:06 -0700919 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700920 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800921 std::swap(info.w, info.h);
922 }
923
Michael Wright28f24d02016-07-12 13:30:53 -0700924 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700925 }
926
Dan Stoza7f7da322014-05-02 15:26:25 -0700927 return NO_ERROR;
928}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700929
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700930status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
931 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700932 return BAD_VALUE;
933 }
934
Ana Krulece588e312018-09-18 12:32:24 -0700935 if (mUseScheduler) {
936 mScheduler->getDisplayStatInfo(stats);
937 } else {
938 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
939 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
940 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700941 return NO_ERROR;
942}
943
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700944int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
945 const auto display = getDisplayDevice(displayToken);
946 if (!display) {
947 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800948 return BAD_VALUE;
949 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700950
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700951 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700952}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700953
Ana Krulec7d1d6832018-12-27 11:10:09 -0800954status_t SurfaceFlinger::setActiveConfigAsync(const sp<IBinder>& displayToken, int mode) {
955 ATRACE_NAME("setActiveConfigAsync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800956 postMessageAsync(new LambdaMessage(
957 [=]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800958 return NO_ERROR;
959}
960
961status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
962 ATRACE_NAME("setActiveConfigSync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800963 postMessageSync(new LambdaMessage(
964 [&]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800965 return NO_ERROR;
966}
967
968void SurfaceFlinger::setActiveConfigInternal(const sp<IBinder>& displayToken, int mode) {
969 Vector<DisplayInfo> configs;
970 getDisplayConfigs(displayToken, &configs);
971 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
972 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
973 return;
974 }
975
976 const auto display = getDisplayDevice(displayToken);
977 if (!display) {
978 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
979 displayToken.get());
980 return;
981 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700982 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800983 ALOGW("Attempt to set active config %d for virtual display", mode);
984 return;
985 }
986 int currentDisplayPowerMode = display->getPowerMode();
987 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
988 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700989 return;
990 }
991
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700992 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700993 if (mode == currentMode) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800994 // Don't update config if we are already running in the desired mode.
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700995 return;
996 }
Ana Krulecb43429d2019-01-09 14:28:51 -0800997 if (mUseScheduler) {
998 mRefreshRateStats->setConfigMode(mode);
999 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001000
Dominik Laskowski075d3172018-05-24 15:50:06 -07001001 const auto displayId = display->getId();
1002 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001003
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001004 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001005 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001006
Ana Krulec7d1d6832018-12-27 11:10:09 -08001007 ATRACE_INT("ActiveConfigMode", mode);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001008 resyncToHardwareVsync(true, getVsyncPeriod());
Mathias Agopianc666cae2012-07-25 18:56:13 -07001009}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001010
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001011status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1012 Vector<ColorMode>* outColorModes) {
1013 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001014 return BAD_VALUE;
1015 }
1016
Dominik Laskowski075d3172018-05-24 15:50:06 -07001017 const auto displayId = getPhysicalDisplayId(displayToken);
1018 if (!displayId) {
1019 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -07001020 }
1021
Peiyong Lina52f0292018-03-14 17:26:31 -07001022 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001023 {
1024 ConditionalLock _l(mStateLock,
1025 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001026 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001027 }
Michael Wright28f24d02016-07-12 13:30:53 -07001028 outColorModes->clear();
1029 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1030
1031 return NO_ERROR;
1032}
1033
Daniel Solomon42d04562019-01-20 21:03:19 -08001034status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1035 ui::DisplayPrimaries &primaries) {
1036 if (!displayToken) {
1037 return BAD_VALUE;
1038 }
1039
1040 // Currently we only support this API for a single internal display.
1041 if (getInternalDisplayToken() != displayToken) {
1042 return BAD_VALUE;
1043 }
1044
1045 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1046 return NO_ERROR;
1047}
1048
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001049ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1050 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001051 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001052 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001053 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001054}
1055
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001056status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001057 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001058 Vector<ColorMode> modes;
1059 getDisplayColorModes(displayToken, &modes);
1060 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1061 if (mode < ColorMode::NATIVE || !exists) {
1062 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1063 decodeColorMode(mode).c_str(), mode, displayToken.get());
1064 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001065 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001066 const auto display = getDisplayDevice(displayToken);
1067 if (!display) {
1068 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1069 decodeColorMode(mode).c_str(), mode, displayToken.get());
1070 } else if (display->isVirtual()) {
1071 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1072 decodeColorMode(mode).c_str(), mode);
1073 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001074 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1075 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001076 }
1077 }));
1078
Michael Wright28f24d02016-07-12 13:30:53 -07001079 return NO_ERROR;
1080}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001081
Svetoslavd85084b2014-03-20 10:28:31 -07001082status_t SurfaceFlinger::clearAnimationFrameStats() {
1083 Mutex::Autolock _l(mStateLock);
1084 mAnimFrameTracker.clearStats();
1085 return NO_ERROR;
1086}
1087
1088status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1089 Mutex::Autolock _l(mStateLock);
1090 mAnimFrameTracker.getStats(outStats);
1091 return NO_ERROR;
1092}
1093
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001094status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1095 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001096 Mutex::Autolock _l(mStateLock);
1097
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001098 const auto display = getDisplayDeviceLocked(displayToken);
1099 if (!display) {
1100 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001101 return BAD_VALUE;
1102 }
1103
Peiyong Linfb069302018-04-25 14:34:31 -07001104 // At this point the DisplayDeivce should already be set up,
1105 // meaning the luminance information is already queried from
1106 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001107 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001108 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1109 capabilities.getDesiredMaxLuminance(),
1110 capabilities.getDesiredMaxAverageLuminance(),
1111 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001112
1113 return NO_ERROR;
1114}
1115
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001116status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1117 ui::PixelFormat* outFormat,
1118 ui::Dataspace* outDataspace,
1119 uint8_t* outComponentMask) const {
1120 if (!outFormat || !outDataspace || !outComponentMask) {
1121 return BAD_VALUE;
1122 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001123 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001124 if (!display || !display->getId()) {
1125 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1126 return BAD_VALUE;
1127 }
1128 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1129 outDataspace, outComponentMask);
1130}
1131
Kevin DuBois74e53772018-11-19 10:52:38 -08001132status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1133 bool enable, uint8_t componentMask,
1134 uint64_t maxFrames) const {
1135 const auto display = getDisplayDevice(displayToken);
1136 if (!display || !display->getId()) {
1137 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1138 return BAD_VALUE;
1139 }
1140
1141 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1142 componentMask, maxFrames);
1143}
1144
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001145status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1146 uint64_t maxFrames, uint64_t timestamp,
1147 DisplayedFrameStats* outStats) const {
1148 const auto display = getDisplayDevice(displayToken);
1149 if (!display || !display->getId()) {
1150 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1151 return BAD_VALUE;
1152 }
1153
1154 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1155 outStats);
1156}
1157
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001158status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1159 if (!outSupported) {
1160 return BAD_VALUE;
1161 }
1162 *outSupported = getRenderEngine().supportsProtectedContent();
1163 return NO_ERROR;
1164}
1165
Marissa Wallebc2c052019-01-16 19:16:55 -08001166status_t SurfaceFlinger::cacheBuffer(const sp<IBinder>& token, const sp<GraphicBuffer>& buffer,
1167 int32_t* outBufferId) {
1168 if (!outBufferId) {
1169 return BAD_VALUE;
1170 }
1171 *outBufferId = mBufferStateLayerCache.add(token, buffer);
1172 return NO_ERROR;
1173}
1174
1175status_t SurfaceFlinger::uncacheBuffer(const sp<IBinder>& token, int32_t bufferId) {
1176 mBufferStateLayerCache.release(token, bufferId);
1177 return NO_ERROR;
1178}
1179
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001180status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1181 bool* outIsWideColorDisplay) const {
1182 if (!displayToken || !outIsWideColorDisplay) {
1183 return BAD_VALUE;
1184 }
1185 Mutex::Autolock _l(mStateLock);
1186 const auto display = getDisplayDeviceLocked(displayToken);
1187 if (!display) {
1188 return BAD_VALUE;
1189 }
1190 *outIsWideColorDisplay = display->hasWideColorGamut();
1191 return NO_ERROR;
1192}
1193
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001194status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001195 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001196 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001197
Chia-I Wu90f669f2017-10-05 14:24:41 -07001198 if (mInjectVSyncs == enable) {
1199 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001200 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001201
Dominik Laskowski83b88212018-12-11 13:34:06 -08001202 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001203
Ana Krulec98b5b242018-08-10 15:03:23 -07001204 // TODO(akrulec): Part of the Injector should be refactored, so that it
1205 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001206 if (enable) {
1207 ALOGV("VSync Injections enabled");
1208 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001209 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001210 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001211 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001212 impl::EventThread::InterceptVSyncsCallback(),
1213 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001214 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001215 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001216 } else {
1217 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001218 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001219 }
1220
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001221 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001222 }));
1223
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001224 return NO_ERROR;
1225}
1226
1227status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001228 Mutex::Autolock _l(mStateLock);
1229
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001230 if (!mInjectVSyncs) {
1231 ALOGE("VSync Injections not enabled");
1232 return BAD_VALUE;
1233 }
1234 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1235 ALOGV("Injecting VSync inside SurfaceFlinger");
1236 mVSyncInjector->onInjectSyncEvent(when);
1237 }
1238 return NO_ERROR;
1239}
1240
Lloyd Pique755e3192018-01-31 16:46:15 -08001241status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1242 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001243 // Try to acquire a lock for 1s, fail gracefully
1244 const status_t err = mStateLock.timedLock(s2ns(1));
1245 const bool locked = (err == NO_ERROR);
1246 if (!locked) {
1247 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1248 return TIMED_OUT;
1249 }
1250
1251 outLayers->clear();
1252 mCurrentState.traverseInZOrder([&](Layer* layer) {
1253 outLayers->push_back(layer->getLayerDebugInfo());
1254 });
1255
1256 mStateLock.unlock();
1257 return NO_ERROR;
1258}
1259
Peiyong Linc6780972018-10-28 15:24:08 -07001260status_t SurfaceFlinger::getCompositionPreference(
1261 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1262 Dataspace* outWideColorGamutDataspace,
1263 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001264 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001265 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001266 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001267 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001268 return NO_ERROR;
1269}
1270
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001271// ----------------------------------------------------------------------------
1272
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001273sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1274 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001275 auto resyncCallback = makeResyncCallback([this] {
1276 Mutex::Autolock lock(mStateLock);
1277 return getVsyncPeriod();
1278 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001279
Ana Krulec98b5b242018-08-10 15:03:23 -07001280 if (mUseScheduler) {
1281 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001282 return mScheduler->createDisplayEventConnection(mSfConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001283 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001284 return mScheduler->createDisplayEventConnection(mAppConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001285 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001286 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001287 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001288 return mSFEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001289 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001290 return mEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001291 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001292 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001293}
1294
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001295// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001296
1297void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001298 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001299}
1300
1301void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001302 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001303}
1304
1305void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001306 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001307}
1308
1309void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001310 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001311 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001312}
1313
1314status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001315 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001316 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001317}
1318
1319status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001320 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001321 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001322 if (res == NO_ERROR) {
1323 msg->wait();
1324 }
1325 return res;
1326}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001327
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001328void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001329 do {
1330 waitForEvent();
1331 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001332}
1333
Dominik Laskowski83b88212018-12-11 13:34:06 -08001334nsecs_t SurfaceFlinger::getVsyncPeriod() const {
1335 const auto displayId = getInternalDisplayId();
1336 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1337 return 0;
1338 }
1339
1340 const auto config = getHwComposer().getActiveConfig(*displayId);
1341 return config ? config->getVsyncPeriod() : 0;
1342}
1343
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001344void SurfaceFlinger::enableHardwareVsync() {
1345 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001346 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001347 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001348 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001349 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001350 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001351}
1352
Dominik Laskowski83b88212018-12-11 13:34:06 -08001353void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001354 Mutex::Autolock _l(mHWVsyncLock);
1355
Jesse Hall948fe0c2013-10-14 12:56:09 -07001356 if (makeAvailable) {
1357 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001358 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1359 if (mUseScheduler) {
1360 mScheduler->makeHWSyncAvailable(true);
1361 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001362 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001363 // Hardware vsync is not currently available, so abort the resync
1364 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001365 return;
1366 }
1367
Dominik Laskowski83b88212018-12-11 13:34:06 -08001368 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001369 return;
1370 }
1371
Ana Krulece588e312018-09-18 12:32:24 -07001372 if (mUseScheduler) {
1373 mScheduler->setVsyncPeriod(period);
1374 } else {
1375 mPrimaryDispSync->reset();
1376 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001377
Ana Krulece588e312018-09-18 12:32:24 -07001378 if (!mPrimaryHWVsyncEnabled) {
1379 mPrimaryDispSync->beginResync();
1380 mEventControlThread->setVsyncEnabled(true);
1381 mPrimaryHWVsyncEnabled = true;
1382 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001383 }
1384}
1385
Jesse Hall948fe0c2013-10-14 12:56:09 -07001386void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001387 Mutex::Autolock _l(mHWVsyncLock);
1388 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001389 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001390 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001391 mPrimaryHWVsyncEnabled = false;
1392 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001393 if (makeUnavailable) {
1394 mHWVsyncAvailable = false;
1395 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001396}
1397
Dominik Laskowski83b88212018-12-11 13:34:06 -08001398void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001399 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001400
Dan Stoza57164302017-05-08 14:03:54 -07001401 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001402 const nsecs_t last = lastResyncTime.exchange(now);
1403
1404 if (now - last > kIgnoreDelay) {
1405 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001406 }
1407}
1408
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001409void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1410 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001411 ATRACE_NAME("SF onVsync");
1412
Steven Thomas3cfac282017-02-06 12:29:30 -08001413 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001414 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001415 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001416 return;
1417 }
1418
Dominik Laskowski075d3172018-05-24 15:50:06 -07001419 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001420 return;
1421 }
1422
Dominik Laskowski075d3172018-05-24 15:50:06 -07001423 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001424 // For now, we don't do anything with external display vsyncs.
1425 return;
1426 }
1427
Ana Krulece588e312018-09-18 12:32:24 -07001428 if (mUseScheduler) {
1429 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001430 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001431 bool needsHwVsync = false;
1432 { // Scope for the lock
1433 Mutex::Autolock _l(mHWVsyncLock);
1434 if (mPrimaryHWVsyncEnabled) {
1435 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1436 }
1437 }
1438
1439 if (needsHwVsync) {
1440 enableHardwareVsync();
1441 } else {
1442 disableHardwareVsync(false);
1443 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001444 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001445}
1446
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001447void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001448 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1449 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001450}
1451
Ana Krulec7d1d6832018-12-27 11:10:09 -08001452void SurfaceFlinger::setRefreshRateTo(float newFps) {
1453 const auto displayId = getInternalDisplayId();
1454 if (!displayId || mBootStage != BootStage::FINISHED) {
1455 return;
1456 }
1457 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1458 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1459 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1460 // refresh cycle.
1461
1462 // Don't do any updating if the current fps is the same as the new one.
1463 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
1464 const nsecs_t currentVsyncPeriod = activeConfig->getVsyncPeriod();
1465 if (currentVsyncPeriod == 0) {
1466 return;
1467 }
1468 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1469 // floating numbers.
1470 const float currentFps = 1e9 / currentVsyncPeriod;
1471 if (std::abs(currentFps - newFps) <= 1) {
1472 return;
1473 }
1474
1475 auto configs = getHwComposer().getConfigs(*displayId);
1476 for (int i = 0; i < configs.size(); i++) {
1477 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1478 if (vsyncPeriod == 0) {
1479 continue;
1480 }
1481 const float fps = 1e9 / vsyncPeriod;
1482 // TODO(b/113612090): There should be a better way at determining which config
1483 // has the right refresh rate.
1484 if (std::abs(fps - newFps) <= 1) {
1485 const auto display = getBuiltInDisplay(HWC_DISPLAY_PRIMARY);
1486 if (!display) return;
1487 // This is posted in async function to avoid deadlock when getDisplayDevice
1488 // requires mStateLock.
1489 setActiveConfigAsync(display, i);
1490 ATRACE_INT("FPS", newFps);
1491 }
1492 }
1493}
1494
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001495void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001496 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001497 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001498 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001499
Lloyd Piqueba04e622017-12-14 17:11:26 -08001500 // Ignore events that do not have the right sequenceId.
1501 if (sequenceId != getBE().mComposerSequenceId) {
1502 return;
1503 }
1504
Steven Thomasb02664d2017-07-26 18:48:28 -07001505 // Only lock if we're not on the main thread. This function is normally
1506 // called on a hwbinder thread, but for the primary display it's called on
1507 // the main thread with the state lock already held, so don't attempt to
1508 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001509 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001510
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001511 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001512
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001513 if (std::this_thread::get_id() == mMainThreadId) {
1514 // Process all pending hot plug events immediately if we are on the main thread.
1515 processDisplayHotplugEventsLocked();
1516 }
1517
Lloyd Piqueba04e622017-12-14 17:11:26 -08001518 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001519}
1520
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001521void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001522 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001523 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001524 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001525 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001526 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001527}
1528
Dominik Laskowski075d3172018-05-24 15:50:06 -07001529void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001530 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001531 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001532 if (const auto displayId = getInternalDisplayId()) {
1533 getHwComposer().setVsyncEnabled(*displayId,
1534 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1535 }
Mathias Agopian86303202012-07-24 22:46:10 -07001536}
1537
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001538// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001539void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001540 if (mUseScheduler) {
1541 mScheduler->disableHardwareVsync(true);
1542 } else {
1543 disableHardwareVsync(true);
1544 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001545 // Clear the drawing state so that the logic inside of
1546 // handleTransactionLocked will fire. It will determine the delta between
1547 // mCurrentState and mDrawingState and re-apply all changes when we make the
1548 // transition.
1549 mDrawingState.displays.clear();
1550 mDisplays.clear();
1551}
1552
Steven Thomas050b2c82017-03-06 11:45:16 -08001553void SurfaceFlinger::updateVrFlinger() {
1554 if (!mVrFlinger)
1555 return;
1556 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001557 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001558 return;
1559 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001560
Lloyd Pique441d5042018-10-18 16:49:51 -07001561 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001562 ALOGE("Vr flinger is only supported for remote hardware composer"
1563 " service connections. Ignoring request to transition to vr"
1564 " flinger.");
1565 mVrFlingerRequestsDisplay = false;
1566 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001567 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001568
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001569 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001570
Steven Thomas0123ac62018-07-12 11:32:34 -07001571 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001572 LOG_ALWAYS_FATAL_IF(!display);
1573 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001574 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1575 // called below. Clear the reference now so we don't accidentally use it
1576 // later.
1577 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001578
Steven Thomasb02664d2017-07-26 18:48:28 -07001579 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001580 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001581 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001582
Steven Thomasb02664d2017-07-26 18:48:28 -07001583 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001584 // Delete the current instance before creating the new one
1585 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1586 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1587 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1588 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001589
Lloyd Pique441d5042018-10-18 16:49:51 -07001590 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001591 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001592
1593 if (vrFlingerRequestsDisplay) {
1594 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001595 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001596
1597 mVisibleRegionsDirty = true;
1598 invalidateHwcGeometry();
1599
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001600 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001601 display = getDefaultDisplayDeviceLocked();
1602 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001603 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001604
Steven Thomasb02664d2017-07-26 18:48:28 -07001605 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001606 const nsecs_t vsyncPeriod = getVsyncPeriod();
1607 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001608
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001609 // The present fences returned from vr_hwc are not an accurate
1610 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001611 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001612 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1613 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001614 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001615 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001616 !hasSyncFramework);
1617 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001618
Steven Thomasb02664d2017-07-26 18:48:28 -07001619 // Use phase of 0 since phase is not known.
1620 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001621 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001622 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001623
Dominik Laskowski83b88212018-12-11 13:34:06 -08001624 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001625
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001626 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001627 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001628}
1629
Mathias Agopian4fec8732012-06-29 14:12:52 -07001630void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001631 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001632 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001633 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001634 if (mUseScheduler) {
1635 // This call is made each time SF wakes up and creates a new frame.
1636 mScheduler->incrementFrameCounter();
1637 }
Dan Stoza50182882016-07-08 12:02:20 -07001638 bool frameMissed = !mHadClientComposition &&
1639 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001640 (mPreviousPresentFence->getSignalTime() ==
1641 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001642 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001643 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001644 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001645 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001646 if (mPropagateBackpressure) {
1647 signalLayerUpdate();
1648 break;
1649 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001650 }
Dan Stoza50182882016-07-08 12:02:20 -07001651
Steven Thomas050b2c82017-03-06 11:45:16 -08001652 // Now that we're going to make it to the handleMessageTransaction()
1653 // call below it's safe to call updateVrFlinger(), which will
1654 // potentially trigger a display handoff.
1655 updateVrFlinger();
1656
Dan Stoza6b9454d2014-11-07 16:00:59 -08001657 bool refreshNeeded = handleMessageTransaction();
1658 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001659 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001660 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001661 // Signal a refresh if a transaction modified the window state,
1662 // a new buffer was latched, or if HWC has requested a full
1663 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001664 signalRefresh();
1665 }
1666 break;
1667 }
1668 case MessageQueue::REFRESH: {
1669 handleMessageRefresh();
1670 break;
1671 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001672 }
1673}
1674
Dan Stoza6b9454d2014-11-07 16:00:59 -08001675bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001676 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001677
1678 // Apply any ready transactions in the queues if there are still transactions that have not been
1679 // applied, wake up during the next vsync period and check again
1680 bool transactionNeeded = false;
1681 if (!flushTransactionQueues()) {
1682 transactionNeeded = true;
1683 }
1684
Mathias Agopian4fec8732012-06-29 14:12:52 -07001685 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001686 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001687 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001688
1689 if (transactionNeeded) {
1690 setTransactionFlags(eTransactionNeeded);
1691 }
1692
1693 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001694}
1695
Mathias Agopian4fec8732012-06-29 14:12:52 -07001696void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001697 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001698
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001699 mRefreshPending = false;
1700
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001701 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001702 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001703 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001704 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001705 for (const auto& [token, display] : mDisplays) {
1706 beginFrame(display);
1707 prepareFrame(display);
1708 doDebugFlashRegions(display, repaintEverything);
1709 doComposition(display, repaintEverything);
1710 }
1711
Adrian Roos1e1a1282017-11-01 19:05:31 +01001712 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001713 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001714
1715 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001716 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001717
Dan Stozabfbffeb2016-07-21 14:49:33 -07001718 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001719 for (const auto& [token, displayDevice] : mDisplays) {
1720 auto display = displayDevice->getCompositionDisplay();
1721 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001722 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001723 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001724 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001725
Alec Mouri86770e52018-09-24 22:40:58 +00001726 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001727 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001728 if (mHadClientComposition) {
1729 base::unique_fd flushFence(getRenderEngine().flush());
1730 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1731 getBE().flushFence = new Fence(std::move(flushFence));
1732 } else {
1733 // Cleanup for hygiene.
1734 getBE().flushFence = Fence::NO_FENCE;
1735 }
1736 }
1737
Jorim Jaggi90535212018-05-23 23:44:06 +02001738 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001739
David Sodman7e4ae112018-02-09 15:02:28 -08001740 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001741 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001742 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001743 compositionInfo.hwc.hwcLayer = nullptr;
1744 }
David Sodmanba340492018-08-05 21:51:33 -07001745 }
David Sodman7e4ae112018-02-09 15:02:28 -08001746
1747 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001748}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001749
David Sodmanfa9b2af2017-12-24 13:28:59 -08001750
1751bool SurfaceFlinger::handleMessageInvalidate() {
1752 ATRACE_CALL();
1753 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001754}
1755
David Sodman79bba0e2018-08-05 18:07:49 -07001756void SurfaceFlinger::calculateWorkingSet() {
1757 ATRACE_CALL();
1758 ALOGV(__FUNCTION__);
1759
David Sodman79bba0e2018-08-05 18:07:49 -07001760 // build the h/w work list
1761 if (CC_UNLIKELY(mGeometryInvalid)) {
1762 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001763 for (const auto& [token, displayDevice] : mDisplays) {
1764 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001765 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001766 if (!displayId) {
1767 continue;
1768 }
David Sodman79bba0e2018-08-05 18:07:49 -07001769
Lloyd Pique32cbe282018-10-19 13:09:22 -07001770 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001771 for (size_t i = 0; i < currentLayers.size(); i++) {
1772 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001773
Dominik Laskowski075d3172018-05-24 15:50:06 -07001774 if (!layer->hasHwcLayer(*displayId)) {
1775 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1776 layer->forceClientComposition(*displayId);
1777 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001778 }
1779 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001780
Lloyd Pique32cbe282018-10-19 13:09:22 -07001781 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001782 if (mDebugDisableHWC || mDebugRegion) {
1783 layer->forceClientComposition(*displayId);
1784 }
David Sodman79bba0e2018-08-05 18:07:49 -07001785 }
1786 }
1787 }
1788
1789 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001790 for (const auto& [token, displayDevice] : mDisplays) {
1791 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001792 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001793 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001794 continue;
1795 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001796 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001797
1798 if (mDrawingState.colorMatrixChanged) {
1799 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001800 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001801 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001802 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001803 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001804 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1805 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001806 !profile->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001807 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001808 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1809 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001810 !profile->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001811 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001812 }
1813
Peiyong Lind3788632018-09-18 16:01:31 -07001814 // TODO(b/111562338) remove when composer 2.3 is shipped.
1815 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001816 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001817 }
1818
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001819 if (layer->getRoundedCornerState().radius > 0.0f) {
1820 layer->forceClientComposition(*displayId);
1821 }
1822
Dominik Laskowski075d3172018-05-24 15:50:06 -07001823 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001824 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001825 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001826 continue;
1827 }
1828
Lloyd Pique32cbe282018-10-19 13:09:22 -07001829 const auto& displayState = display->getState();
1830 layer->setPerFrameData(*displayId, displayState.transform, displayState.viewport,
1831 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001832 }
1833
Peiyong Lin13effd12018-07-24 17:01:47 -07001834 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001835 ColorMode colorMode;
1836 Dataspace dataSpace;
1837 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001838 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001839 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001840 }
1841 }
1842
1843 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001844
1845 for (const auto& [token, display] : mDisplays) {
1846 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001847 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001848 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001849
1850 if (displayId) {
1851 if (!layer->setHwcLayer(*displayId)) {
1852 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1853 }
1854 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001855 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001856
Dominik Laskowski05275f12018-11-01 15:03:24 -07001857 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001858 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1859 }
1860 }
David Sodman79bba0e2018-08-05 18:07:49 -07001861}
1862
Lloyd Pique32cbe282018-10-19 13:09:22 -07001863void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1864 bool repaintEverything) {
1865 auto display = displayDevice->getCompositionDisplay();
1866 const auto& displayState = display->getState();
1867
Mathias Agopiancd60f992012-08-16 16:28:27 -07001868 // is debugging enabled
1869 if (CC_LIKELY(!mDebugRegion))
1870 return;
1871
Lloyd Pique32cbe282018-10-19 13:09:22 -07001872 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001873 // transform the dirty region into this screen's coordinate space
Alec Mouri0f714832018-11-12 15:31:06 -08001874 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001875 if (!dirtyRegion.isEmpty()) {
Alec Mouri0f714832018-11-12 15:31:06 -08001876 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001877 // redraw the whole screen
Alec Mouri0f714832018-11-12 15:31:06 -08001878 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001879
Alec Mouri0f714832018-11-12 15:31:06 -08001880 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001881 }
1882 }
1883
Lloyd Pique32cbe282018-10-19 13:09:22 -07001884 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001885
1886 if (mDebugRegion > 1) {
1887 usleep(mDebugRegion * 1000);
1888 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001889
Lloyd Pique32cbe282018-10-19 13:09:22 -07001890 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001891}
1892
Adrian Roos1e1a1282017-11-01 19:05:31 +01001893void SurfaceFlinger::doTracing(const char* where) {
1894 ATRACE_CALL();
1895 ATRACE_NAME(where);
1896 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001897 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001898 }
1899}
1900
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001901void SurfaceFlinger::logLayerStats() {
1902 ATRACE_CALL();
1903 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001904 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001905 if (display->isPrimary()) {
1906 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001907 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001908 }
1909 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001910
1911 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001912 }
1913}
1914
David Sodman2b406362017-12-15 13:33:47 -08001915void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001916{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001917 ATRACE_CALL();
1918 ALOGV("preComposition");
1919
David Sodman2b406362017-12-15 13:33:47 -08001920 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1921
Mathias Agopiancd60f992012-08-16 16:28:27 -07001922 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001923 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001924 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001925 needExtraInvalidate = true;
1926 }
Robert Carr2047fae2016-11-28 14:09:09 -08001927 });
1928
Mathias Agopiancd60f992012-08-16 16:28:27 -07001929 if (needExtraInvalidate) {
1930 signalLayerUpdate();
1931 }
1932}
1933
Ana Krulece588e312018-09-18 12:32:24 -07001934void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1935 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001936 // Update queue of past composite+present times and determine the
1937 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001938 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001939 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001940 while (!getBE().mCompositePresentTimes.empty()) {
1941 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001942 // Cached values should have been updated before calling this method,
1943 // which helps avoid duplicate syscalls.
1944 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1945 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1946 break;
1947 }
1948 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001949 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001950 }
1951
1952 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001953 while (getBE().mCompositePresentTimes.size() > 16) {
1954 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001955 }
1956
Ana Krulece588e312018-09-18 12:32:24 -07001957 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001958}
1959
Ana Krulece588e312018-09-18 12:32:24 -07001960void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1961 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001962 // Integer division and modulo round toward 0 not -inf, so we need to
1963 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001964 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1965 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1966 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001967
Ana Krulec757f63a2019-01-25 10:46:18 -08001968 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001969 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001970 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001971 }
1972
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001973 // Snap the latency to a value that removes scheduling jitter from the
1974 // composition and present times, which often have >1ms of jitter.
1975 // Reducing jitter is important if an app attempts to extrapolate
1976 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001977 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001978 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001979 nsecs_t bias = stats.vsyncPeriod / 2;
1980 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1981 nsecs_t snappedCompositeToPresentLatency =
1982 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001983
David Sodman99974d22017-11-28 12:04:33 -08001984 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001985 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1986 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001987 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001988}
1989
Ady Abraham8164d482019-01-11 14:47:59 -08001990// debug patch for b/119477596 - add stack guards to catch stack
1991// corruptions and disable clang optimizations.
1992// The code below is temporary and planned to be removed once stack
1993// corruptions are found.
1994#pragma clang optimize off
1995class StackGuard {
1996public:
1997 StackGuard(const char* name, const char* func, int line) {
1998 guarders.reserve(MIN_CAPACITY);
1999 guarders.push_back({this, name, func, line});
2000 validate();
2001 }
2002 ~StackGuard() {
2003 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
2004 if (i->guard == this) {
2005 guarders.erase(i);
2006 break;
2007 }
2008 }
2009 }
2010
2011 static void validate() {
2012 for (const auto& guard : guarders) {
2013 if (guard.guard->cookie != COOKIE_VALUE) {
2014 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
2015 CallStack stack(LOG_TAG);
2016 abort();
2017 }
2018 }
2019 }
2020
2021private:
2022 uint64_t cookie = COOKIE_VALUE;
2023 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
2024 static constexpr size_t MIN_CAPACITY = 16;
2025
2026 struct GuarderElement {
2027 StackGuard* guard;
2028 const char* name;
2029 const char* func;
2030 int line;
2031 };
2032
2033 static std::vector<GuarderElement> guarders;
2034};
2035std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2036
2037#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2038
2039#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002040void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002041{
Ady Abraham8164d482019-01-11 14:47:59 -08002042 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002043 ATRACE_CALL();
2044 ALOGV("postComposition");
2045
Brian Anderson3546a3f2016-07-14 11:51:14 -07002046 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002047 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002048 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002049 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002050 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002051 }
Ady Abraham8164d482019-01-11 14:47:59 -08002052 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002053
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002054 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002055 const auto displayDevice = getDefaultDisplayDeviceLocked();
2056 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002057
David Sodman73beded2017-11-15 11:56:06 -08002058 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002059 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002060 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2061
Lloyd Pique32cbe282018-10-19 13:09:22 -07002062 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002063 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002064 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2065 ->getRenderSurface()
2066 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002067 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002068 } else {
2069 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2070 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002071
Ady Abraham8164d482019-01-11 14:47:59 -08002072 ASSERT_ON_STACK_GUARD();
2073
David Sodman73beded2017-11-15 11:56:06 -08002074 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002075 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2076 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002077 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002078 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002079 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002080
Ana Krulece588e312018-09-18 12:32:24 -07002081 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002082 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002083 if (mUseScheduler) {
2084 mScheduler->getDisplayStatInfo(&stats);
2085 } else {
2086 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2087 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2088 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002089
Ady Abraham8164d482019-01-11 14:47:59 -08002090 ASSERT_ON_STACK_GUARD();
2091
David Sodman2b406362017-12-15 13:33:47 -08002092 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002093 // when we started doing work for this frame, but that should be okay
2094 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002095 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002096 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002097 DEFINE_STACK_GUARD(compositorTiming);
2098
Brian Andersond0010582017-03-07 13:20:31 -08002099 {
David Sodman99974d22017-11-28 12:04:33 -08002100 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002101 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002102 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002103
2104 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002105 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002106
Robert Carr2047fae2016-11-28 14:09:09 -08002107 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002108 bool frameLatched =
2109 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2110 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002111 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002112 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002113 recordBufferingStats(layer->getName().string(),
2114 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002115 }
Ady Abraham8164d482019-01-11 14:47:59 -08002116 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002117 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002118
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002119 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002120 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002121 if (mUseScheduler) {
2122 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002123 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002124 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002125 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2126 enableHardwareVsync();
2127 } else {
2128 disableHardwareVsync(false);
2129 }
Ady Abraham8164d482019-01-11 14:47:59 -08002130 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002131 }
2132 }
2133
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002134 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002135 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2136 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002137 if (mUseScheduler) {
2138 mScheduler->enableHardwareVsync();
2139 } else {
2140 enableHardwareVsync();
2141 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002142 }
2143 }
2144
Ady Abraham8164d482019-01-11 14:47:59 -08002145 ASSERT_ON_STACK_GUARD();
2146
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002147 if (mAnimCompositionPending) {
2148 mAnimCompositionPending = false;
2149
Brian Anderson4e606e32017-03-16 15:34:57 -07002150 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002151 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002152 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002153
2154 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002155 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002156 // The HWC doesn't support present fences, so use the refresh
2157 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002158 const nsecs_t presentTime =
2159 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002160 DEFINE_STACK_GUARD(presentTime);
2161
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002162 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002163 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002164 }
2165 mAnimFrameTracker.advanceFrame();
2166 }
Dan Stozab90cf072015-03-05 11:05:59 -08002167
Ady Abraham8164d482019-01-11 14:47:59 -08002168 ASSERT_ON_STACK_GUARD();
2169
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002170 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002171 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002172 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002173 }
2174
Ady Abraham8164d482019-01-11 14:47:59 -08002175 ASSERT_ON_STACK_GUARD();
2176
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002177 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002178
Ady Abraham8164d482019-01-11 14:47:59 -08002179 ASSERT_ON_STACK_GUARD();
2180
Lloyd Pique32cbe282018-10-19 13:09:22 -07002181 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2182 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002183 return;
2184 }
2185
2186 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002187 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002188 if (mHasPoweredOff) {
2189 mHasPoweredOff = false;
2190 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002191 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002192 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002193 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002194 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002195 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2196 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002197 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002198 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002199 }
David Sodman4a36e932017-11-07 14:29:47 -08002200 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002201
2202 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002203 }
David Sodman4a36e932017-11-07 14:29:47 -08002204 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002205 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002206
2207 {
2208 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002209 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002210 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002211 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002212 if (refillCount > 0) {
2213 const size_t offset = mTexturePool.size();
2214 mTexturePool.resize(mTexturePoolSize);
2215 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2216 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2217 }
Ady Abraham8164d482019-01-11 14:47:59 -08002218 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002219 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002220
Marissa Wallfda30bb2018-10-12 11:34:28 -07002221 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002222 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002223
2224 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002225}
Ady Abraham8164d482019-01-11 14:47:59 -08002226#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002227
2228void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002229 ATRACE_CALL();
2230 ALOGV("rebuildLayerStacks");
2231
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002232 // We need to clear these out now as these may be holding on to a
2233 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2234 // also holds a reference. When the set of visible layers is recomputed,
2235 // some layers may be destroyed if the only thing keeping them alive was
2236 // that list of visible layers associated with each display. The layer
2237 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2238 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2239 for (const auto& [token, display] : mDisplays) {
2240 getBE().mCompositionInfo[token].clear();
2241 }
2242
Mathias Agopiancd60f992012-08-16 16:28:27 -07002243 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002244 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002245 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002246 mVisibleRegionsDirty = false;
2247 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002248
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002249 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002250 const auto& displayDevice = pair.second;
2251 auto display = displayDevice->getCompositionDisplay();
2252 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002253 Region opaqueRegion;
2254 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002255 compositionengine::Output::OutputLayers layersSortedByZ;
2256 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002257 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002258 const ui::Transform& tr = displayState.transform;
2259 const Rect bounds = displayState.bounds;
2260 if (displayState.isEnabled) {
2261 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002262
Jeff Sharkey76488112017-02-27 14:15:18 -07002263 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002264 auto compositionLayer = layer->getCompositionLayer();
2265 if (compositionLayer == nullptr) {
2266 return;
2267 }
2268
Chia-I Wu83806892017-11-16 10:50:20 -08002269 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002270 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002271 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2272 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2273
Lloyd Piqueef36b002019-01-23 17:52:04 -08002274 if (display->belongsInOutput(layer->getLayerStack(),
2275 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002276 Region drawRegion(tr.transform(
2277 layer->visibleNonTransparentRegion));
2278 drawRegion.andSelf(bounds);
2279 if (!drawRegion.isEmpty()) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002280 layersSortedByZ.emplace_back(
2281 display->getOrCreateOutputLayer(layer->getCompositionLayer(),
2282 layerFE));
2283
2284 deprecated_layersSortedByZ.add(layer);
Jeff Sharkey76488112017-02-27 14:15:18 -07002285 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002286 // Clear out the HWC layer if this layer was
2287 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002288 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002289 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002290 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002291 // WM changes display->layerStack upon sleep/awake.
2292 // Here we make sure we delete the HWC layers even if
2293 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002294 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002295 }
2296
2297 // If a layer is not going to get a release fence because
2298 // it is invisible, but it is also going to release its
2299 // old buffer, add it to the list of layers needing
2300 // fences.
2301 if (hwcLayerDestroyed) {
2302 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2303 mLayersWithQueuedFrames.cend(), layer);
2304 if (found != mLayersWithQueuedFrames.cend()) {
2305 layersNeedingFences.add(layer);
2306 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002307 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002308 });
2309 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002310
2311 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2312
2313 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002314 displayDevice->setLayersNeedingFences(layersNeedingFences);
2315
2316 Region undefinedRegion{bounds};
2317 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2318
2319 display->editState().undefinedRegion = undefinedRegion;
2320 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002321 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002322 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002323}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002324
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002325// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002326// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002327// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002328// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002329// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002330// The returned HDR data space is one of
2331// - Dataspace::UNKNOWN
2332// - Dataspace::BT2020_HLG
2333// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002334Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2335 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002336 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002337 *outHdrDataSpace = Dataspace::UNKNOWN;
2338
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002339 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002340 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002341 case Dataspace::V0_SCRGB:
2342 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002343 case Dataspace::BT2020:
2344 case Dataspace::BT2020_ITU:
2345 case Dataspace::BT2020_LINEAR:
2346 case Dataspace::DISPLAY_BT2020:
2347 bestDataSpace = Dataspace::DISPLAY_BT2020;
2348 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002349 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002350 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002351 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002352 case Dataspace::BT2020_PQ:
2353 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002354 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002355 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002356 case Dataspace::BT2020_HLG:
2357 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002358 // When there's mixed PQ content and HLG content, we set the HDR
2359 // data space to be BT2020_PQ and convert HLG to PQ.
2360 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2361 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002362 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002363 break;
2364 default:
2365 break;
2366 }
Romain Guy54f154a2017-10-24 21:40:32 +01002367 }
2368
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002369 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002370}
2371
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002372// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002373void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2374 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002375 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2376 *outMode = ColorMode::NATIVE;
2377 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002378 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002379 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002380 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002381
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002382 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002383 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002384
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002385 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2386
Peiyong Lindfde5112018-06-05 10:58:41 -07002387 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002388 const bool isHdr =
2389 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002390 if (isHdr) {
2391 bestDataSpace = hdrDataSpace;
2392 }
2393
Chia-I Wu0d711262018-05-21 15:19:35 -07002394 RenderIntent intent;
2395 switch (mDisplayColorSetting) {
2396 case DisplayColorSetting::MANAGED:
2397 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002398 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002399 break;
2400 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002401 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002402 break;
2403 default: // vendor display color setting
2404 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2405 break;
2406 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002407
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002408 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002409}
2410
Lloyd Pique32cbe282018-10-19 13:09:22 -07002411void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2412 auto display = displayDevice->getCompositionDisplay();
2413 const auto& displayState = display->getState();
2414
Alec Mouri0f714832018-11-12 15:31:06 -08002415 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002416 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2417 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002418
David Sodmanfa9b2af2017-12-24 13:28:59 -08002419 // If nothing has changed (!dirty), don't recompose.
2420 // If something changed, but we don't currently have any visible layers,
2421 // and didn't when we last did a composition, then skip it this time.
2422 // The second rule does two things:
2423 // - When all layers are removed from a display, we'll emit one black
2424 // frame, then nothing more until we get new layers.
2425 // - When a display is created with a private layer stack, we won't
2426 // emit any black frames until a layer is added to the layer stack.
2427 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002428
Dominik Laskowski075d3172018-05-24 15:50:06 -07002429 const char flagPrefix[] = {'-', '+'};
2430 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002431 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2432 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2433 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2434 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002435
Lloyd Pique31cb2942018-10-19 17:23:03 -07002436 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002437
David Sodmanfa9b2af2017-12-24 13:28:59 -08002438 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002439 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002440 }
2441}
2442
Lloyd Pique32cbe282018-10-19 13:09:22 -07002443void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2444 auto display = displayDevice->getCompositionDisplay();
2445 const auto& displayState = display->getState();
2446
2447 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002448 return;
David Sodman2b406362017-12-15 13:33:47 -08002449 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002450
Lloyd Pique31cb2942018-10-19 17:23:03 -07002451 status_t result = display->getRenderSurface()->prepareFrame(
2452 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002453 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002454 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002455}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002456
Lloyd Pique32cbe282018-10-19 13:09:22 -07002457void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002458 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002459 ALOGV("doComposition");
2460
Lloyd Pique32cbe282018-10-19 13:09:22 -07002461 auto display = displayDevice->getCompositionDisplay();
2462 const auto& displayState = display->getState();
2463
2464 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002465 // transform the dirty region into this screen's coordinate space
Alec Mouri0f714832018-11-12 15:31:06 -08002466 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002467
David Sodmanfa9b2af2017-12-24 13:28:59 -08002468 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002469 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002470
Lloyd Pique32cbe282018-10-19 13:09:22 -07002471 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002472 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002473 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002474 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002475}
2476
David Sodmanfa9b2af2017-12-24 13:28:59 -08002477void SurfaceFlinger::postFrame()
2478{
2479 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002480 const auto display = getDefaultDisplayDeviceLocked();
2481 if (display && getHwComposer().isConnected(*display->getId())) {
2482 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002483 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2484 logFrameStats();
2485 }
2486 }
2487}
2488
Lloyd Pique32cbe282018-10-19 13:09:22 -07002489void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002490 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002491 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002492
Lloyd Pique32cbe282018-10-19 13:09:22 -07002493 auto display = displayDevice->getCompositionDisplay();
2494 const auto& displayState = display->getState();
2495 const auto displayId = display->getId();
2496
David Sodmanfa9b2af2017-12-24 13:28:59 -08002497 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002498
Lloyd Pique32cbe282018-10-19 13:09:22 -07002499 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002500 if (displayId) {
2501 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002502 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002503 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002504 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002505 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002506
Chia-I Wu7b549592017-11-15 09:14:57 -08002507 // The layer buffer from the previous frame (if any) is released
2508 // by HWC only when the release fence from this frame (if any) is
2509 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002510 if (displayId && layer->hasHwcLayer(*displayId)) {
2511 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2512 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002513 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002514
2515 // If the layer was client composited in the previous frame, we
2516 // need to merge with the previous client target acquire fence.
2517 // Since we do not track that, always merge with the current
2518 // client target acquire fence when it is available, even though
2519 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002520 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002521 releaseFence =
2522 Fence::merge("LayerRelease", releaseFence,
2523 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002524 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002525
David Sodman15094112018-10-11 09:39:37 -07002526 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002527 }
Chia-I Wu83806892017-11-16 10:50:20 -08002528
2529 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002530 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002531 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002532 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002533 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002534 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002535 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002536 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002537 }
2538 }
2539
Dominik Laskowski075d3172018-05-24 15:50:06 -07002540 if (displayId) {
2541 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002542 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002543 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002544}
2545
Mathias Agopian87baae12012-07-31 12:38:26 -07002546void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002547{
Mathias Agopian841cde52012-03-01 15:44:37 -08002548 ATRACE_CALL();
2549
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002550 // here we keep a copy of the drawing state (that is the state that's
2551 // going to be overwritten by handleTransactionLocked()) outside of
2552 // mStateLock so that the side-effects of the State assignment
2553 // don't happen with mStateLock held (which can cause deadlocks).
2554 State drawingState(mDrawingState);
2555
Mathias Agopianca4d3602011-05-19 15:38:14 -07002556 Mutex::Autolock _l(mStateLock);
2557 const nsecs_t now = systemTime();
2558 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002559
Mathias Agopianca4d3602011-05-19 15:38:14 -07002560 // Here we're guaranteed that some transaction flags are set
2561 // so we can call handleTransactionLocked() unconditionally.
2562 // We call getTransactionFlags(), which will also clear the flags,
2563 // with mStateLock held to guarantee that mCurrentState won't change
2564 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002565
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002566 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002567 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002568 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002569
Mathias Agopianca4d3602011-05-19 15:38:14 -07002570 mLastTransactionTime = systemTime() - now;
2571 mDebugInTransaction = 0;
2572 invalidateHwcGeometry();
2573 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002574}
2575
Lloyd Piqueba04e622017-12-14 17:11:26 -08002576void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2577 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002578 const std::optional<DisplayIdentificationInfo> info =
2579 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002580
Dominik Laskowski075d3172018-05-24 15:50:06 -07002581 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002582 continue;
2583 }
2584
Lloyd Piqueba04e622017-12-14 17:11:26 -08002585 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002586 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002587 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002588 mPhysicalDisplayTokens[info->id] = new BBinder();
2589 DisplayDeviceState state;
2590 state.displayId = info->id;
2591 state.isSecure = true; // All physical displays are currently considered secure.
2592 state.displayName = info->name;
2593 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2594 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002595 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002596 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002597 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002598
Dominik Laskowski075d3172018-05-24 15:50:06 -07002599 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2600 if (index >= 0) {
2601 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2602 mInterceptor->saveDisplayDeletion(state.sequenceId);
2603 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002604 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002605 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002606 }
2607
2608 processDisplayChangesLocked();
2609 }
2610
2611 mPendingHotplugEvents.clear();
2612}
2613
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002614void SurfaceFlinger::dispatchDisplayHotplugEvent(EventThread::DisplayType displayType,
2615 bool connected) {
2616 if (mUseScheduler) {
2617 mScheduler->hotplugReceived(mAppConnectionHandle, displayType, connected);
2618 mScheduler->hotplugReceived(mSfConnectionHandle, displayType, connected);
2619 } else {
2620 mEventThread->onHotplugReceived(displayType, connected);
2621 mSFEventThread->onHotplugReceived(displayType, connected);
2622 }
2623}
2624
Lloyd Pique99d3da52018-01-22 17:48:03 -08002625sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002626 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002627 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002628 const sp<IGraphicBufferProducer>& producer) {
2629 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002630 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002631 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002632 creationArgs.isSecure = state.isSecure;
2633 creationArgs.displaySurface = dispSurface;
2634 creationArgs.hasWideColorGamut = false;
2635 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002636
Dominik Laskowski075d3172018-05-24 15:50:06 -07002637 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2638 creationArgs.isPrimary = isInternalDisplay;
2639
2640 if (useColorManagement && displayId) {
2641 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002642 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002643 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002644 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002645 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002646
Dominik Laskowski7e045462018-05-30 13:02:02 -07002647 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002648 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002649 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002650 }
tangrobin6753a022018-08-10 10:58:54 +08002651 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002652
Dominik Laskowski075d3172018-05-24 15:50:06 -07002653 if (displayId) {
2654 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002655 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002656 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002657 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002658
Lloyd Pique90c115d2018-09-18 21:39:42 -07002659 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002660 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002661 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002662
Lloyd Pique99d3da52018-01-22 17:48:03 -08002663 // Make sure that composition can never be stalled by a virtual display
2664 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002665 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002666 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002667 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2668 }
2669
Dominik Laskowski075d3172018-05-24 15:50:06 -07002670 creationArgs.displayInstallOrientation =
2671 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002672
Lloyd Pique99d3da52018-01-22 17:48:03 -08002673 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002674 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002675
Lloyd Pique90c115d2018-09-18 21:39:42 -07002676 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002677
2678 if (maxFrameBufferAcquiredBuffers >= 3) {
2679 nativeWindowSurface->preallocateBuffers();
2680 }
2681
2682 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002683 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002684 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002685 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002686 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002687 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002688 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2689 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002690 if (!state.isVirtual()) {
2691 LOG_ALWAYS_FATAL_IF(!displayId);
2692 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002693 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002694
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002695 display->setLayerStack(state.layerStack);
2696 display->setProjection(state.orientation, state.viewport, state.frame);
2697 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002698
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002699 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002700}
2701
Lloyd Pique347200f2017-12-14 17:00:15 -08002702void SurfaceFlinger::processDisplayChangesLocked() {
2703 // here we take advantage of Vector's copy-on-write semantics to
2704 // improve performance by skipping the transaction entirely when
2705 // know that the lists are identical
2706 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2707 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2708 if (!curr.isIdenticalTo(draw)) {
2709 mVisibleRegionsDirty = true;
2710 const size_t cc = curr.size();
2711 size_t dc = draw.size();
2712
2713 // find the displays that were removed
2714 // (ie: in drawing state but not in current state)
2715 // also handle displays that changed
2716 // (ie: displays that are in both lists)
2717 for (size_t i = 0; i < dc;) {
2718 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2719 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002720 // Save display IDs before disconnecting.
2721 const auto internalDisplayId = getInternalDisplayId();
2722 const auto externalDisplayId = getExternalDisplayId();
2723
Lloyd Pique347200f2017-12-14 17:00:15 -08002724 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002725 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002726 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002727 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002728 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002729 dispatchDisplayHotplugEvent(EventThread::DisplayType::Primary, false);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002730 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002731 dispatchDisplayHotplugEvent(EventThread::DisplayType::External, false);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002732 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002733 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002734 } else {
2735 // this display is in both lists. see if something changed.
2736 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002737 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002738 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2739 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2740 if (state_binder != draw_binder) {
2741 // changing the surface is like destroying and
2742 // recreating the DisplayDevice, so we just remove it
2743 // from the drawing state, so that it get re-added
2744 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002745 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002746 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002747 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002748 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002749 mDrawingState.displays.removeItemsAt(i);
2750 dc--;
2751 // at this point we must loop to the next item
2752 continue;
2753 }
2754
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002755 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002756 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002757 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002758 }
2759 if ((state.orientation != draw[i].orientation) ||
2760 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002761 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002762 }
2763 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002764 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002765 }
2766 }
2767 }
2768 ++i;
2769 }
2770
2771 // find displays that were added
2772 // (ie: in current state but not in drawing state)
2773 for (size_t i = 0; i < cc; i++) {
2774 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2775 const DisplayDeviceState& state(curr[i]);
2776
Lloyd Pique542307f2018-10-19 13:24:08 -07002777 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002778 sp<IGraphicBufferProducer> producer;
2779 sp<IGraphicBufferProducer> bqProducer;
2780 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002781 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002782
Dominik Laskowski075d3172018-05-24 15:50:06 -07002783 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002784 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002785 // Virtual displays without a surface are dormant:
2786 // they have external state (layer stack, projection,
2787 // etc.) but no internal state (i.e. a DisplayDevice).
2788 if (state.surface != nullptr) {
2789 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002790 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002791 int width = 0;
2792 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2793 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2794 int height = 0;
2795 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2796 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2797 int intFormat = 0;
2798 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2799 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002800 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002801
Dominik Laskowski075d3172018-05-24 15:50:06 -07002802 displayId =
2803 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002804 }
2805
2806 // TODO: Plumb requested format back up to consumer
2807
2808 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002809 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002810 bqProducer, bqConsumer,
2811 state.displayName);
2812
2813 dispSurface = vds;
2814 producer = vds;
2815 }
2816 } else {
2817 ALOGE_IF(state.surface != nullptr,
2818 "adding a supported display, but rendering "
2819 "surface is provided (%p), ignoring it",
2820 state.surface.get());
2821
Dominik Laskowski075d3172018-05-24 15:50:06 -07002822 displayId = state.displayId;
2823 LOG_ALWAYS_FATAL_IF(!displayId);
2824 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002825 producer = bqProducer;
2826 }
2827
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002828 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002829 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002830 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002831 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002832 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002833 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002834 LOG_ALWAYS_FATAL_IF(!displayId);
2835
2836 if (displayId == getInternalDisplayId()) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002837 dispatchDisplayHotplugEvent(EventThread::DisplayType::Primary, true);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002838 } else if (displayId == getExternalDisplayId()) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002839 dispatchDisplayHotplugEvent(EventThread::DisplayType::External, true);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002840 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002841 }
2842 }
2843 }
2844 }
2845 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002846
2847 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002848}
2849
Mathias Agopian87baae12012-07-31 12:38:26 -07002850void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002851{
Dan Stoza7dde5992015-05-22 09:51:44 -07002852 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002853 mCurrentState.traverseInZOrder([](Layer* layer) {
2854 layer->notifyAvailableFrames();
2855 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002856
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002857 /*
2858 * Traversal of the children
2859 * (perform the transaction for each of them if needed)
2860 */
2861
Robert Carr720e5062018-07-30 17:45:14 -07002862 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002863 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002864 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002865 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002866 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002867
2868 const uint32_t flags = layer->doTransaction(0);
2869 if (flags & Layer::eVisibleRegion)
2870 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002871
2872 if (flags & Layer::eInputInfoChanged) {
2873 inputChanged = true;
2874 }
Robert Carr2047fae2016-11-28 14:09:09 -08002875 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002876 }
2877
2878 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002879 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002880 */
2881
Mathias Agopiane57f2922012-08-09 16:29:12 -07002882 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002883 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002884 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002885 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002886
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002887 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002888 // The transform hint might have changed for some layers
2889 // (either because a display has changed, or because a layer
2890 // as changed).
2891 //
2892 // Walk through all the layers in currentLayers,
2893 // and update their transform hint.
2894 //
2895 // If a layer is visible only on a single display, then that
2896 // display is used to calculate the hint, otherwise we use the
2897 // default display.
2898 //
2899 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2900 // the hint is set before we acquire a buffer from the surface texture.
2901 //
2902 // NOTE: layer transactions have taken place already, so we use their
2903 // drawing state. However, SurfaceFlinger's own transaction has not
2904 // happened yet, so we must use the current state layer list
2905 // (soon to become the drawing state list).
2906 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002907 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002908 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002909 bool first = true;
2910 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002911 // NOTE: we rely on the fact that layers are sorted by
2912 // layerStack first (so we don't have to traverse the list
2913 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002914 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002915 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002916 currentlayerStack = layerStack;
2917 // figure out if this layerstack is mirrored
2918 // (more than one display) if so, pick the default display,
2919 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002920 hintDisplay = nullptr;
2921 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002922 if (display->getCompositionDisplay()
2923 ->belongsInOutput(layer->getLayerStack(),
2924 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002925 if (hintDisplay) {
2926 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002927 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002928 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002929 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002930 }
2931 }
2932 }
2933 }
Chet Haase91d25932013-04-11 15:24:55 -07002934
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002935 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002936 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2937 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002938
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002939 // could be null when this layer is using a layerStack
2940 // that is not visible on any display. Also can occur at
2941 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002942 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002943 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002944
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002945 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002946 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002947 if (hintDisplay) {
2948 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002949 }
Robert Carr2047fae2016-11-28 14:09:09 -08002950
2951 first = false;
2952 });
Mathias Agopian84300952012-11-21 16:02:13 -08002953 }
2954
2955
Mathias Agopian3559b072012-08-15 13:46:03 -07002956 /*
2957 * Perform our own transaction if needed
2958 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002959
2960 if (mLayersAdded) {
2961 mLayersAdded = false;
2962 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002963 mVisibleRegionsDirty = true;
2964 }
2965
2966 // some layers might have been removed, so
2967 // we need to update the regions they're exposing.
2968 if (mLayersRemoved) {
2969 mLayersRemoved = false;
2970 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002971 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002972 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002973 // this layer is not visible anymore
2974 // TODO: we could traverse the tree from front to back and
2975 // compute the actual visible region
2976 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002977 Region visibleReg;
2978 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002979 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002980 }
Robert Carr2047fae2016-11-28 14:09:09 -08002981 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002982 }
2983
2984 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002985
Vishnu Nairde19f852018-12-18 16:11:53 -08002986 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002987 updateInputWindows();
2988 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002989 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002990
Riley Andrews03414a12014-07-01 14:22:59 -07002991 updateCursorAsync();
2992}
2993
Robert Carr720e5062018-07-30 17:45:14 -07002994void SurfaceFlinger::updateInputWindows() {
2995 ATRACE_CALL();
2996
Vishnu Nairde19f852018-12-18 16:11:53 -08002997 if (mInputFlinger == nullptr) {
2998 return;
2999 }
3000
Robert Carr720e5062018-07-30 17:45:14 -07003001 Vector<InputWindowInfo> inputHandles;
3002
3003 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
3004 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08003005 // When calculating the screen bounds we ignore the transparent region since it may
3006 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08003007 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07003008 }
3009 });
3010 mInputFlinger->setInputWindows(inputHandles);
3011}
3012
chaviwfbe5d9c2018-12-26 12:23:37 -08003013void SurfaceFlinger::executeInputWindowCommands() {
3014 if (!mInputFlinger) {
3015 return;
3016 }
3017
3018 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3019 if (transferTouchFocusCommand.fromToken != nullptr &&
3020 transferTouchFocusCommand.toToken != nullptr &&
3021 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3022 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3023 transferTouchFocusCommand.toToken);
3024 }
3025 }
3026
3027 mInputWindowCommands.clear();
3028}
3029
Riley Andrews03414a12014-07-01 14:22:59 -07003030void SurfaceFlinger::updateCursorAsync()
3031{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003032 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003033 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003034 continue;
3035 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003036
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003037 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3038 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003039 }
3040 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003041}
3042
chaviw61626f22018-11-15 16:26:27 -08003043void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3044 if (layer->hasReadyFrame()) {
3045 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3046 if (layer->shouldPresentNow(expectedPresentTime)) {
3047 bool ignored = false;
3048 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3049 }
3050 }
3051 layer->releasePendingBuffer(systemTime());
3052}
3053
Mathias Agopian4fec8732012-06-29 14:12:52 -07003054void SurfaceFlinger::commitTransaction()
3055{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003056 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003057 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003058 for (const auto& l : mLayersPendingRemoval) {
3059 recordBufferingStats(l->getName().string(),
3060 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003061
3062 // We need to release the HWC layers when the Layer is removed
3063 // from the current state otherwise the HWC layer just continues
3064 // showing at its last configured state until we eventually
3065 // abandon the buffer queue.
3066 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003067 l->destroyHwcLayersForAllDisplays();
3068 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003069 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003070 }
3071 mLayersPendingRemoval.clear();
3072 }
3073
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003074 // If this transaction is part of a window animation then the next frame
3075 // we composite should be considered an animation as well.
3076 mAnimCompositionPending = mAnimTransactionPending;
3077
Mathias Agopian4fec8732012-06-29 14:12:52 -07003078 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003079 // clear the "changed" flags in current state
3080 mCurrentState.colorMatrixChanged = false;
3081
Robert Carr1f0a16a2016-10-24 16:27:39 -07003082 mDrawingState.traverseInZOrder([](Layer* layer) {
3083 layer->commitChildList();
3084 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003085 mTransactionPending = false;
3086 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003087 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003088}
3089
Lloyd Pique32cbe282018-10-19 13:09:22 -07003090void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003091 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003092 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003093 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003094
Lloyd Pique32cbe282018-10-19 13:09:22 -07003095 auto display = displayDevice->getCompositionDisplay();
3096
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003097 Region aboveOpaqueLayers;
3098 Region aboveCoveredLayers;
3099 Region dirty;
3100
Mathias Agopian87baae12012-07-31 12:38:26 -07003101 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003102
Robert Carr2047fae2016-11-28 14:09:09 -08003103 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003104 // start with the whole surface at its current location
3105 const Layer::State& s(layer->getDrawingState());
3106
Jesse Hall01e29052013-02-19 16:13:35 -08003107 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003108 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003109 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003110 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003111
Mathias Agopianab028732010-03-16 16:41:46 -07003112 /*
3113 * opaqueRegion: area of a surface that is fully opaque.
3114 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003115 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003116
3117 /*
3118 * visibleRegion: area of a surface that is visible on screen
3119 * and not fully transparent. This is essentially the layer's
3120 * footprint minus the opaque regions above it.
3121 * Areas covered by a translucent surface are considered visible.
3122 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003123 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003124
3125 /*
3126 * coveredRegion: area of a surface that is covered by all
3127 * visible regions above it (which includes the translucent areas).
3128 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003129 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003130
Jesse Halla8026d22012-09-25 13:25:04 -07003131 /*
3132 * transparentRegion: area of a surface that is hinted to be completely
3133 * transparent. This is only used to tell when the layer has no visible
3134 * non-transparent regions and can be removed from the layer list. It
3135 * does not affect the visibleRegion of this layer or any layers
3136 * beneath it. The hint may not be correct if apps don't respect the
3137 * SurfaceView restrictions (which, sadly, some don't).
3138 */
3139 Region transparentRegion;
3140
Mathias Agopianab028732010-03-16 16:41:46 -07003141
3142 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003143 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003144 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003145 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003146
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003147 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003148 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003149 if (!visibleRegion.isEmpty()) {
3150 // Remove the transparent area from the visible region
3151 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003152 if (tr.preserveRects()) {
3153 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003154 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003155 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003156 // transformation too complex, can't do the
3157 // transparent region optimization.
3158 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003159 }
Mathias Agopianab028732010-03-16 16:41:46 -07003160 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003161
Mathias Agopianab028732010-03-16 16:41:46 -07003162 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003163 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003164 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003165 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003166 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003167 // the opaque region is the layer's footprint
3168 opaqueRegion = visibleRegion;
3169 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003170 }
3171 }
3172
Robert Carre5f4f692018-01-12 13:12:28 -08003173 if (visibleRegion.isEmpty()) {
3174 layer->clearVisibilityRegions();
3175 return;
3176 }
3177
Mathias Agopianab028732010-03-16 16:41:46 -07003178 // Clip the covered region to the visible region
3179 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3180
3181 // Update aboveCoveredLayers for next (lower) layer
3182 aboveCoveredLayers.orSelf(visibleRegion);
3183
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003184 // subtract the opaque region covered by the layers above us
3185 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003186
3187 // compute this layer's dirty region
3188 if (layer->contentDirty) {
3189 // we need to invalidate the whole region
3190 dirty = visibleRegion;
3191 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003192 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003193 layer->contentDirty = false;
3194 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003195 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003196 * the exposed region consists of two components:
3197 * 1) what's VISIBLE now and was COVERED before
3198 * 2) what's EXPOSED now less what was EXPOSED before
3199 *
3200 * note that (1) is conservative, we start with the whole
3201 * visible region but only keep what used to be covered by
3202 * something -- which mean it may have been exposed.
3203 *
3204 * (2) handles areas that were not covered by anything but got
3205 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003206 */
Mathias Agopianab028732010-03-16 16:41:46 -07003207 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003208 const Region oldVisibleRegion = layer->visibleRegion;
3209 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003210 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3211 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003212 }
3213 dirty.subtractSelf(aboveOpaqueLayers);
3214
3215 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003216 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003217
Mathias Agopianab028732010-03-16 16:41:46 -07003218 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003219 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003220
Jesse Halla8026d22012-09-25 13:25:04 -07003221 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003222 layer->setVisibleRegion(visibleRegion);
3223 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003224 layer->setVisibleNonTransparentRegion(
3225 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003226 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003227
Mathias Agopian87baae12012-07-31 12:38:26 -07003228 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003229}
3230
Chia-I Wuab0c3192017-08-01 11:29:00 -07003231void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003232 for (const auto& [token, displayDevice] : mDisplays) {
3233 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003234 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003235 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003236 }
3237 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003238}
3239
Daniel Solomon42d04562019-01-20 21:03:19 -08003240void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3241 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3242 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3243 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3244 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3245 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3246 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3247 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3248 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3249 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3250 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3251 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3252 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3253}
3254
Dan Stoza6b9454d2014-11-07 16:00:59 -08003255bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003256{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003257 ALOGV("handlePageFlip");
3258
Brian Andersond6927fb2016-07-23 23:37:30 -07003259 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003260
Mathias Agopian4fec8732012-06-29 14:12:52 -07003261 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003262 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003263 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003264
3265 // Store the set of layers that need updates. This set must not change as
3266 // buffers are being latched, as this could result in a deadlock.
3267 // Example: Two producers share the same command stream and:
3268 // 1.) Layer 0 is latched
3269 // 2.) Layer 0 gets a new frame
3270 // 2.) Layer 1 gets a new frame
3271 // 3.) Layer 1 is latched.
3272 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3273 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003274 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003275 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003276 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003277 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3278 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003279 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003280 } else {
3281 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003282 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003283 } else {
3284 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003285 }
Robert Carr2047fae2016-11-28 14:09:09 -08003286 });
3287
Lloyd Piquef2c79392018-12-20 16:23:33 -08003288 if (!mLayersWithQueuedFrames.empty()) {
3289 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3290 // writes to Layer current state. See also b/119481871
3291 Mutex::Autolock lock(mStateLock);
3292
3293 for (auto& layer : mLayersWithQueuedFrames) {
3294 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3295 layer->useSurfaceDamage();
3296 invalidateLayerStack(layer, dirty);
3297 if (layer->isBufferLatched()) {
3298 newDataLatched = true;
3299 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003300 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003301 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003302
Alec Mouri86770e52018-09-24 22:40:58 +00003303 // Clear the renderengine fence here...
3304 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3305 // clear instead of sp::clear.
3306 getBE().flushFence = Fence::NO_FENCE;
3307
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003308 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003309
Vishnu Nairde19f852018-12-18 16:11:53 -08003310 if (visibleRegions) {
3311 // Update input window info if the layer receives its first buffer.
3312 updateInputWindows();
3313 }
3314
Dan Stoza6b9454d2014-11-07 16:00:59 -08003315 // If we will need to wake up at some time in the future to deal with a
3316 // queued frame that shouldn't be displayed during this vsync period, wake
3317 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003318 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003319 signalLayerUpdate();
3320 }
3321
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003322 // enter boot animation on first buffer latch
3323 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3324 ALOGI("Enter boot animation");
3325 mBootStage = BootStage::BOOTANIMATION;
3326 }
3327
Dan Stoza6b9454d2014-11-07 16:00:59 -08003328 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003329 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003330}
3331
Mathias Agopianad456f92011-01-13 17:53:01 -08003332void SurfaceFlinger::invalidateHwcGeometry()
3333{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003334 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003335}
3336
Lloyd Pique32cbe282018-10-19 13:09:22 -07003337void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003338 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003339 auto display = displayDevice->getCompositionDisplay();
3340
Dan Stoza71433162014-02-04 16:22:36 -08003341 // We only need to actually compose the display if:
3342 // 1) It is being handled by hardware composer, which may need this to
3343 // keep its virtual display state machine in sync, or
3344 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003345 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003346 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003347 return;
3348 }
3349
Dan Stoza9e56aa02015-11-02 13:00:03 -08003350 ALOGV("doDisplayComposition");
Alec Mouri0f714832018-11-12 15:31:06 -08003351 base::unique_fd readyFence;
3352 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003353
3354 // swap buffers (presentation)
Alec Mouri0f714832018-11-12 15:31:06 -08003355 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003356}
3357
Alec Mouri0f714832018-11-12 15:31:06 -08003358bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3359 const Region& debugRegion, base::unique_fd* readyFence) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003360 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003361
Lloyd Pique32cbe282018-10-19 13:09:22 -07003362 auto display = displayDevice->getCompositionDisplay();
3363 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003364 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003365
3366 const Region bounds(displayState.bounds);
3367 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003368 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003369 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003370
Peiyong Lind3788632018-09-18 16:01:31 -07003371 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003372 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003373
Alec Mouri0f714832018-11-12 15:31:06 -08003374 renderengine::DisplaySettings clientCompositionDisplay;
3375 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3376 sp<GraphicBuffer> buf;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003377
Dan Stoza9e56aa02015-11-02 13:00:03 -08003378 if (hasClientComposition) {
3379 ALOGV("hasClientComposition");
3380
Alec Mouri0f714832018-11-12 15:31:06 -08003381 buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003382
3383 if (buf == nullptr) {
3384 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3385 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003386 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003387 return false;
3388 }
3389
Alec Mouri0f714832018-11-12 15:31:06 -08003390 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3391 clientCompositionDisplay.clip = displayState.scissor;
3392 const ui::Transform& displayTransform = displayState.transform;
3393 mat4 m;
3394 m[0][0] = displayTransform[0][0];
3395 m[0][1] = displayTransform[0][1];
3396 m[0][3] = displayTransform[0][2];
3397 m[1][0] = displayTransform[1][0];
3398 m[1][1] = displayTransform[1][1];
3399 m[1][3] = displayTransform[1][2];
3400 m[3][0] = displayTransform[2][0];
3401 m[3][1] = displayTransform[2][1];
3402 m[3][3] = displayTransform[2][2];
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003403
Alec Mouri0f714832018-11-12 15:31:06 -08003404 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003405
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003406 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003407 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003408 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003409 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003410 }
Alec Mouri0f714832018-11-12 15:31:06 -08003411 clientCompositionDisplay.outputDataspace = outputDataspace;
3412 clientCompositionDisplay.maxLuminance =
3413 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003414
Lloyd Pique441d5042018-10-18 16:49:51 -07003415 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003416 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003417 getHwComposer()
3418 .hasDisplayCapability(displayId,
3419 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003420
Peiyong Lind3788632018-09-18 16:01:31 -07003421 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003422 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3423 if (applyColorMatrix) {
Alec Mouri0f714832018-11-12 15:31:06 -08003424 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003425 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003426 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003427
Mathias Agopian85d751c2012-08-29 16:59:24 -07003428 /*
3429 * and then, render the layers targeted at the framebuffer
3430 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003431
Dan Stoza9e56aa02015-11-02 13:00:03 -08003432 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003433 bool firstLayer = true;
Alec Mouri0f714832018-11-12 15:31:06 -08003434 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003435 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mouri0f714832018-11-12 15:31:06 -08003436 const Region viewportRegion(displayState.viewport);
3437 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003438 ALOGV("Layer: %s", layer->getName().string());
3439 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003440 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003441 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003442 case HWC2::Composition::Cursor:
3443 case HWC2::Composition::Device:
3444 case HWC2::Composition::Sideband:
3445 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003446 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003447 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003448 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003449 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003450 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003451 // never clear the very first layer since we're
3452 // guaranteed the FB is already cleared
Alec Mouri0f714832018-11-12 15:31:06 -08003453 renderengine::LayerSettings layerSettings;
3454 Region dummyRegion;
3455 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3456 layerSettings);
3457
3458 if (prepared) {
3459 layerSettings.source.buffer.buffer = nullptr;
3460 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3461 layerSettings.alpha = half(0.0);
3462 layerSettings.disableBlending = true;
3463 clientCompositionLayers.push_back(layerSettings);
3464 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003465 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003466 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003467 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003468 case HWC2::Composition::Client: {
Alec Mouri0f714832018-11-12 15:31:06 -08003469 renderengine::LayerSettings layerSettings;
3470 bool prepared =
3471 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3472 if (prepared) {
3473 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003474 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003475 break;
3476 }
3477 default:
3478 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003479 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003480 } else {
3481 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003482 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003483 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003484 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003485
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003486 if (hasClientComposition) {
Alec Mouri0f714832018-11-12 15:31:06 -08003487 clientCompositionDisplay.clearRegion = clearRegion;
3488 if (!debugRegion.isEmpty()) {
3489 Region::const_iterator it = debugRegion.begin();
3490 Region::const_iterator end = debugRegion.end();
3491 while (it != end) {
3492 const Rect& rect = *it++;
3493 renderengine::LayerSettings layerSettings;
3494 layerSettings.source.buffer.buffer = nullptr;
3495 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3496 layerSettings.geometry.boundaries = rect.toFloatRect();
3497 layerSettings.alpha = half(1.0);
3498 clientCompositionLayers.push_back(layerSettings);
3499 }
3500 }
3501 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
3502 buf->getNativeBuffer(), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003503 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003504 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003505}
3506
Chia-I Wu28e3a252018-09-07 12:05:02 -07003507void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003508 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003509 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003510}
3511
Dan Stoza7d89d062015-04-30 13:29:25 -07003512status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003513 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003514 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003515 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003516 const sp<Layer>& parent,
3517 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003518{
Dan Stoza7d89d062015-04-30 13:29:25 -07003519 // add this layer to the current state list
3520 {
3521 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003522 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003523 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3524 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003525 return NO_MEMORY;
3526 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003527 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003528 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003529 } else if (parent == nullptr) {
3530 lbc->onRemovedFromCurrentState();
3531 } else if (parent->isRemovedFromCurrentState()) {
3532 parent->addChild(lbc);
3533 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003534 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003535 parent->addChild(lbc);
3536 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003537
Yiwei Zhang243b3782018-05-15 17:40:04 -07003538 if (gbc != nullptr) {
3539 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3540 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3541 mMaxGraphicBufferProducerListSize,
3542 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3543 mGraphicBufferProducerList.size(),
3544 mMaxGraphicBufferProducerListSize, mNumLayers);
3545 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003546 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003547 }
3548
Mathias Agopian96f08192010-06-02 23:28:45 -07003549 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003550 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003551
Dan Stoza7d89d062015-04-30 13:29:25 -07003552 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003553}
3554
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003555uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003556 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003557}
3558
Mathias Agopian3f844832013-08-07 21:24:32 -07003559uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003560 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003561}
3562
Mathias Agopian3f844832013-08-07 21:24:32 -07003563uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003564 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003565}
3566
3567uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003568 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003569 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003570 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003571 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003572 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003573 }
3574 return old;
3575}
3576
Marissa Wall713b63f2018-10-17 15:42:43 -07003577bool SurfaceFlinger::flushTransactionQueues() {
3578 Mutex::Autolock _l(mStateLock);
3579 auto it = mTransactionQueues.begin();
3580 while (it != mTransactionQueues.end()) {
3581 auto& [applyToken, transactionQueue] = *it;
3582
3583 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003584 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3585 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003586 break;
3587 }
chaviw273171b2018-12-26 11:46:30 -08003588 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003589 transactionQueue.pop();
3590 }
3591
3592 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3593 }
3594 return mTransactionQueues.empty();
3595}
3596
chaviwca27f252018-02-06 16:46:39 -08003597bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3598 for (const ComposerState& state : states) {
3599 // Here we need to check that the interface we're given is indeed
3600 // one of our own. A malicious client could give us a nullptr
3601 // IInterface, or one of its own or even one of our own but a
3602 // different type. All these situations would cause us to crash.
3603 if (state.client == nullptr) {
3604 return true;
3605 }
3606
3607 sp<IBinder> binder = IInterface::asBinder(state.client);
3608 if (binder == nullptr) {
3609 return true;
3610 }
3611
3612 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3613 return true;
3614 }
3615 }
3616 return false;
3617}
3618
Marissa Wall17b4e452018-12-26 16:32:34 -08003619bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3620 const Vector<ComposerState>& states) {
3621 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3622 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3623 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3624 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3625 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3626 return false;
3627 }
3628
Marissa Wall713b63f2018-10-17 15:42:43 -07003629 for (const ComposerState& state : states) {
3630 const layer_state_t& s = state.state;
3631 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3632 continue;
3633 }
3634 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003635 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003636 }
3637 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003638 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003639}
3640
3641void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3642 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003643 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003644 const InputWindowCommands& inputWindowCommands,
3645 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003646 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003647 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003648
chaviwca27f252018-02-06 16:46:39 -08003649 if (containsAnyInvalidClientState(states)) {
3650 return;
3651 }
3652
Marissa Wall713b63f2018-10-17 15:42:43 -07003653 // If its TransactionQueue already has a pending TransactionState or if it is pending
3654 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003655 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3656 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003657 setTransactionFlags(eTransactionNeeded);
3658 return;
3659 }
3660
chaviw273171b2018-12-26 11:46:30 -08003661 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003662}
3663
3664void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003665 const Vector<DisplayState>& displays, uint32_t flags,
3666 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003667 uint32_t transactionFlags = 0;
3668
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003669 if (flags & eAnimation) {
3670 // For window updates that are part of an animation we must wait for
3671 // previous animation "frames" to be handled.
3672 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003673 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003674 if (CC_UNLIKELY(err != NO_ERROR)) {
3675 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003676 // caller after a few seconds.
3677 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3678 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003679 mAnimTransactionPending = false;
3680 break;
3681 }
3682 }
3683 }
3684
chaviwca27f252018-02-06 16:46:39 -08003685 for (const DisplayState& display : displays) {
3686 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003687 }
3688
Marissa Walle2ffb422018-10-12 11:33:52 -07003689 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003690 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003691 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003692 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003693 // If the state doesn't require a traversal and there are callbacks, send them now
3694 if (!(clientStateFlags & eTraversalNeeded)) {
3695 mTransactionCompletedThread.sendCallbacks();
3696 }
3697 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003698
chaviw273171b2018-12-26 11:46:30 -08003699 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3700
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003701 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3702 // anyway. This can be used as a flush mechanism for previous async transactions.
3703 // Empty animation transaction can be used to simulate back-pressure, so also force a
3704 // transaction for empty animation transactions.
3705 if (transactionFlags == 0 &&
3706 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003707 transactionFlags = eTransactionNeeded;
3708 }
3709
Mathias Agopian386aa982011-11-07 21:58:03 -08003710 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003711 if (mInterceptor->isEnabled()) {
3712 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003713 }
Irvel468051e2016-06-13 16:44:44 -07003714
Mathias Agopian386aa982011-11-07 21:58:03 -08003715 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003716 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3717 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003718 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003719
3720 // if this is a synchronous transaction, wait for it to take effect
3721 // before returning.
3722 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003723 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003724 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003725 if (flags & eAnimation) {
3726 mAnimTransactionPending = true;
3727 }
3728 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003729 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3730 if (CC_UNLIKELY(err != NO_ERROR)) {
3731 // just in case something goes wrong in SF, return to the
3732 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003733 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3734 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003735 break;
3736 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003737 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003738 }
3739}
3740
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003741uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3742 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3743 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003744
Mathias Agopiane57f2922012-08-09 16:29:12 -07003745 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003746 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3747
3748 const uint32_t what = s.what;
3749 if (what & DisplayState::eSurfaceChanged) {
3750 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3751 state.surface = s.surface;
3752 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003753 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003754 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003755 if (what & DisplayState::eLayerStackChanged) {
3756 if (state.layerStack != s.layerStack) {
3757 state.layerStack = s.layerStack;
3758 flags |= eDisplayTransactionNeeded;
3759 }
3760 }
3761 if (what & DisplayState::eDisplayProjectionChanged) {
3762 if (state.orientation != s.orientation) {
3763 state.orientation = s.orientation;
3764 flags |= eDisplayTransactionNeeded;
3765 }
3766 if (state.frame != s.frame) {
3767 state.frame = s.frame;
3768 flags |= eDisplayTransactionNeeded;
3769 }
3770 if (state.viewport != s.viewport) {
3771 state.viewport = s.viewport;
3772 flags |= eDisplayTransactionNeeded;
3773 }
3774 }
3775 if (what & DisplayState::eDisplaySizeChanged) {
3776 if (state.width != s.width) {
3777 state.width = s.width;
3778 flags |= eDisplayTransactionNeeded;
3779 }
3780 if (state.height != s.height) {
3781 state.height = s.height;
3782 flags |= eDisplayTransactionNeeded;
3783 }
3784 }
3785
Mathias Agopiane57f2922012-08-09 16:29:12 -07003786 return flags;
3787}
3788
Robert Carrd4ae7f32018-06-07 16:10:57 -07003789bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3790 IPCThreadState* ipc = IPCThreadState::self();
3791 const int pid = ipc->getCallingPid();
3792 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003793 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003794 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003795 return false;
3796 }
3797 return true;
3798}
3799
chaviwca27f252018-02-06 16:46:39 -08003800uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3801 const layer_state_t& s = composerState.state;
3802 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3803
Mathias Agopian13127d82013-03-05 17:47:11 -08003804 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003805 if (layer == nullptr) {
3806 return 0;
3807 }
3808
chaviw8b3871a2017-11-01 17:41:01 -07003809 uint32_t flags = 0;
3810
Garfield Tan8a3083e2018-12-03 13:21:07 -08003811 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003812 bool geometryAppliesWithResize =
3813 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003814
3815 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3816 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003817 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003818 layer->pushPendingState();
3819 }
3820
chaviw8b3871a2017-11-01 17:41:01 -07003821 if (what & layer_state_t::ePositionChanged) {
3822 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3823 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003824 }
chaviw8b3871a2017-11-01 17:41:01 -07003825 }
3826 if (what & layer_state_t::eLayerChanged) {
3827 // NOTE: index needs to be calculated before we update the state
3828 const auto& p = layer->getParent();
3829 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003830 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003831 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003832 mCurrentState.layersSortedByZ.removeAt(idx);
3833 mCurrentState.layersSortedByZ.add(layer);
3834 // we need traversal (state changed)
3835 // AND transaction (list changed)
3836 flags |= eTransactionNeeded|eTraversalNeeded;
3837 }
chaviw8b3871a2017-11-01 17:41:01 -07003838 } else {
3839 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003840 flags |= eTransactionNeeded|eTraversalNeeded;
3841 }
3842 }
chaviw8b3871a2017-11-01 17:41:01 -07003843 }
3844 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003845 // NOTE: index needs to be calculated before we update the state
3846 const auto& p = layer->getParent();
3847 if (p == nullptr) {
3848 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3849 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3850 mCurrentState.layersSortedByZ.removeAt(idx);
3851 mCurrentState.layersSortedByZ.add(layer);
3852 // we need traversal (state changed)
3853 // AND transaction (list changed)
3854 flags |= eTransactionNeeded|eTraversalNeeded;
3855 }
3856 } else {
3857 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3858 flags |= eTransactionNeeded|eTraversalNeeded;
3859 }
chaviw8b3871a2017-11-01 17:41:01 -07003860 }
3861 }
3862 if (what & layer_state_t::eSizeChanged) {
3863 if (layer->setSize(s.w, s.h)) {
3864 flags |= eTraversalNeeded;
3865 }
3866 }
3867 if (what & layer_state_t::eAlphaChanged) {
3868 if (layer->setAlpha(s.alpha))
3869 flags |= eTraversalNeeded;
3870 }
3871 if (what & layer_state_t::eColorChanged) {
3872 if (layer->setColor(s.color))
3873 flags |= eTraversalNeeded;
3874 }
Peiyong Lind3788632018-09-18 16:01:31 -07003875 if (what & layer_state_t::eColorTransformChanged) {
3876 if (layer->setColorTransform(s.colorTransform)) {
3877 flags |= eTraversalNeeded;
3878 }
3879 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003880 if (what & layer_state_t::eBackgroundColorChanged) {
3881 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3882 flags |= eTraversalNeeded;
3883 }
3884 }
chaviw8b3871a2017-11-01 17:41:01 -07003885 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003886 // TODO: b/109894387
3887 //
3888 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3889 // rotation. To see the problem observe that if we have a square parent, and a child
3890 // of the same size, then we rotate the child 45 degrees around it's center, the child
3891 // must now be cropped to a non rectangular 8 sided region.
3892 //
3893 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3894 // private API, and the WindowManager only uses rotation in one case, which is on a top
3895 // level layer in which cropping is not an issue.
3896 //
3897 // However given that abuse of rotation matrices could lead to surfaces extending outside
3898 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3899 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3900 // transformations.
3901 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003902 flags |= eTraversalNeeded;
3903 }
3904 if (what & layer_state_t::eTransparentRegionChanged) {
3905 if (layer->setTransparentRegionHint(s.transparentRegion))
3906 flags |= eTraversalNeeded;
3907 }
3908 if (what & layer_state_t::eFlagsChanged) {
3909 if (layer->setFlags(s.flags, s.mask))
3910 flags |= eTraversalNeeded;
3911 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003912 if (what & layer_state_t::eCropChanged_legacy) {
3913 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003914 flags |= eTraversalNeeded;
3915 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003916 if (what & layer_state_t::eCornerRadiusChanged) {
3917 if (layer->setCornerRadius(s.cornerRadius))
3918 flags |= eTraversalNeeded;
3919 }
chaviw8b3871a2017-11-01 17:41:01 -07003920 if (what & layer_state_t::eLayerStackChanged) {
3921 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3922 // We only allow setting layer stacks for top level layers,
3923 // everything else inherits layer stack from its parent.
3924 if (layer->hasParent()) {
3925 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3926 layer->getName().string());
3927 } else if (idx < 0) {
3928 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3929 "that also does not appear in the top level layer list. Something"
3930 " has gone wrong.", layer->getName().string());
3931 } else if (layer->setLayerStack(s.layerStack)) {
3932 mCurrentState.layersSortedByZ.removeAt(idx);
3933 mCurrentState.layersSortedByZ.add(layer);
3934 // we need traversal (state changed)
3935 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003936 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003937 }
3938 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003939 if (what & layer_state_t::eDeferTransaction_legacy) {
3940 if (s.barrierHandle_legacy != nullptr) {
3941 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3942 } else if (s.barrierGbp_legacy != nullptr) {
3943 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003944 if (authenticateSurfaceTextureLocked(gbp)) {
3945 const auto& otherLayer =
3946 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003947 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003948 } else {
3949 ALOGE("Attempt to defer transaction to to an"
3950 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003951 }
3952 }
chaviw8b3871a2017-11-01 17:41:01 -07003953 // We don't trigger a traversal here because if no other state is
3954 // changed, we don't want this to cause any more work
3955 }
3956 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003957 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003958 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003959 if (!hadParent) {
3960 mCurrentState.layersSortedByZ.remove(layer);
3961 }
chaviw8b3871a2017-11-01 17:41:01 -07003962 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003963 }
chaviw8b3871a2017-11-01 17:41:01 -07003964 }
3965 if (what & layer_state_t::eReparentChildren) {
3966 if (layer->reparentChildren(s.reparentHandle)) {
3967 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003968 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003969 }
chaviw8b3871a2017-11-01 17:41:01 -07003970 if (what & layer_state_t::eDetachChildren) {
3971 layer->detachChildren();
3972 }
3973 if (what & layer_state_t::eOverrideScalingModeChanged) {
3974 layer->setOverrideScalingMode(s.overrideScalingMode);
3975 // We don't trigger a traversal here because if no other state is
3976 // changed, we don't want this to cause any more work
3977 }
Marissa Wall61c58622018-07-18 10:12:20 -07003978 if (what & layer_state_t::eTransformChanged) {
3979 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3980 }
3981 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3982 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3983 flags |= eTraversalNeeded;
3984 }
3985 if (what & layer_state_t::eCropChanged) {
3986 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3987 }
Marissa Wall861616d2018-10-22 12:52:23 -07003988 if (what & layer_state_t::eFrameChanged) {
3989 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3990 }
Marissa Wall61c58622018-07-18 10:12:20 -07003991 if (what & layer_state_t::eBufferChanged) {
3992 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3993 }
3994 if (what & layer_state_t::eAcquireFenceChanged) {
3995 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3996 }
3997 if (what & layer_state_t::eDataspaceChanged) {
3998 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3999 }
4000 if (what & layer_state_t::eHdrMetadataChanged) {
4001 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4002 }
4003 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4004 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4005 }
4006 if (what & layer_state_t::eApiChanged) {
4007 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4008 }
4009 if (what & layer_state_t::eSidebandStreamChanged) {
4010 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4011 }
Robert Carr720e5062018-07-30 17:45:14 -07004012 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004013 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
4014 layer->setInputInfo(s.inputInfo);
4015 flags |= eTraversalNeeded;
4016 } else {
4017 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4018 }
Robert Carr720e5062018-07-30 17:45:14 -07004019 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004020 if (what & layer_state_t::eMetadataChanged) {
4021 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4022 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004023 std::vector<sp<CallbackHandle>> callbackHandles;
4024 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
4025 mTransactionCompletedThread.run();
4026 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
4027 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4028 }
4029 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004030 if (what & layer_state_t::eCachedBufferChanged) {
4031 sp<GraphicBuffer> buffer =
4032 mBufferStateLayerCache.get(s.cachedBuffer.token, s.cachedBuffer.bufferId);
4033 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4034 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004035 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4036 // Do not put anything that updates layer state or modifies flags after
4037 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004038 return flags;
4039}
4040
chaviw273171b2018-12-26 11:46:30 -08004041uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4042 uint32_t flags = 0;
4043 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4044 flags |= eTraversalNeeded;
4045 }
4046
4047 mInputWindowCommands.merge(inputWindowCommands);
4048 return flags;
4049}
4050
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004051status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4052 uint32_t h, PixelFormat format, uint32_t flags,
4053 LayerMetadata metadata, sp<IBinder>* handle,
4054 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004055 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004056 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004057 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004058 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004059 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004060
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004061 status_t result = NO_ERROR;
4062
4063 sp<Layer> layer;
4064
Cody Northropbc755282017-03-31 12:00:08 -06004065 String8 uniqueName = getUniqueLayerName(name);
4066
Mathias Agopian3165cc22012-08-08 19:42:09 -07004067 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004068 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004069 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4070 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004071
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004072 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004073 case ISurfaceComposerClient::eFXSurfaceBufferState:
4074 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4075 break;
chaviw13fdc492017-06-27 12:40:18 -07004076 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004077 // check if buffer size is set for color layer.
4078 if (w > 0 || h > 0) {
4079 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4080 int(w), int(h));
4081 return BAD_VALUE;
4082 }
4083
chaviw13fdc492017-06-27 12:40:18 -07004084 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004085 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004086 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004087 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004088 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004089 // check if buffer size is set for container layer.
4090 if (w > 0 || h > 0) {
4091 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4092 int(w), int(h));
4093 return BAD_VALUE;
4094 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004095 result = createContainerLayer(client,
4096 uniqueName, w, h, flags,
4097 handle, &layer);
4098 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004099 default:
4100 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004101 break;
4102 }
4103
Dan Stoza7d89d062015-04-30 13:29:25 -07004104 if (result != NO_ERROR) {
4105 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004106 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004107
Chia-I Wuab0c3192017-08-01 11:29:00 -07004108 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4109 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004110 if (metadata.has(METADATA_WINDOW_TYPE)) {
4111 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4112 if (windowType == 441731) {
4113 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4114 layer->setPrimaryDisplayOnly();
4115 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004116 }
4117
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004118 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004119
Robert Carrb89ea9d2018-12-10 13:01:14 -08004120 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4121 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4122 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004123 if (result != NO_ERROR) {
4124 return result;
4125 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004126 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004127
4128 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004129 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004130}
4131
Cody Northropbc755282017-03-31 12:00:08 -06004132String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4133{
4134 bool matchFound = true;
4135 uint32_t dupeCounter = 0;
4136
4137 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4138 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4139
Dan Stoza436ccf32018-06-21 12:10:12 -07004140 // Grab the state lock since we're accessing mCurrentState
4141 Mutex::Autolock lock(mStateLock);
4142
Cody Northropbc755282017-03-31 12:00:08 -06004143 // Loop over layers until we're sure there is no matching name
4144 while (matchFound) {
4145 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004146 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004147 if (layer->getName() == uniqueName) {
4148 matchFound = true;
4149 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4150 }
4151 });
4152 }
4153
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004154 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4155 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004156
4157 return uniqueName;
4158}
4159
Marissa Wallfd668622018-05-10 10:21:13 -07004160status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4161 uint32_t w, uint32_t h, uint32_t flags,
4162 PixelFormat& format, sp<IBinder>* handle,
4163 sp<IGraphicBufferProducer>* gbp,
4164 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004165 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004166 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004167 case PIXEL_FORMAT_TRANSPARENT:
4168 case PIXEL_FORMAT_TRANSLUCENT:
4169 format = PIXEL_FORMAT_RGBA_8888;
4170 break;
4171 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004172 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004173 break;
4174 }
4175
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004176 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004177 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004178 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004179 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004180 *handle = layer->getHandle();
4181 *gbp = layer->getProducer();
4182 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004183 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004184
Marissa Wallfd668622018-05-10 10:21:13 -07004185 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004186 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004187}
4188
Marissa Wall61c58622018-07-18 10:12:20 -07004189status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4190 uint32_t w, uint32_t h, uint32_t flags,
4191 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004192 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004193 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004194 *handle = layer->getHandle();
4195 *outLayer = layer;
4196
4197 return NO_ERROR;
4198}
4199
chaviw13fdc492017-06-27 12:40:18 -07004200status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004201 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004202 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004203{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004204 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004205 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004206 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004207}
4208
Robert Carr6b3f6c52018-08-13 13:05:17 -07004209status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4210 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4211 sp<IBinder>* handle, sp<Layer>* outLayer)
4212{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004213 *outLayer =
4214 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004215 *handle = (*outLayer)->getHandle();
4216 return NO_ERROR;
4217}
4218
4219
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004220void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004221 mLayersPendingRemoval.add(layer);
4222 mLayersRemoved = true;
4223 setTransactionFlags(eTransactionNeeded);
4224}
4225
Robert Carr695d5282018-12-18 15:27:58 -08004226void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004227{
Robert Carr2e102c92018-10-23 12:11:15 -07004228 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004229 // If a layer has a parent, we allow it to out-live it's handle
4230 // with the idea that the parent holds a reference and will eventually
4231 // be cleaned up. However no one cleans up the top-level so we do so
4232 // here.
4233 if (layer->getParent() == nullptr) {
4234 mCurrentState.layersSortedByZ.remove(layer);
4235 }
4236 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004237 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004238}
4239
Mathias Agopianb60314a2012-04-10 22:09:54 -07004240// ---------------------------------------------------------------------------
4241
Andy McFadden13a082e2012-08-24 10:16:42 -07004242void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004243 const auto display = getDefaultDisplayDeviceLocked();
4244 if (!display) return;
4245
4246 const sp<IBinder> token = display->getDisplayToken().promote();
4247 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004248
Jesse Hall01e29052013-02-19 16:13:35 -08004249 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004250 Vector<ComposerState> state;
4251 Vector<DisplayState> displays;
4252 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004253 d.what = DisplayState::eDisplayProjectionChanged |
4254 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004255 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004256 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004257 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004258 d.frame.makeInvalid();
4259 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004260 d.width = 0;
4261 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004262 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004263 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004264
Dominik Laskowskie9774092018-12-11 10:04:24 -08004265 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004266
Dominik Laskowski83b88212018-12-11 13:34:06 -08004267 const nsecs_t vsyncPeriod = getVsyncPeriod();
4268 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004269
Brian Andersond0010582017-03-07 13:20:31 -08004270 // Use phase of 0 since phase is not known.
4271 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004272 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004273 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004274}
4275
4276void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004277 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004278 postMessageAsync(
4279 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004280}
4281
Dominik Laskowskie9774092018-12-11 10:04:24 -08004282void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004283 if (display->isVirtual()) {
4284 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004285 return;
4286 }
4287
Dominik Laskowski075d3172018-05-24 15:50:06 -07004288 const auto displayId = display->getId();
4289 LOG_ALWAYS_FATAL_IF(!displayId);
4290
Dominik Laskowski34157762018-10-31 13:07:19 -07004291 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004292
4293 int currentMode = display->getPowerMode();
4294 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004295 return;
4296 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004297
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004298 display->setPowerMode(mode);
4299
Lloyd Pique4dccc412018-01-22 17:21:36 -08004300 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004301 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004302 }
4303
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004304 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004305 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004306 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004307 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004308 if (mUseScheduler) {
4309 mScheduler->onScreenAcquired(mAppConnectionHandle);
4310 } else {
4311 mEventThread->onScreenAcquired();
4312 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004313 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004314 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004315
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004316 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004317 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004318 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004319
4320 struct sched_param param = {0};
4321 param.sched_priority = 1;
4322 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4323 ALOGW("Couldn't set SCHED_FIFO on display on");
4324 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004325 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004326 // Turn off the display
4327 struct sched_param param = {0};
4328 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4329 ALOGW("Couldn't set SCHED_OTHER on display off");
4330 }
4331
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004332 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004333 if (mUseScheduler) {
4334 mScheduler->disableHardwareVsync(true);
4335 } else {
4336 disableHardwareVsync(true); // also cancels any in-progress resync
4337 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004338 if (mUseScheduler) {
4339 mScheduler->onScreenReleased(mAppConnectionHandle);
4340 } else {
4341 mEventThread->onScreenReleased();
4342 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004343 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004344
Dominik Laskowski075d3172018-05-24 15:50:06 -07004345 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004346 mVisibleRegionsDirty = true;
4347 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004348 } else if (mode == HWC_POWER_MODE_DOZE ||
4349 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004350 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004351 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004352 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004353 if (mUseScheduler) {
4354 mScheduler->onScreenAcquired(mAppConnectionHandle);
4355 } else {
4356 mEventThread->onScreenAcquired();
4357 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004358 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004359 }
4360 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4361 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004362 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004363 if (mUseScheduler) {
4364 mScheduler->disableHardwareVsync(true);
4365 } else {
4366 disableHardwareVsync(true); // also cancels any in-progress resync
4367 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004368 if (mUseScheduler) {
4369 mScheduler->onScreenReleased(mAppConnectionHandle);
4370 } else {
4371 mEventThread->onScreenReleased();
4372 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004373 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004374 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004375 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004376 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004377 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004378 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004379
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004380 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004381 mTimeStats->setPowerMode(mode);
Ana Krulec4593b692019-01-11 22:07:25 -08004382 if (mUseScheduler && mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004383 // Update refresh rate stats.
4384 mRefreshRateStats->setPowerMode(mode);
4385 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004386 }
4387
Dominik Laskowski34157762018-10-31 13:07:19 -07004388 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004389}
4390
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004391void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004392 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004393 const auto display = getDisplayDevice(displayToken);
4394 if (!display) {
4395 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4396 displayToken.get());
4397 } else if (display->isVirtual()) {
4398 ALOGW("Attempt to set power mode %d for virtual display", mode);
4399 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004400 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004401 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004402 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004403}
4404
4405// ---------------------------------------------------------------------------
4406
Dominik Laskowskic2867142019-01-21 11:33:38 -08004407status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4408 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004409 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004410
Mathias Agopianbd115332013-04-18 16:41:04 -07004411 IPCThreadState* ipc = IPCThreadState::self();
4412 const int pid = ipc->getCallingPid();
4413 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004414
Mathias Agopianbd115332013-04-18 16:41:04 -07004415 if ((uid != AID_SHELL) &&
4416 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004417 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4418 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004419 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004420 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004421 // (this would indicate SF is stuck, but we want to be able to
4422 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004423 status_t err = mStateLock.timedLock(s2ns(1));
4424 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004425 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004426 StringAppendF(&result,
4427 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4428 "(no locks held)\n",
4429 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004430 }
4431
Dominik Laskowskic2867142019-01-21 11:33:38 -08004432 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004433
Dominik Laskowskic2867142019-01-21 11:33:38 -08004434 static const std::unordered_map<std::string, Dumper> dumpers = {
4435 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4436 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4437 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
4438 {"--dispsync"s, dumper([this](std::string& s) { mPrimaryDispSync->dump(s); })},
4439 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4440 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
4441 {"--frame-composition"s, dumper(&SurfaceFlinger::dumpFrameCompositionInfo)},
4442 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4443 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4444 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4445 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4446 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4447 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004448 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004449 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4450 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004451
Dominik Laskowskic2867142019-01-21 11:33:38 -08004452 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004453
Dominik Laskowskic2867142019-01-21 11:33:38 -08004454 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4455 (it->second)(args, asProto, result);
4456 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004457 if (asProto) {
4458 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4459 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4460 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004461 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004462 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004463 }
4464
Mathias Agopian9795c422009-08-26 16:36:26 -07004465 if (locked) {
4466 mStateLock.unlock();
4467 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004468 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004469 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004470 return NO_ERROR;
4471}
4472
Dominik Laskowskic2867142019-01-21 11:33:38 -08004473void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004474 mCurrentState.traverseInZOrder(
4475 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004476}
4477
Dominik Laskowskic2867142019-01-21 11:33:38 -08004478void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004479 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004480
Dominik Laskowskic2867142019-01-21 11:33:38 -08004481 if (args.size() > 1) {
4482 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004483 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004484 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004485 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004486 }
Robert Carr2047fae2016-11-28 14:09:09 -08004487 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004488 } else {
4489 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004490 }
4491}
4492
Dominik Laskowskic2867142019-01-21 11:33:38 -08004493void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004494 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004495 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004496 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004497 }
Robert Carr2047fae2016-11-28 14:09:09 -08004498 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004499
Svetoslavd85084b2014-03-20 10:28:31 -07004500 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004501}
4502
Dominik Laskowskic2867142019-01-21 11:33:38 -08004503void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4504 mTimeStats->parseArgs(asProto, args, result);
4505}
4506
Jamie Gennis6547ff42013-07-16 20:12:42 -07004507// This should only be called from the main thread. Otherwise it would need
4508// the lock and should use mCurrentState rather than mDrawingState.
4509void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004510 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004511 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004512 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004513
4514 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4515}
4516
Yiwei Zhang5434a782018-12-05 18:06:32 -08004517void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004518 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004519
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004520 if (isLayerTripleBufferingDisabled())
4521 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004522
Yiwei Zhang5434a782018-12-05 18:06:32 -08004523 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4524 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4525 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4526 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4527 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4528 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004529 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004530}
4531
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004532void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004533 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004534 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004535 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004536 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004537
4538 StringAppendF(&result, "Scheduler: %s\n\n", mUseScheduler ? "enabled" : "disabled");
4539
4540 if (mUseScheduler) {
4541 mScheduler->dump(mAppConnectionHandle, result);
4542 } else {
4543 mEventThread->dump(result);
4544 }
4545}
4546
Yiwei Zhang5434a782018-12-05 18:06:32 -08004547void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4548 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004549 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4550 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004551 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004552 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004553 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004554 }
David Sodman4a36e932017-11-07 14:29:47 -08004555 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004556 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004557 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004558 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4559 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004560}
4561
Dan Stozae77c7662016-05-13 11:37:28 -07004562void SurfaceFlinger::recordBufferingStats(const char* layerName,
4563 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004564 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4565 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004566 for (const auto& segment : history) {
4567 if (!segment.usedThirdBuffer) {
4568 stats.twoBufferTime += segment.totalTime;
4569 }
4570 if (segment.occupancyAverage < 1.0f) {
4571 stats.doubleBufferedTime += segment.totalTime;
4572 } else if (segment.occupancyAverage < 2.0f) {
4573 stats.tripleBufferedTime += segment.totalTime;
4574 }
4575 ++stats.numSegments;
4576 stats.totalTime += segment.totalTime;
4577 }
4578}
4579
Yiwei Zhang5434a782018-12-05 18:06:32 -08004580void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4581 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004582
4583 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4584 const size_t count = currentLayers.size();
4585 for (size_t i=0 ; i<count ; i++) {
4586 currentLayers[i]->dumpFrameEvents(result);
4587 }
4588}
4589
Yiwei Zhang5434a782018-12-05 18:06:32 -08004590void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004591 result.append("Buffering stats:\n");
4592 result.append(" [Layer name] <Active time> <Two buffer> "
4593 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004594 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004595 typedef std::tuple<std::string, float, float, float> BufferTuple;
4596 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004597 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004598 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004599 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004600 if (stats.numSegments == 0) {
4601 continue;
4602 }
4603 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4604 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4605 stats.totalTime;
4606 float doubleBufferRatio = static_cast<float>(
4607 stats.doubleBufferedTime) / stats.totalTime;
4608 float tripleBufferRatio = static_cast<float>(
4609 stats.tripleBufferedTime) / stats.totalTime;
4610 sorted.insert({activeTime, {name, twoBufferRatio,
4611 doubleBufferRatio, tripleBufferRatio}});
4612 }
4613 for (const auto& sortedPair : sorted) {
4614 float activeTime = sortedPair.first;
4615 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004616 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4617 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004618 }
4619 result.append("\n");
4620}
4621
Yiwei Zhang5434a782018-12-05 18:06:32 -08004622void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004623 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004624 const auto displayId = display->getId();
4625 if (!displayId) {
4626 continue;
4627 }
4628 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004629 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004630 continue;
4631 }
4632
Yiwei Zhang5434a782018-12-05 18:06:32 -08004633 StringAppendF(&result,
4634 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4635 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004636 uint8_t port;
4637 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004638 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004639 result.append("no identification data\n");
4640 continue;
4641 }
4642
4643 if (!isEdid(data)) {
4644 result.append("unknown identification data: ");
4645 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004646 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004647 }
4648 result.append("\n");
4649 continue;
4650 }
4651
4652 const auto edid = parseEdid(data);
4653 if (!edid) {
4654 result.append("invalid EDID: ");
4655 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004656 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004657 }
4658 result.append("\n");
4659 continue;
4660 }
4661
Yiwei Zhang5434a782018-12-05 18:06:32 -08004662 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004663 result.append(edid->displayName.data(), edid->displayName.length());
4664 result.append("\"\n");
4665 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004666}
4667
Yiwei Zhang5434a782018-12-05 18:06:32 -08004668void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4669 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4670 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4671 StringAppendF(&result, "DisplayColorSetting: %s\n",
4672 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004673
4674 // TODO: print out if wide-color mode is active or not
4675
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004676 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004677 const auto displayId = display->getId();
4678 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004679 continue;
4680 }
4681
Yiwei Zhang5434a782018-12-05 18:06:32 -08004682 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004683 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004684 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004685 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004686 }
4687
Lloyd Pique32cbe282018-10-19 13:09:22 -07004688 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004689 StringAppendF(&result, " Current color mode: %s (%d)\n",
4690 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004691 }
4692 result.append("\n");
4693}
4694
Yiwei Zhang5434a782018-12-05 18:06:32 -08004695void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004696 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004697 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4698 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004699 continue;
4700 }
4701
Dominik Laskowski05275f12018-11-01 15:03:24 -07004702 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004703 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4704 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004705 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004706 compositionInfo.dump(result, nullptr);
4707 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004708 }
4709 }
David Sodman7e4ae112018-02-09 15:02:28 -08004710}
4711
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004712LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004713 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004714 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4715 const State& state = useDrawing ? mDrawingState : mCurrentState;
4716 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004717 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004718 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004719 });
4720
4721 return layersProto;
4722}
4723
Lloyd Pique32cbe282018-10-19 13:09:22 -07004724LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004725 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004726
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004727 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004728 resolution->set_w(displayDevice.getWidth());
4729 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004730
Lloyd Pique32cbe282018-10-19 13:09:22 -07004731 auto display = displayDevice.getCompositionDisplay();
4732 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004733
Lloyd Pique32cbe282018-10-19 13:09:22 -07004734 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4735 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4736 layersProto.set_global_transform(displayState.orientation);
4737
4738 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004739 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004740 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004741 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004742 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004743 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004744 }
4745 });
4746
4747 return layersProto;
4748}
4749
Dominik Laskowskic2867142019-01-21 11:33:38 -08004750void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4751 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004752 Colorizer colorizer(colorize);
4753
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004754 // figure out if we're stuck somewhere
4755 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004756 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004757 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4758
4759 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004760 * Dump library configuration.
4761 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004762
4763 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004764 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004765 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004766 appendSfConfigString(result);
4767 appendUiConfigString(result);
4768 appendGuiConfigString(result);
4769 result.append("\n");
4770
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004771 result.append("\nDisplay identification data:\n");
4772 dumpDisplayIdentificationData(result);
4773
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004774 result.append("\nWide-Color information:\n");
4775 dumpWideColorInfo(result);
4776
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004777 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004778 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004779 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004780 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004781 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004782
Andy McFadden41d67d72014-04-25 16:58:34 -07004783 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004784 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004785 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004786 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004787 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004788
Dan Stozab90cf072015-03-05 11:05:59 -08004789 dumpStaticScreenStats(result);
4790 result.append("\n");
4791
Yiwei Zhang5434a782018-12-05 18:06:32 -08004792 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004793
Dan Stozae77c7662016-05-13 11:37:28 -07004794 dumpBufferingStats(result);
4795
Andy McFadden4803b742012-09-24 19:07:20 -07004796 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004797 * Dump the visible layer list
4798 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004799 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004800 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4801 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4802 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004803 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004804
Chia-I Wu2f884132018-09-13 15:17:58 -07004805 {
4806 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4807 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004808 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004809 result.append("\n");
4810 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004811
David Sodman7e4ae112018-02-09 15:02:28 -08004812 result.append("\nFrame-Composition information:\n");
4813 dumpFrameCompositionInfo(result);
4814 result.append("\n");
4815
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004816 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004817 * Dump Display state
4818 */
4819
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004820 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004821 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004822 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004823 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004824 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004825 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004826 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004827
4828 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004829 * Dump SurfaceFlinger global state
4830 */
4831
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004832 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004833 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004834 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004835
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004836 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004837
Dominik Laskowski075d3172018-05-24 15:50:06 -07004838 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004839 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4840 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004841 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4842 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004843 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004844 StringAppendF(&result,
4845 " transaction-flags : %08x\n"
4846 " gpu_to_cpu_unsupported : %d\n",
4847 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004848
Dominik Laskowski075d3172018-05-24 15:50:06 -07004849 if (const auto displayId = getInternalDisplayId();
4850 displayId && getHwComposer().isConnected(*displayId)) {
4851 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004852 StringAppendF(&result,
4853 " refresh-rate : %f fps\n"
4854 " x-dpi : %f\n"
4855 " y-dpi : %f\n",
4856 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4857 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004858 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004859
Yiwei Zhang5434a782018-12-05 18:06:32 -08004860 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004861
Dan Stozae22aec72016-08-01 13:20:59 -07004862 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004863 * Tracing state
4864 */
4865 mTracing.dump(result);
4866 result.append("\n");
4867
4868 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004869 * HWC layer minidump
4870 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004871 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004872 const auto displayId = display->getId();
4873 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004874 continue;
4875 }
4876
Yiwei Zhang5434a782018-12-05 18:06:32 -08004877 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004878 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004879 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004880 result.append("\n");
4881 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004882
4883 /*
4884 * Dump HWComposer state
4885 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004886 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004887 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004888 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004889 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004890 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004891 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004892
4893 /*
4894 * Dump gralloc state
4895 */
4896 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4897 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004898
4899 /*
4900 * Dump VrFlinger state if in use.
4901 */
4902 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4903 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004904 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004905 result.append("\n");
4906 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004907
4908 /**
4909 * Scheduler dump state.
4910 */
4911 if (mUseScheduler) {
4912 result.append("\nScheduler state:\n");
4913 result.append(mScheduler->doDump() + "\n");
4914 result.append(mRefreshRateStats->doDump() + "\n");
4915 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004916}
4917
Dominik Laskowski075d3172018-05-24 15:50:06 -07004918const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004919 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004920 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004921 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004922 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004923 }
4924 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004925
Dominik Laskowski34157762018-10-31 13:07:19 -07004926 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004927 static const Vector<sp<Layer>> empty;
4928 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004929}
4930
Keun young Park63f165f2012-08-31 10:53:36 -07004931bool SurfaceFlinger::startDdmConnection()
4932{
4933 void* libddmconnection_dso =
4934 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4935 if (!libddmconnection_dso) {
4936 return false;
4937 }
4938 void (*DdmConnection_start)(const char* name);
4939 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004940 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004941 if (!DdmConnection_start) {
4942 dlclose(libddmconnection_dso);
4943 return false;
4944 }
4945 (*DdmConnection_start)(getServiceName());
4946 return true;
4947}
4948
Chia-I Wu28f320b2018-05-03 11:02:56 -07004949void SurfaceFlinger::updateColorMatrixLocked() {
4950 mat4 colorMatrix;
4951 if (mGlobalSaturationFactor != 1.0f) {
4952 // Rec.709 luma coefficients
4953 float3 luminance{0.213f, 0.715f, 0.072f};
4954 luminance *= 1.0f - mGlobalSaturationFactor;
4955 mat4 saturationMatrix = mat4(
4956 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4957 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4958 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4959 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4960 );
4961 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4962 } else {
4963 colorMatrix = mClientColorMatrix * mDaltonizer();
4964 }
4965
4966 if (mCurrentState.colorMatrix != colorMatrix) {
4967 mCurrentState.colorMatrix = colorMatrix;
4968 mCurrentState.colorMatrixChanged = true;
4969 setTransactionFlags(eTransactionNeeded);
4970 }
4971}
4972
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004973status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004974#pragma clang diagnostic push
4975#pragma clang diagnostic error "-Wswitch-enum"
4976 switch (static_cast<ISurfaceComposerTag>(code)) {
4977 // These methods should at minimum make sure that the client requested
4978 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004979 case BOOT_FINISHED:
4980 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004981 case CREATE_DISPLAY:
4982 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004983 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004984 case GET_ACTIVE_COLOR_MODE:
4985 case GET_ANIMATION_FRAME_STATS:
4986 case GET_HDR_CAPABILITIES:
4987 case SET_ACTIVE_CONFIG:
4988 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004989 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004990 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004991 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004992 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4993 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004994 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4995 IPCThreadState* ipc = IPCThreadState::self();
4996 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4997 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004998 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004999 }
Robert Carr1db73f62016-12-21 12:58:51 -08005000 return OK;
5001 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005002 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005003 IPCThreadState* ipc = IPCThreadState::self();
5004 const int pid = ipc->getCallingPid();
5005 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005006 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5007 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005008 return PERMISSION_DENIED;
5009 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005010 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005011 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005012 // Used by apps to hook Choreographer to SurfaceFlinger.
5013 case CREATE_DISPLAY_EVENT_CONNECTION:
5014 // The following calls are currently used by clients that do not
5015 // request necessary permissions. However, they do not expose any secret
5016 // information, so it is OK to pass them.
5017 case AUTHENTICATE_SURFACE:
5018 case GET_ACTIVE_CONFIG:
5019 case GET_BUILT_IN_DISPLAY:
5020 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005021 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005022 case GET_DISPLAY_CONFIGS:
5023 case GET_DISPLAY_STATS:
5024 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5025 // Calling setTransactionState is safe, because you need to have been
5026 // granted a reference to Client* and Handle* to do anything with it.
5027 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005028 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005029 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005030 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005031 case GET_PROTECTED_CONTENT_SUPPORT:
5032 case CACHE_BUFFER:
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08005033 case UNCACHE_BUFFER:
5034 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005035 return OK;
5036 }
5037 case CAPTURE_LAYERS:
5038 case CAPTURE_SCREEN: {
5039 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005040 IPCThreadState* ipc = IPCThreadState::self();
5041 const int pid = ipc->getCallingPid();
5042 const int uid = ipc->getCallingUid();
5043 if ((uid != AID_GRAPHICS) &&
5044 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5045 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5046 return PERMISSION_DENIED;
5047 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005048 return OK;
5049 }
5050 // The following codes are deprecated and should never be allowed to access SF.
5051 case CONNECT_DISPLAY_UNUSED:
5052 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5053 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5054 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005055 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005056 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005057
5058 // These codes are used for the IBinder protocol to either interrogate the recipient
5059 // side of the transaction for its canonical interface descriptor or to dump its state.
5060 // We let them pass by default.
5061 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5062 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5063 code == IBinder::SYSPROPS_TRANSACTION) {
5064 return OK;
5065 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005066 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005067 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005068 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005069 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5070 return OK;
5071 }
5072 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5073 return PERMISSION_DENIED;
5074#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005075}
5076
Ana Krulec13be8ad2018-08-21 02:43:56 +00005077status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5078 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005079 status_t credentialCheck = CheckTransactCodeCredentials(code);
5080 if (credentialCheck != OK) {
5081 return credentialCheck;
5082 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005083
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005084 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5085 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005086 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005087 IPCThreadState* ipc = IPCThreadState::self();
5088 const int uid = ipc->getCallingUid();
5089 if (CC_UNLIKELY(uid != AID_SYSTEM
5090 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005091 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005092 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005093 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005094 return PERMISSION_DENIED;
5095 }
5096 int n;
5097 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005098 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005099 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005100 return NO_ERROR;
5101 case 1002: // SHOW_UPDATES
5102 n = data.readInt32();
5103 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005104 invalidateHwcGeometry();
5105 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005106 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005107 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005108 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005109 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005110 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005111 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005112 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005113 setTransactionFlags(
5114 eTransactionNeeded|
5115 eDisplayTransactionNeeded|
5116 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005117 return NO_ERROR;
5118 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005119 case 1006:{ // send empty update
5120 signalRefresh();
5121 return NO_ERROR;
5122 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005123 case 1008: // toggle use of hw composer
5124 n = data.readInt32();
5125 mDebugDisableHWC = n ? 1 : 0;
5126 invalidateHwcGeometry();
5127 repaintEverything();
5128 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005129 case 1009: // toggle use of transform hint
5130 n = data.readInt32();
5131 mDebugDisableTransformHint = n ? 1 : 0;
5132 invalidateHwcGeometry();
5133 repaintEverything();
5134 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005135 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005136 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005137 reply->writeInt32(0);
5138 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005139 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005140 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005141 return NO_ERROR;
5142 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005143 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005144 if (!display) {
5145 return NAME_NOT_FOUND;
5146 }
5147
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005148 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005149 return NO_ERROR;
5150 }
5151 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005152 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005153 // daltonize
5154 n = data.readInt32();
5155 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005156 case 1:
5157 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5158 break;
5159 case 2:
5160 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5161 break;
5162 case 3:
5163 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5164 break;
5165 default:
5166 mDaltonizer.setType(ColorBlindnessType::None);
5167 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005168 }
5169 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005170 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005171 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005172 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005173 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005174
5175 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005176 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005177 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005178 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005179 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005180 // apply a color matrix
5181 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005182 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005183 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005184 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005185 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005186 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005187 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005188 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005189 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005190 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005191 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005192
5193 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5194 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005195 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005196 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5197 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5198 }
5199
Chia-I Wu28f320b2018-05-03 11:02:56 -07005200 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005201 return NO_ERROR;
5202 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005203 // This is an experimental interface
5204 // Needs to be shifted to proper binder interface when we productize
5205 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005206 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005207 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005208 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005209 return NO_ERROR;
5210 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005211 case 1017: {
5212 n = data.readInt32();
5213 mForceFullDamage = static_cast<bool>(n);
5214 return NO_ERROR;
5215 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005216 case 1018: { // Modify Choreographer's phase offset
5217 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005218 if (mUseScheduler) {
5219 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5220 } else {
5221 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5222 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005223 return NO_ERROR;
5224 }
5225 case 1019: { // Modify SurfaceFlinger's phase offset
5226 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005227 if (mUseScheduler) {
5228 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5229 } else {
5230 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5231 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005232 return NO_ERROR;
5233 }
Irvel468051e2016-06-13 16:44:44 -07005234 case 1020: { // Layer updates interceptor
5235 n = data.readInt32();
5236 if (n) {
5237 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005238 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005239 }
5240 else{
5241 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005242 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005243 }
5244 return NO_ERROR;
5245 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005246 case 1021: { // Disable HWC virtual displays
5247 n = data.readInt32();
5248 mUseHwcVirtualDisplays = !n;
5249 return NO_ERROR;
5250 }
Romain Guy0147a172017-06-01 13:53:56 -07005251 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005252 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005253 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005254
Chia-I Wu28f320b2018-05-03 11:02:56 -07005255 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005256 return NO_ERROR;
5257 }
Romain Guy54f154a2017-10-24 21:40:32 +01005258 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005259 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005260 invalidateHwcGeometry();
5261 repaintEverything();
5262 return NO_ERROR;
5263 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005264 // Deprecate, use 1030 to check whether the device is color managed.
5265 case 1024: {
5266 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005267 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005268 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005269 n = data.readInt32();
5270 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005271 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005272 mTracing.enable();
5273 doTracing("tracing.enable");
5274 reply->writeInt32(NO_ERROR);
5275 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005276 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005277 status_t err = mTracing.disable();
5278 reply->writeInt32(err);
5279 }
5280 return NO_ERROR;
5281 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005282 case 1026: { // Get layer tracing status
5283 reply->writeBool(mTracing.isEnabled());
5284 return NO_ERROR;
5285 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005286 // Is a DisplayColorSetting supported?
5287 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005288 const auto display = getDefaultDisplayDevice();
5289 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005290 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005291 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005292
5293 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5294 switch (setting) {
5295 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005296 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005297 break;
5298 case DisplayColorSetting::UNMANAGED:
5299 reply->writeBool(true);
5300 break;
5301 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005302 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005303 break;
5304 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005305 reply->writeBool(
5306 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005307 break;
5308 }
5309 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005310 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005311 // Is VrFlinger active?
5312 case 1028: {
5313 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005314 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005315 return NO_ERROR;
5316 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005317 // Is device color managed?
5318 case 1030: {
5319 reply->writeBool(useColorManagement);
5320 return NO_ERROR;
5321 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005322 // Override default composition data space
5323 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5324 // && adb shell stop zygote && adb shell start zygote
5325 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5326 // adb shell stop zygote && adb shell start zygote
5327 case 1031: {
5328 Mutex::Autolock _l(mStateLock);
5329 n = data.readInt32();
5330 if (n) {
5331 n = data.readInt32();
5332 if (n) {
5333 Dataspace dataspace = static_cast<Dataspace>(n);
5334 if (!validateCompositionDataspace(dataspace)) {
5335 return BAD_VALUE;
5336 }
5337 mDefaultCompositionDataspace = dataspace;
5338 }
5339 n = data.readInt32();
5340 if (n) {
5341 Dataspace dataspace = static_cast<Dataspace>(n);
5342 if (!validateCompositionDataspace(dataspace)) {
5343 return BAD_VALUE;
5344 }
5345 mWideColorGamutCompositionDataspace = dataspace;
5346 }
5347 } else {
5348 // restore composition data space.
5349 mDefaultCompositionDataspace = defaultCompositionDataspace;
5350 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5351 }
5352 return NO_ERROR;
5353 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005354 }
5355 }
5356 return err;
5357}
5358
Steven Thomas6d8110b2017-08-31 18:24:21 -07005359void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005360 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005361 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005362}
5363
Ana Krulec7d1d6832018-12-27 11:10:09 -08005364void SurfaceFlinger::repaintEverythingForHWC() {
5365 mRepaintEverything = true;
5366 mEventQueue->invalidateForHWC();
5367}
5368
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005369// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5370class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005371public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005372 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5373 ~WindowDisconnector() {
5374 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005375 }
5376
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005377private:
5378 ANativeWindow* mWindow;
5379 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005380};
5381
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005382status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005383 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5384 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005385 uint32_t reqWidth, uint32_t reqHeight,
5386 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005387 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005388 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005389
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005390 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005391
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005392 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5393
Chia-I Wu20261cb2018-08-23 12:55:44 -07005394 sp<DisplayDevice> display;
5395 {
5396 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005397
Chia-I Wu20261cb2018-08-23 12:55:44 -07005398 display = getDisplayDeviceLocked(displayToken);
5399 if (!display) return BAD_VALUE;
5400
Chia-I Wucb023152018-08-28 12:57:23 -07005401 // set the requested width/height to the logical display viewport size
5402 // by default
5403 if (reqWidth == 0 || reqHeight == 0) {
5404 reqWidth = uint32_t(display->getViewport().width());
5405 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005406 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005407 }
5408
Peiyong Lin0e003c92018-09-17 11:09:51 -07005409 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5410 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005411
5412 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005413 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005414 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5415 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005416}
5417
5418status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005419 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5420 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005421 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005422 ATRACE_CALL();
5423
5424 class LayerRenderArea : public RenderArea {
5425 public:
Robert Carr578038f2018-03-09 12:25:24 -08005426 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005427 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5428 bool childrenOnly)
5429 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005430 mLayer(layer),
5431 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005432 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005433 mFlinger(flinger),
5434 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005435 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005436 Rect getBounds() const override {
5437 const Layer::State& layerState(mLayer->getDrawingState());
5438 return mLayer->getBufferSize(layerState);
5439 }
Marissa Wall61c58622018-07-18 10:12:20 -07005440 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005441 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005442 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005443 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005444 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005445 }
chaviwa76b2712017-09-20 12:02:26 -07005446 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005447 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005448 Rect getSourceCrop() const override {
5449 if (mCrop.isEmpty()) {
5450 return getBounds();
5451 } else {
5452 return mCrop;
5453 }
5454 }
Robert Carr578038f2018-03-09 12:25:24 -08005455 class ReparentForDrawing {
5456 public:
5457 const sp<Layer>& oldParent;
5458 const sp<Layer>& newParent;
5459
5460 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5461 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005462 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005463 }
Robert Carr15eae092018-03-23 13:43:53 -07005464 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005465 };
5466
5467 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005468 const Rect sourceCrop = getSourceCrop();
5469 // no need to check rotation because there is none
5470 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5471 sourceCrop.height() != getReqHeight();
5472
Robert Carr578038f2018-03-09 12:25:24 -08005473 if (!mChildrenOnly) {
5474 mTransform = mLayer->getTransform().inverse();
5475 drawLayers();
5476 } else {
5477 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005478 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005479 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5480 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005481
5482 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5483 drawLayers();
5484 }
5485 }
chaviwa76b2712017-09-20 12:02:26 -07005486
chaviwa76b2712017-09-20 12:02:26 -07005487 private:
chaviw7206d492017-11-10 16:16:12 -08005488 const sp<Layer> mLayer;
5489 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005490
5491 // In the "childrenOnly" case we reparent the children to a screenshot
5492 // layer which has no properties set and which does not draw.
5493 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005494 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005495 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005496
5497 SurfaceFlinger* mFlinger;
5498 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005499 };
5500
5501 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5502 auto parent = layerHandle->owner.promote();
5503
Robert Carr2e102c92018-10-23 12:11:15 -07005504 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005505 ALOGE("captureLayers called with a removed parent");
5506 return NAME_NOT_FOUND;
5507 }
5508
Robert Carr578038f2018-03-09 12:25:24 -08005509 const int uid = IPCThreadState::self()->getCallingUid();
5510 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005511 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005512 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5513 return PERMISSION_DENIED;
5514 }
5515
chaviw7206d492017-11-10 16:16:12 -08005516 Rect crop(sourceCrop);
5517 if (sourceCrop.width() <= 0) {
5518 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005519 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005520 }
5521
5522 if (sourceCrop.height() <= 0) {
5523 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005524 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005525 }
5526
5527 int32_t reqWidth = crop.width() * frameScale;
5528 int32_t reqHeight = crop.height() * frameScale;
5529
Chia-I Wu20261cb2018-08-23 12:55:44 -07005530 // really small crop or frameScale
5531 if (reqWidth <= 0) {
5532 reqWidth = 1;
5533 }
5534 if (reqHeight <= 0) {
5535 reqHeight = 1;
5536 }
5537
Peiyong Lin0e003c92018-09-17 11:09:51 -07005538 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005539
Robert Carr578038f2018-03-09 12:25:24 -08005540 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005541 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5542 if (!layer->isVisible()) {
5543 return;
Robert Carr578038f2018-03-09 12:25:24 -08005544 } else if (childrenOnly && layer == parent.get()) {
5545 return;
chaviwa76b2712017-09-20 12:02:26 -07005546 }
5547 visitor(layer);
5548 });
5549 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005550 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005551}
5552
5553status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5554 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005555 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005556 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005557 bool useIdentityTransform) {
5558 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005559
Peiyong Lin0e003c92018-09-17 11:09:51 -07005560 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005561 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5562 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005563 *outBuffer =
5564 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5565 static_cast<android_pixel_format>(reqPixelFormat), 1,
5566 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005567
5568 // This mutex protects syncFd and captureResult for communication of the return values from the
5569 // main thread back to this Binder thread
5570 std::mutex captureMutex;
5571 std::condition_variable captureCondition;
5572 std::unique_lock<std::mutex> captureLock(captureMutex);
5573 int syncFd = -1;
5574 std::optional<status_t> captureResult;
5575
Robert Carr03480e22018-01-04 16:02:06 -08005576 const int uid = IPCThreadState::self()->getCallingUid();
5577 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5578
Dominik Laskowski8c001672018-05-30 16:52:06 -07005579 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005580 // If there is a refresh pending, bug out early and tell the binder thread to try again
5581 // after the refresh.
5582 if (mRefreshPending) {
5583 ATRACE_NAME("Skipping screenshot for now");
5584 std::unique_lock<std::mutex> captureLock(captureMutex);
5585 captureResult = std::make_optional<status_t>(EAGAIN);
5586 captureCondition.notify_one();
5587 return;
5588 }
5589
5590 status_t result = NO_ERROR;
5591 int fd = -1;
5592 {
5593 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005594 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005595 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5596 useIdentityTransform, forSystem, &fd);
5597 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005598 }
5599
5600 {
5601 std::unique_lock<std::mutex> captureLock(captureMutex);
5602 syncFd = fd;
5603 captureResult = std::make_optional<status_t>(result);
5604 captureCondition.notify_one();
5605 }
5606 });
5607
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005608 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005609 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005610 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005611 while (*captureResult == EAGAIN) {
5612 captureResult.reset();
5613 result = postMessageAsync(message);
5614 if (result != NO_ERROR) {
5615 return result;
5616 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005617 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005618 }
5619 result = *captureResult;
5620 }
5621
5622 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005623 sync_wait(syncFd, -1);
5624 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005625 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005626
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005627 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005628}
5629
chaviwa76b2712017-09-20 12:02:26 -07005630void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005631 TraverseLayersFunction traverseLayers,
Alec Mouri0f714832018-11-12 15:31:06 -08005632 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5633 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005634 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005635
chaviwa76b2712017-09-20 12:02:26 -07005636 const auto reqWidth = renderArea.getReqWidth();
5637 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005638 const auto sourceCrop = renderArea.getSourceCrop();
5639 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005640
Alec Mouri0f714832018-11-12 15:31:06 -08005641 renderengine::DisplaySettings clientCompositionDisplay;
5642 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005643
Alec Mouri0f714832018-11-12 15:31:06 -08005644 // assume that bounds are never offset, and that they are the same as the
5645 // buffer bounds.
5646 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5647 ui::Transform transform = renderArea.getTransform();
5648 mat4 m;
5649 m[0][0] = transform[0][0];
5650 m[0][1] = transform[0][1];
5651 m[0][3] = transform[0][2];
5652 m[1][0] = transform[1][0];
5653 m[1][1] = transform[1][1];
5654 m[1][3] = transform[1][2];
5655 m[3][0] = transform[2][0];
5656 m[3][1] = transform[2][1];
5657 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005658
Alec Mouri0f714832018-11-12 15:31:06 -08005659 clientCompositionDisplay.globalTransform = m;
5660 mat4 rotMatrix;
5661 // Displacement for repositioning the clipping rectangle after rotating it
5662 // with the rotation hint.
5663 int displacementX = 0;
5664 int displacementY = 0;
5665 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5666 switch (rotation) {
5667 case ui::Transform::ROT_90:
5668 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5669 displacementX = reqWidth;
5670 break;
5671 case ui::Transform::ROT_180:
5672 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5673 displacementX = reqWidth;
5674 displacementY = reqHeight;
5675 break;
5676 case ui::Transform::ROT_270:
5677 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5678 displacementY = reqHeight;
5679 break;
5680 default:
5681 break;
5682 }
5683 // We need to transform the clipping window into the right spot.
5684 // First, rotate the clipping rectangle by the rotation hint to get the
5685 // right orientation
5686 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5687 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5688 const vec4 rotClipTL = rotMatrix * clipTL;
5689 const vec4 rotClipBR = rotMatrix * clipBR;
5690 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5691 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5692 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5693 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5694
5695 // Now reposition the clipping rectangle with the displacement vector
5696 // computed above.
5697 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5698
5699 clientCompositionDisplay.clip =
5700 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5701 newClipRight + displacementX, newClipBottom + displacementY);
5702
5703 // We need to perform the same transformation in layer space, so propagate
5704 // it to the global transform.
5705 mat4 clipTransform = displacementMat * rotMatrix;
5706 clientCompositionDisplay.globalTransform *= clipTransform;
5707 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5708 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005709
chaviw50da5042018-04-09 13:49:37 -07005710 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005711
Alec Mouri0f714832018-11-12 15:31:06 -08005712 renderengine::LayerSettings fillLayer;
5713 fillLayer.source.buffer.buffer = nullptr;
5714 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5715 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5716 fillLayer.alpha = half(alpha);
5717 clientCompositionLayers.push_back(fillLayer);
5718
5719 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005720 traverseLayers([&](Layer* layer) {
Alec Mouri0f714832018-11-12 15:31:06 -08005721 renderengine::LayerSettings layerSettings;
5722 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5723 layerSettings);
5724 if (prepared) {
5725 clientCompositionLayers.push_back(layerSettings);
5726 }
chaviwa76b2712017-09-20 12:02:26 -07005727 });
Alec Mouri0f714832018-11-12 15:31:06 -08005728
5729 clientCompositionDisplay.clearRegion = clearRegion;
5730 base::unique_fd drawFence;
5731 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
5732 &drawFence);
5733
5734 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005735}
5736
chaviwa76b2712017-09-20 12:02:26 -07005737status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5738 TraverseLayersFunction traverseLayers,
5739 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005740 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005741 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005742 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005743 ATRACE_CALL();
5744
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005745 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005746
5747 traverseLayers([&](Layer* layer) {
5748 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5749 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005750
Robert Carr03480e22018-01-04 16:02:06 -08005751 // We allow the system server to take screenshots of secure layers for
5752 // use in situations like the Screen-rotation animation and place
5753 // the impetus on WindowManager to not persist them.
5754 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005755 ALOGW("FB is protected: PERMISSION_DENIED");
5756 return PERMISSION_DENIED;
5757 }
Alec Mouri0f714832018-11-12 15:31:06 -08005758 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005759 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005760}
5761
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005762// ---------------------------------------------------------------------------
5763
Dan Stoza412903f2017-04-27 13:42:17 -07005764void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5765 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005766}
5767
Dan Stoza412903f2017-04-27 13:42:17 -07005768void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5769 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005770}
5771
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005772void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005773 const LayerVector::Visitor& visitor) {
5774 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005775 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005776 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005777 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005778 continue;
5779 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005780 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005781 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005782 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005783 return;
5784 }
chaviwa76b2712017-09-20 12:02:26 -07005785 if (!layer->isVisible()) {
5786 return;
5787 }
5788 visitor(layer);
5789 });
5790 }
5791}
5792
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005793}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005794
Lloyd Pique074e8122018-07-26 12:57:23 -07005795
Mathias Agopian3f844832013-08-07 21:24:32 -07005796#if defined(__gl_h_)
5797#error "don't include gl/gl.h in this file"
5798#endif
5799
5800#if defined(__gl2_h_)
5801#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005802#endif