blob: 43932e093e83fe446d08d514a12170a00220c4c6 [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
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Robert Carr720e5062018-07-30 17:45:14 -070040#include <input/IInputFlinger.h>
41
Chia-I Wud49d6692018-06-27 07:17:41 +080042#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060043#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070045#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070046
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070048#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070049#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080050#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080051#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080052#include <gui/Surface.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070053#include <renderengine/RenderEngine.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070054#include <ui/GraphicBufferAllocator.h>
55#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070056#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080057
Mathias Agopiancde87a32012-09-13 14:09:01 -070058#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059#include <utils/String8.h>
60#include <utils/String16.h>
61#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070062#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080063#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Mathias Agopian921e6ac2012-07-23 23:11:29 -070065#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070066#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080067
Robert Carr578038f2018-03-09 12:25:24 -080068#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070069#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070070#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020071#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080072#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020073#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080074#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080075#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080076#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070078#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080079#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070080#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070081#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070083#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
Steven Thomasb02664d2017-07-26 18:48:28 -070085#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070086#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070087#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070088#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070089#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070090#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070091#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070092#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070093#include "Scheduler/EventControlThread.h"
94#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070095#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070096#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070097#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080098#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070099
Mathias Agopianff2ed702013-09-01 21:36:12 -0700100#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700101
David Sodman7e4ae112018-02-09 15:02:28 -0800102#include "android-base/stringprintf.h"
103
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900104#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800105#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700106#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800107#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900108#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900109
chaviw1d044282017-09-27 12:19:28 -0700110#include <layerproto/LayerProtoParser.h>
111
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800112namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700113
Jaesoo Lee43518572017-01-23 19:03:16 +0900114using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900115using namespace android::hardware::configstore::V1_0;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800116using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700117using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700118using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700119using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700120using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900121
Steven Thomasb02664d2017-07-26 18:48:28 -0700122namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700123
124#pragma clang diagnostic push
125#pragma clang diagnostic error "-Wswitch-enum"
126
127bool isWideColorMode(const ColorMode colorMode) {
128 switch (colorMode) {
129 case ColorMode::DISPLAY_P3:
130 case ColorMode::ADOBE_RGB:
131 case ColorMode::DCI_P3:
132 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700133 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700134 case ColorMode::BT2100_PQ:
135 case ColorMode::BT2100_HLG:
136 return true;
137 case ColorMode::NATIVE:
138 case ColorMode::STANDARD_BT601_625:
139 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
140 case ColorMode::STANDARD_BT601_525:
141 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
142 case ColorMode::STANDARD_BT709:
143 case ColorMode::SRGB:
144 return false;
145 }
146 return false;
147}
148
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700149ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
150 switch (rotation) {
151 case ISurfaceComposer::eRotateNone:
152 return ui::Transform::ROT_0;
153 case ISurfaceComposer::eRotate90:
154 return ui::Transform::ROT_90;
155 case ISurfaceComposer::eRotate180:
156 return ui::Transform::ROT_180;
157 case ISurfaceComposer::eRotate270:
158 return ui::Transform::ROT_270;
159 }
160 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
161 return ui::Transform::ROT_0;
162}
163
Peiyong Linfca547f2018-07-09 13:03:33 -0700164#pragma clang diagnostic pop
165
Steven Thomasb02664d2017-07-26 18:48:28 -0700166class ConditionalLock {
167public:
168 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
169 if (lock) {
170 mMutex.lock();
171 }
172 }
173 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
174private:
175 Mutex& mMutex;
176 bool mLocked;
177};
Peiyong Linfca547f2018-07-09 13:03:33 -0700178
Peiyong Lin9d846a52018-11-05 13:18:20 -0800179// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
180bool validateCompositionDataspace(Dataspace dataspace) {
181 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
182}
183
Steven Thomasb02664d2017-07-26 18:48:28 -0700184} // namespace anonymous
185
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800186// ---------------------------------------------------------------------------
187
Mathias Agopian99b49842011-06-27 16:05:52 -0700188const String16 sHardwareTest("android.permission.HARDWARE_TEST");
189const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
190const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
191const String16 sDump("android.permission.DUMP");
192
193// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800194int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
195int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700196int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700197bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800198uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800199bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800200bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800201int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600202bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700203int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700204bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700205bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700206Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
207ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
208Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
209ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700210
Kalle Raitaa099a242017-01-11 11:17:29 -0800211std::string getHwcServiceName() {
212 char value[PROPERTY_VALUE_MAX] = {};
213 property_get("debug.sf.hwc_service_name", value, "default");
214 ALOGI("Using HWComposer service: '%s'", value);
215 return std::string(value);
216}
217
218bool useTrebleTestingOverride() {
219 char value[PROPERTY_VALUE_MAX] = {};
220 property_get("debug.sf.treble_testing_override", value, "false");
221 ALOGI("Treble testing override: '%s'", value);
222 return std::string(value) == "true";
223}
224
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800225std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
226 switch(displayColorSetting) {
227 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700228 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800229 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700230 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800231 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700232 return std::string("Enhanced");
233 default:
234 return std::string("Unknown ") +
235 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800236 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800237}
238
David Sodmanbc815282017-11-05 18:57:52 -0800239SurfaceFlingerBE::SurfaceFlingerBE()
240 : mHwcServiceName(getHwcServiceName()),
241 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800242 mFrameBuckets(),
243 mTotalTime(0),
244 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800245 mComposerSequenceId(0) {
246}
247
Lloyd Pique90c115d2018-09-18 21:39:42 -0700248SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
249 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800250 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700251 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700252 mTransactionPending(false),
253 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700254 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700255 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800256 mBootTime(systemTime()),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800258 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800259 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800260 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800261 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700262 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700263 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700264 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700265 mDebugInTransaction(0),
266 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700267 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800268 mTimeStats(factory.createTimeStats()),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700269 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700270 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800271 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800272 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800273 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700274 mVrFlingerRequestsDisplay(false),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700275 mMainThreadId(std::this_thread::get_id()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800276
Lloyd Pique90c115d2018-09-18 21:39:42 -0700277SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
278 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800279 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800280
281 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
282 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
283
284 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
285 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
286
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800287 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
288 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800289
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700290 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
291 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
292
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700293 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
294 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
295
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800296 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
297 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
298
Steven Thomas050b2c82017-03-06 11:45:16 -0800299 // Vr flinger is only enabled on Daydream ready devices.
300 useVrFlinger = getBool< ISurfaceFlingerConfigs,
301 &ISurfaceFlingerConfigs::useVrFlinger>(false);
302
Fabien Sanglard1971b632017-03-10 14:50:03 -0800303 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
304 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
305
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600306 hasWideColorDisplay =
307 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700308 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700309 getBool<V1_2::ISurfaceFlingerConfigs,
310 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
311
312 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
313 if (surfaceFlingerConfigsServiceV1_2) {
314 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
Peiyong Linc6780972018-10-28 15:24:08 -0700315 [&](auto tmpDefaultDataspace, auto tmpDefaultPixelFormat,
316 auto tmpWideColorGamutDataspace, auto tmpWideColorGamutPixelFormat) {
317 defaultCompositionDataspace = tmpDefaultDataspace;
318 defaultCompositionPixelFormat = tmpDefaultPixelFormat;
319 wideColorGamutCompositionDataspace = tmpWideColorGamutDataspace;
320 wideColorGamutCompositionPixelFormat = tmpWideColorGamutPixelFormat;
321 });
Peiyong Lin0256f722018-08-31 15:45:10 -0700322 }
Peiyong Lin9d846a52018-11-05 13:18:20 -0800323 mDefaultCompositionDataspace = defaultCompositionDataspace;
324 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600325
Peiyong Linb3839ad2018-09-05 15:37:19 -0700326 useContextPriority = getBool<ISurfaceFlingerConfigs,
327 &ISurfaceFlingerConfigs::useContextPriority>(true);
328
Iris Chang7501ed62018-04-30 14:45:42 +0800329 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700330 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
331 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800332 V1_1::DisplayOrientation::ORIENTATION_0);
333
334 switch (primaryDisplayOrientation) {
335 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700336 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800337 break;
338 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700339 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800340 break;
341 case V1_1::DisplayOrientation::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
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800354 // debugging stuff...
355 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700356
Mathias Agopianb4b17302013-03-20 18:36:41 -0700357 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700358 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700359
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800360 property_get("debug.sf.showupdates", value, "0");
361 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700362
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700363 property_get("debug.sf.ddms", value, "0");
364 mDebugDDMS = atoi(value);
365 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700366 if (!startDdmConnection()) {
367 // start failed, and DDMS debugging not enabled
368 mDebugDDMS = 0;
369 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700370 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700371 ALOGI_IF(mDebugRegion, "showupdates enabled");
372 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700373
374 property_get("debug.sf.disable_backpressure", value, "0");
375 mPropagateBackpressure = !atoi(value);
376 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700377
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800378 property_get("debug.sf.enable_hwc_vds", value, "0");
379 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800380 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800381
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800382 property_get("ro.sf.disable_triple_buffer", value, "1");
383 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800384 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700385
Yiwei Zhang243b3782018-05-15 17:40:04 -0700386 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700387 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
388 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
389
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200390 property_get("debug.sf.early_phase_offset_ns", value, "-1");
391 const int earlySfOffsetNs = atoi(value);
392
393 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
394 const int earlyGlSfOffsetNs = atoi(value);
395
396 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
397 const int earlyAppOffsetNs = atoi(value);
398
399 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
400 const int earlyGlAppOffsetNs = atoi(value);
401
Ana Krulec98b5b242018-08-10 15:03:23 -0700402 property_get("debug.sf.use_scheduler", value, "0");
403 mUseScheduler = atoi(value);
404
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200405 const VSyncModulator::Offsets earlyOffsets =
406 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
407 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
408 const VSyncModulator::Offsets earlyGlOffsets =
409 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
410 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
411 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
412 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700413
Romain Guy11d63f42017-07-20 12:47:14 -0700414 // We should be reading 'persist.sys.sf.color_saturation' here
415 // but since /data may be encrypted, we need to wait until after vold
416 // comes online to attempt to read the property. The property is
417 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800418
419 if (useTrebleTestingOverride()) {
420 // Without the override SurfaceFlinger cannot connect to HIDL
421 // services that are not listed in the manifests. Considered
422 // deriving the setting from the set service name, but it
423 // would be brittle if the name that's not 'default' is used
424 // for production purposes later on.
425 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
426 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800427}
428
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800429void SurfaceFlinger::onFirstRef()
430{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800431 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800432}
433
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800434SurfaceFlinger::~SurfaceFlinger()
435{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800436}
437
Dan Stozac7014012014-02-14 15:03:43 -0800438void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800439{
440 // the window manager died on us. prepare its eulogy.
441
Andy McFadden13a082e2012-08-24 10:16:42 -0700442 // restore initial conditions (default device unblank, etc)
443 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800444
445 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700446 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800447}
448
Robert Carr1db73f62016-12-21 12:58:51 -0800449static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700450 status_t err = client->initCheck();
451 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800452 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800453 }
Robert Carr1db73f62016-12-21 12:58:51 -0800454 return nullptr;
455}
456
457sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
458 return initClient(new Client(this));
459}
460
461sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
462 const sp<IGraphicBufferProducer>& gbp) {
463 if (authenticateSurfaceTexture(gbp) == false) {
464 return nullptr;
465 }
466 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
467 if (layer == nullptr) {
468 return nullptr;
469 }
470
471 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800472}
473
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700474sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
475 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700476{
477 class DisplayToken : public BBinder {
478 sp<SurfaceFlinger> flinger;
479 virtual ~DisplayToken() {
480 // no more references, this display must be terminated
481 Mutex::Autolock _l(flinger->mStateLock);
482 flinger->mCurrentState.displays.removeItem(this);
483 flinger->setTransactionFlags(eDisplayTransactionNeeded);
484 }
485 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700486 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700487 : flinger(flinger) {
488 }
489 };
490
491 sp<BBinder> token = new DisplayToken(this);
492
493 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700494 // Display ID is assigned when virtual display is allocated by HWC.
495 DisplayDeviceState state;
496 state.isSecure = secure;
497 state.displayName = displayName;
498 mCurrentState.displays.add(token, state);
499 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700500 return token;
501}
502
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700503void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700504 Mutex::Autolock _l(mStateLock);
505
Dominik Laskowski075d3172018-05-24 15:50:06 -0700506 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
507 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700508 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700509 return;
510 }
511
Dominik Laskowski075d3172018-05-24 15:50:06 -0700512 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
513 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700514 ALOGE("destroyDisplay called for non-virtual display");
515 return;
516 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700517 mInterceptor->saveDisplayDeletion(state.sequenceId);
518 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700519 setTransactionFlags(eDisplayTransactionNeeded);
520}
521
Mathias Agopiane57f2922012-08-09 16:29:12 -0700522sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700523 std::optional<DisplayId> displayId;
524
525 if (id == HWC_DISPLAY_PRIMARY) {
526 displayId = getInternalDisplayId();
527 } else if (id == HWC_DISPLAY_EXTERNAL) {
528 displayId = getExternalDisplayId();
529 }
530
531 if (!displayId) {
532 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800533 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700534 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700535
536 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700537}
538
Ady Abraham37965d42018-11-01 13:43:32 -0700539status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
540 if (!outGetColorManagement) {
541 return BAD_VALUE;
542 }
543 *outGetColorManagement = useColorManagement;
544 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700545}
546
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800547void SurfaceFlinger::bootFinished()
548{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700549 if (mStartPropertySetThread->join() != NO_ERROR) {
550 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800551 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800552 const nsecs_t now = systemTime();
553 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000554 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700555
556 // wait patiently for the window manager death
557 const String16 name("window");
558 sp<IBinder> window(defaultServiceManager()->getService(name));
559 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700560 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700561 }
Robert Carr720e5062018-07-30 17:45:14 -0700562 sp<IBinder> input(defaultServiceManager()->getService(
563 String16("inputflinger")));
564 if (input == nullptr) {
565 ALOGE("Failed to link to input service");
566 } else {
567 mInputFlinger = interface_cast<IInputFlinger>(input);
568 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700569
Steven Thomas050b2c82017-03-06 11:45:16 -0800570 if (mVrFlinger) {
571 mVrFlinger->OnBootFinished();
572 }
573
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700574 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700575 // formerly we would just kill the process, but we now ask it to exit so it
576 // can choose where to stop the animation.
577 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700578
579 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
580 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
581 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700582
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800583 postMessageAsync(new LambdaMessage([this] {
584 readPersistentProperties();
585 mBootStage = BootStage::FINISHED;
586 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800587}
588
Dan Stoza436ccf32018-06-21 12:10:12 -0700589uint32_t SurfaceFlinger::getNewTexture() {
590 {
591 std::lock_guard lock(mTexturePoolMutex);
592 if (!mTexturePool.empty()) {
593 uint32_t name = mTexturePool.back();
594 mTexturePool.pop_back();
595 ATRACE_INT("TexturePoolSize", mTexturePool.size());
596 return name;
597 }
598
599 // The pool was too small, so increase it for the future
600 ++mTexturePoolSize;
601 }
602
603 // The pool was empty, so we need to get a new texture name directly using a
604 // blocking call to the main thread
605 uint32_t name = 0;
606 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
607 return name;
608}
609
Mathias Agopian3f844832013-08-07 21:24:32 -0700610void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700611 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700612}
613
Wei Wangf9b05ee2017-07-19 20:59:39 -0700614// Do not call property_set on main thread which will be blocked by init
615// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700616void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700617 ALOGI( "SurfaceFlinger's main thread ready to run. "
618 "Initializing graphics H/W...");
619
Thierry Strudel2924d012017-08-14 15:19:37 -0700620 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900621
Steven Thomasb02664d2017-07-26 18:48:28 -0700622 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800623
Steven Thomasb02664d2017-07-26 18:48:28 -0700624 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700625 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700626 mScheduler = getFactory().createScheduler([this](bool enabled) {
627 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
628 });
629
Ana Krulec98b5b242018-08-10 15:03:23 -0700630 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700631 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700632 [this] { resyncWithRateLimit(); },
633 impl::EventThread::InterceptVSyncsCallback());
634 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700635 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700636 [this] { resyncWithRateLimit(); },
637 [this](nsecs_t timestamp) {
638 mInterceptor->saveVSyncEvent(timestamp);
639 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800640
Ana Krulec98b5b242018-08-10 15:03:23 -0700641 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700642 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
643 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700644 } else {
645 mEventThreadSource =
646 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
647 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
648 mEventThread =
649 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
650 [this] { resyncWithRateLimit(); },
651 impl::EventThread::InterceptVSyncsCallback(),
652 "appEventThread");
653 mSfEventThreadSource =
654 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
655 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
656
657 mSFEventThread =
658 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
659 [this] { resyncWithRateLimit(); },
660 [this](nsecs_t timestamp) {
661 mInterceptor->saveVSyncEvent(timestamp);
662 },
663 "sfEventThread");
664 mEventQueue->setEventThread(mSFEventThread.get());
665 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
666 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800667
Steven Thomasb02664d2017-07-26 18:48:28 -0700668 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700669 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700670 renderEngineFeature |= (useColorManagement ?
671 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700672 renderEngineFeature |= (useContextPriority ?
673 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700674
675 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
676 getBE().mRenderEngine =
Peiyong Linc6780972018-10-28 15:24:08 -0700677 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
678 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800679 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700680
681 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
682 "Starting with vr flinger active is not currently supported.");
Lloyd Pique90c115d2018-09-18 21:39:42 -0700683 getBE().mHwc = getFactory().createHWComposer(getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -0700684 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800685 // Process any initial hotplug and resulting display changes.
686 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700687 const auto display = getDefaultDisplayDeviceLocked();
688 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700689 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700690 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800691
Steven Thomas050b2c82017-03-06 11:45:16 -0800692 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700693 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700694 // This callback is called from the vr flinger dispatch thread. We
695 // need to call signalTransaction(), which requires holding
696 // mStateLock when we're not on the main thread. Acquiring
697 // mStateLock from the vr flinger dispatch thread might trigger a
698 // deadlock in surface flinger (see b/66916578), so post a message
699 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700700 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700701 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
702 mVrFlingerRequestsDisplay = requestDisplay;
703 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700704 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800705 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700706 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
707 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700708 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700709 .value_or(0),
710 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800711 if (!mVrFlinger) {
712 ALOGE("Failed to start vrflinger");
713 }
714 }
715
Lloyd Pique90c115d2018-09-18 21:39:42 -0700716 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700717 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700718
Mathias Agopian92a979a2012-08-02 18:32:23 -0700719 // initialize our drawing state
720 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700721
Andy McFadden13a082e2012-08-24 10:16:42 -0700722 // set initial conditions (e.g. unblank default device)
723 initializeDisplays();
724
David Sodmanbc815282017-11-05 18:57:52 -0800725 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700726
Wei Wangf9b05ee2017-07-19 20:59:39 -0700727 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700728
729 const bool presentFenceReliable =
730 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
731 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700732
733 if (mStartPropertySetThread->Start() != NO_ERROR) {
734 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800735 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800736
Chia-I Wud49d6692018-06-27 07:17:41 +0800737 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
738 // is used to saturate legacy sRGB content. However, to make sure the same color under
739 // Display P3 will be saturated to the same color, we intentionally break the API spec
740 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
741 // such saturation matrix on Display P3 is understood fully, the API should always return
742 // identify matrix.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700743 mEnhancedSaturationMatrix =
744 getHwComposer().getDataspaceSaturationMatrix(*display->getId(), Dataspace::SRGB_LINEAR);
Chia-I Wud49d6692018-06-27 07:17:41 +0800745
746 // we will apply this on Display P3.
747 if (mEnhancedSaturationMatrix != mat4()) {
748 ColorSpace srgb(ColorSpace::sRGB());
749 ColorSpace displayP3(ColorSpace::DisplayP3());
750 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
751 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
752 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
753 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800754
Dan Stoza9e56aa02015-11-02 13:00:03 -0800755 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700756}
757
Romain Guy11d63f42017-07-20 12:47:14 -0700758void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700759 Mutex::Autolock _l(mStateLock);
760
Romain Guy11d63f42017-07-20 12:47:14 -0700761 char value[PROPERTY_VALUE_MAX];
762
763 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800764 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700765 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800766 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100767
768 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700769 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700770}
771
Mathias Agopiana67e4182012-06-19 17:26:12 -0700772void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800773 // Start boot animation service by setting a property mailbox
774 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700775 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800776 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700777 if (mStartPropertySetThread->join() != NO_ERROR) {
778 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800779 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700780}
781
Mathias Agopian875d8e12013-06-07 15:35:48 -0700782size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800783 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700784}
785
Mathias Agopian875d8e12013-06-07 15:35:48 -0700786size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800787 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700788}
789
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800790// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800791
Jamie Gennis582270d2011-08-17 18:19:00 -0700792bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800793 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800794 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800795 return authenticateSurfaceTextureLocked(bufferProducer);
796}
797
798bool SurfaceFlinger::authenticateSurfaceTextureLocked(
799 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800800 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800801 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800802}
803
Brian Anderson6b376712017-04-04 10:51:39 -0700804status_t SurfaceFlinger::getSupportedFrameTimestamps(
805 std::vector<FrameEvent>* outSupported) const {
806 *outSupported = {
807 FrameEvent::REQUESTED_PRESENT,
808 FrameEvent::ACQUIRE,
809 FrameEvent::LATCH,
810 FrameEvent::FIRST_REFRESH_START,
811 FrameEvent::LAST_REFRESH_START,
812 FrameEvent::GPU_COMPOSITION_DONE,
813 FrameEvent::DEQUEUE_READY,
814 FrameEvent::RELEASE,
815 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700816 ConditionalLock _l(mStateLock,
817 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700818 if (!getHwComposer().hasCapability(
819 HWC2::Capability::PresentFenceIsNotReliable)) {
820 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
821 }
822 return NO_ERROR;
823}
824
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700825status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
826 Vector<DisplayInfo>* configs) {
827 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700828 return BAD_VALUE;
829 }
830
Dominik Laskowski075d3172018-05-24 15:50:06 -0700831 const auto displayId = getPhysicalDisplayId(displayToken);
832 if (!displayId) {
833 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700834 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835
Mathias Agopian8b736f12012-08-13 17:54:26 -0700836 // TODO: Not sure if display density should handled by SF any longer
837 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700838 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700839 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700840 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800841 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700842 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700843 }
844 return density;
845 }
846 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700847 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700848 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700849 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700850 return getDensityFromProperty("ro.sf.lcd_density"); }
851 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700852
Dan Stoza7f7da322014-05-02 15:26:25 -0700853 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700854
Steven Thomas6d8110b2017-08-31 18:24:21 -0700855 ConditionalLock _l(mStateLock,
856 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700857 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700858 DisplayInfo info = DisplayInfo();
859
Dan Stoza9e56aa02015-11-02 13:00:03 -0800860 float xdpi = hwConfig->getDpiX();
861 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700862
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700863 info.w = hwConfig->getWidth();
864 info.h = hwConfig->getHeight();
865 // Default display viewport to display width and height
866 info.viewportW = info.w;
867 info.viewportH = info.h;
868
Dominik Laskowski075d3172018-05-24 15:50:06 -0700869 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700870 // The density of the device is provided by a build property
871 float density = Density::getBuildDensity() / 160.0f;
872 if (density == 0) {
873 // the build doesn't provide a density -- this is wrong!
874 // use xdpi instead
875 ALOGE("ro.sf.lcd_density must be defined as a build property");
876 density = xdpi / 160.0f;
877 }
878 if (Density::getEmuDensity()) {
879 // if "qemu.sf.lcd_density" is specified, it overrides everything
880 xdpi = ydpi = density = Density::getEmuDensity();
881 density /= 160.0f;
882 }
883 info.density = density;
884
885 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700886 const auto display = getDefaultDisplayDeviceLocked();
887 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700888
889 // This is for screenrecord
890 const Rect viewport = display->getViewport();
891 if (viewport.isValid()) {
892 info.viewportW = uint32_t(viewport.getWidth());
893 info.viewportH = uint32_t(viewport.getHeight());
894 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700895 } else {
896 // TODO: where should this value come from?
897 static const int TV_DENSITY = 213;
898 info.density = TV_DENSITY / 160.0f;
899 info.orientation = 0;
900 }
901
Dan Stoza7f7da322014-05-02 15:26:25 -0700902 info.xdpi = xdpi;
903 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800904 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900905 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800906
Andy McFadden91b2ca82014-06-13 14:04:23 -0700907 // This is how far in advance a buffer must be queued for
908 // presentation at a given time. If you want a buffer to appear
909 // on the screen at time N, you must submit the buffer before
910 // (N - presentationDeadline).
911 //
912 // Normally it's one full refresh period (to give SF a chance to
913 // latch the buffer), but this can be reduced by configuring a
914 // DispSync offset. Any additional delays introduced by the hardware
915 // composer or panel must be accounted for here.
916 //
917 // We add an additional 1ms to allow for processing time and
918 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800919 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800920 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700921
922 // All non-virtual displays are currently considered secure.
923 info.secure = true;
924
Dominik Laskowski075d3172018-05-24 15:50:06 -0700925 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700926 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800927 std::swap(info.w, info.h);
928 }
929
Michael Wright28f24d02016-07-12 13:30:53 -0700930 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700931 }
932
Dan Stoza7f7da322014-05-02 15:26:25 -0700933 return NO_ERROR;
934}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700935
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700936status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
937 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700938 return BAD_VALUE;
939 }
940
Ana Krulece588e312018-09-18 12:32:24 -0700941 if (mUseScheduler) {
942 mScheduler->getDisplayStatInfo(stats);
943 } else {
944 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
945 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
946 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700947 return NO_ERROR;
948}
949
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700950int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
951 const auto display = getDisplayDevice(displayToken);
952 if (!display) {
953 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800954 return BAD_VALUE;
955 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700956
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700957 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700958}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700959
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700960void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700961 if (display->isVirtual()) {
962 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
963 return;
964 }
965
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700966 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700967 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700968 return;
969 }
970
Dominik Laskowski075d3172018-05-24 15:50:06 -0700971 const auto displayId = display->getId();
972 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700973
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700974 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700975 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700976}
977
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700978status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700979 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700980 Vector<DisplayInfo> configs;
981 getDisplayConfigs(displayToken, &configs);
982 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
983 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
984 configs.size());
985 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700986 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700987 const auto display = getDisplayDevice(displayToken);
988 if (!display) {
989 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
990 displayToken.get());
991 } else if (display->isVirtual()) {
992 ALOGW("Attempt to set active config %d for virtual display", mode);
993 } else {
994 setActiveConfigInternal(display, mode);
995 }
996 }));
997
Mathias Agopian888c8222012-08-04 21:10:38 -0700998 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700999}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001000
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001001status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1002 Vector<ColorMode>* outColorModes) {
1003 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001004 return BAD_VALUE;
1005 }
1006
Dominik Laskowski075d3172018-05-24 15:50:06 -07001007 const auto displayId = getPhysicalDisplayId(displayToken);
1008 if (!displayId) {
1009 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -07001010 }
1011
Peiyong Lina52f0292018-03-14 17:26:31 -07001012 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001013 {
1014 ConditionalLock _l(mStateLock,
1015 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001016 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001017 }
Michael Wright28f24d02016-07-12 13:30:53 -07001018 outColorModes->clear();
1019 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1020
1021 return NO_ERROR;
1022}
1023
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001024ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1025 if (const auto display = getDisplayDevice(displayToken)) {
1026 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001027 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001028 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001029}
1030
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001031void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1032 Dataspace dataSpace, RenderIntent renderIntent) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001033 if (display->isVirtual()) {
1034 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
1035 return;
1036 }
1037
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001038 ColorMode currentMode = display->getActiveColorMode();
1039 Dataspace currentDataSpace = display->getCompositionDataSpace();
1040 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001041
Peiyong Lin38e9a562018-04-10 16:24:20 -07001042 if (mode == currentMode && dataSpace == currentDataSpace &&
1043 renderIntent == currentRenderIntent) {
1044 return;
1045 }
1046
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001047 display->setActiveColorMode(mode);
1048 display->setCompositionDataSpace(dataSpace);
1049 display->setActiveRenderIntent(renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001050
Dominik Laskowski075d3172018-05-24 15:50:06 -07001051 const auto displayId = display->getId();
1052 LOG_ALWAYS_FATAL_IF(!displayId);
1053 getHwComposer().setActiveColorMode(*displayId, mode, renderIntent);
1054
Dominik Laskowski34157762018-10-31 13:07:19 -07001055 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), display=%s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001056 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
Dominik Laskowski34157762018-10-31 13:07:19 -07001057 renderIntent, to_string(*displayId).c_str());
Michael Wright28f24d02016-07-12 13:30:53 -07001058}
1059
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001060status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001061 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001062 Vector<ColorMode> modes;
1063 getDisplayColorModes(displayToken, &modes);
1064 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1065 if (mode < ColorMode::NATIVE || !exists) {
1066 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1067 decodeColorMode(mode).c_str(), mode, displayToken.get());
1068 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001069 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001070 const auto display = getDisplayDevice(displayToken);
1071 if (!display) {
1072 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1073 decodeColorMode(mode).c_str(), mode, displayToken.get());
1074 } else if (display->isVirtual()) {
1075 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1076 decodeColorMode(mode).c_str(), mode);
1077 } else {
1078 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1079 RenderIntent::COLORIMETRIC);
1080 }
1081 }));
1082
Michael Wright28f24d02016-07-12 13:30:53 -07001083 return NO_ERROR;
1084}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001085
Svetoslavd85084b2014-03-20 10:28:31 -07001086status_t SurfaceFlinger::clearAnimationFrameStats() {
1087 Mutex::Autolock _l(mStateLock);
1088 mAnimFrameTracker.clearStats();
1089 return NO_ERROR;
1090}
1091
1092status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1093 Mutex::Autolock _l(mStateLock);
1094 mAnimFrameTracker.getStats(outStats);
1095 return NO_ERROR;
1096}
1097
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001098status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1099 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001100 Mutex::Autolock _l(mStateLock);
1101
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001102 const auto display = getDisplayDeviceLocked(displayToken);
1103 if (!display) {
1104 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001105 return BAD_VALUE;
1106 }
1107
Peiyong Linfb069302018-04-25 14:34:31 -07001108 // At this point the DisplayDeivce should already be set up,
1109 // meaning the luminance information is already queried from
1110 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001111 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001112 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1113 capabilities.getDesiredMaxLuminance(),
1114 capabilities.getDesiredMaxAverageLuminance(),
1115 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001116
1117 return NO_ERROR;
1118}
1119
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001120status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1121 ui::PixelFormat* outFormat,
1122 ui::Dataspace* outDataspace,
1123 uint8_t* outComponentMask) const {
1124 if (!outFormat || !outDataspace || !outComponentMask) {
1125 return BAD_VALUE;
1126 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001127 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001128 if (!display || !display->getId()) {
1129 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1130 return BAD_VALUE;
1131 }
1132 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1133 outDataspace, outComponentMask);
1134}
1135
Kevin DuBois74e53772018-11-19 10:52:38 -08001136status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1137 bool enable, uint8_t componentMask,
1138 uint64_t maxFrames) const {
1139 const auto display = getDisplayDevice(displayToken);
1140 if (!display || !display->getId()) {
1141 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1142 return BAD_VALUE;
1143 }
1144
1145 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1146 componentMask, maxFrames);
1147}
1148
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001149status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001150 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001151 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001152
Chia-I Wu90f669f2017-10-05 14:24:41 -07001153 if (mInjectVSyncs == enable) {
1154 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001155 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001156
Ana Krulec98b5b242018-08-10 15:03:23 -07001157 // TODO(akrulec): Part of the Injector should be refactored, so that it
1158 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001159 if (enable) {
1160 ALOGV("VSync Injections enabled");
1161 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001162 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001163 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001164 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001165 impl::EventThread::InterceptVSyncsCallback(),
1166 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001167 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001168 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001169 } else {
1170 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001171 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001172 }
1173
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001174 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001175 }));
1176
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001177 return NO_ERROR;
1178}
1179
1180status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001181 Mutex::Autolock _l(mStateLock);
1182
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001183 if (!mInjectVSyncs) {
1184 ALOGE("VSync Injections not enabled");
1185 return BAD_VALUE;
1186 }
1187 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1188 ALOGV("Injecting VSync inside SurfaceFlinger");
1189 mVSyncInjector->onInjectSyncEvent(when);
1190 }
1191 return NO_ERROR;
1192}
1193
Lloyd Pique755e3192018-01-31 16:46:15 -08001194status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1195 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001196 // Try to acquire a lock for 1s, fail gracefully
1197 const status_t err = mStateLock.timedLock(s2ns(1));
1198 const bool locked = (err == NO_ERROR);
1199 if (!locked) {
1200 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1201 return TIMED_OUT;
1202 }
1203
1204 outLayers->clear();
1205 mCurrentState.traverseInZOrder([&](Layer* layer) {
1206 outLayers->push_back(layer->getLayerDebugInfo());
1207 });
1208
1209 mStateLock.unlock();
1210 return NO_ERROR;
1211}
1212
Peiyong Linc6780972018-10-28 15:24:08 -07001213status_t SurfaceFlinger::getCompositionPreference(
1214 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1215 Dataspace* outWideColorGamutDataspace,
1216 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001217 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001218 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001219 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001220 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001221 return NO_ERROR;
1222}
1223
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001224// ----------------------------------------------------------------------------
1225
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001226sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1227 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001228 if (mUseScheduler) {
1229 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1230 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1231 } else {
1232 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1233 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001234 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001235 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1236 return mSFEventThread->createEventConnection();
1237 } else {
1238 return mEventThread->createEventConnection();
1239 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001240 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001241}
1242
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001243// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001244
1245void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001246 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001247}
1248
1249void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001250 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001251}
1252
1253void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001254 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001255}
1256
1257void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001258 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001259 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001260}
1261
1262status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001263 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001264 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001265}
1266
1267status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001268 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001269 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001270 if (res == NO_ERROR) {
1271 msg->wait();
1272 }
1273 return res;
1274}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001275
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001276void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001277 do {
1278 waitForEvent();
1279 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001280}
1281
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001282void SurfaceFlinger::enableHardwareVsync() {
1283 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001284 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001285 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001286 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001287 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001288 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001289}
1290
Jesse Hall948fe0c2013-10-14 12:56:09 -07001291void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001292 Mutex::Autolock _l(mHWVsyncLock);
1293
Jesse Hall948fe0c2013-10-14 12:56:09 -07001294 if (makeAvailable) {
1295 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001296 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1297 if (mUseScheduler) {
1298 mScheduler->makeHWSyncAvailable(true);
1299 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001300 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001301 // Hardware vsync is not currently available, so abort the resync
1302 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001303 return;
1304 }
1305
Dominik Laskowski075d3172018-05-24 15:50:06 -07001306 const auto displayId = getInternalDisplayId();
1307 if (!displayId || !getHwComposer().isConnected(*displayId)) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001308 return;
1309 }
1310
Dominik Laskowski075d3172018-05-24 15:50:06 -07001311 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001312 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001313
Ana Krulece588e312018-09-18 12:32:24 -07001314 if (mUseScheduler) {
1315 mScheduler->setVsyncPeriod(period);
1316 } else {
1317 mPrimaryDispSync->reset();
1318 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001319
Ana Krulece588e312018-09-18 12:32:24 -07001320 if (!mPrimaryHWVsyncEnabled) {
1321 mPrimaryDispSync->beginResync();
1322 mEventControlThread->setVsyncEnabled(true);
1323 mPrimaryHWVsyncEnabled = true;
1324 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001325 }
1326}
1327
Jesse Hall948fe0c2013-10-14 12:56:09 -07001328void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001329 Mutex::Autolock _l(mHWVsyncLock);
1330 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001331 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001332 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001333 mPrimaryHWVsyncEnabled = false;
1334 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001335 if (makeUnavailable) {
1336 mHWVsyncAvailable = false;
1337 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001338}
1339
Tim Murray4a4e4a22016-04-19 16:29:23 +00001340void SurfaceFlinger::resyncWithRateLimit() {
1341 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001342
1343 // No explicit locking is needed here since EventThread holds a lock while calling this method
1344 static nsecs_t sLastResyncAttempted = 0;
1345 const nsecs_t now = systemTime();
1346 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001347 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001348 }
Dan Stoza57164302017-05-08 14:03:54 -07001349 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001350}
1351
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001352void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1353 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001354 ATRACE_NAME("SF onVsync");
1355
Steven Thomas3cfac282017-02-06 12:29:30 -08001356 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001357 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001358 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001359 return;
1360 }
1361
Dominik Laskowski075d3172018-05-24 15:50:06 -07001362 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001363 return;
1364 }
1365
Dominik Laskowski075d3172018-05-24 15:50:06 -07001366 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001367 // For now, we don't do anything with external display vsyncs.
1368 return;
1369 }
1370
Ana Krulece588e312018-09-18 12:32:24 -07001371 if (mUseScheduler) {
1372 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001373 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001374 bool needsHwVsync = false;
1375 { // Scope for the lock
1376 Mutex::Autolock _l(mHWVsyncLock);
1377 if (mPrimaryHWVsyncEnabled) {
1378 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1379 }
1380 }
1381
1382 if (needsHwVsync) {
1383 enableHardwareVsync();
1384 } else {
1385 disableHardwareVsync(false);
1386 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001387 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001388}
1389
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001390void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001391 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1392 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001393}
1394
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001395void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001396 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001397 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001398 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001399
Lloyd Piqueba04e622017-12-14 17:11:26 -08001400 // Ignore events that do not have the right sequenceId.
1401 if (sequenceId != getBE().mComposerSequenceId) {
1402 return;
1403 }
1404
Steven Thomasb02664d2017-07-26 18:48:28 -07001405 // Only lock if we're not on the main thread. This function is normally
1406 // called on a hwbinder thread, but for the primary display it's called on
1407 // the main thread with the state lock already held, so don't attempt to
1408 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001409 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001410
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001411 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001412
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001413 if (std::this_thread::get_id() == mMainThreadId) {
1414 // Process all pending hot plug events immediately if we are on the main thread.
1415 processDisplayHotplugEventsLocked();
1416 }
1417
Lloyd Piqueba04e622017-12-14 17:11:26 -08001418 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001419}
1420
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001421void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001422 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001423 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001424 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001425 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001426 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001427}
1428
Dominik Laskowski075d3172018-05-24 15:50:06 -07001429void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001430 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001431 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001432 if (const auto displayId = getInternalDisplayId()) {
1433 getHwComposer().setVsyncEnabled(*displayId,
1434 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1435 }
Mathias Agopian86303202012-07-24 22:46:10 -07001436}
1437
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001438// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001439void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001440 if (mUseScheduler) {
1441 mScheduler->disableHardwareVsync(true);
1442 } else {
1443 disableHardwareVsync(true);
1444 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001445 // Clear the drawing state so that the logic inside of
1446 // handleTransactionLocked will fire. It will determine the delta between
1447 // mCurrentState and mDrawingState and re-apply all changes when we make the
1448 // transition.
1449 mDrawingState.displays.clear();
1450 mDisplays.clear();
1451}
1452
Steven Thomas050b2c82017-03-06 11:45:16 -08001453void SurfaceFlinger::updateVrFlinger() {
1454 if (!mVrFlinger)
1455 return;
1456 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001457 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001458 return;
1459 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001460
David Sodman105b7dc2017-11-04 20:28:14 -07001461 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001462 ALOGE("Vr flinger is only supported for remote hardware composer"
1463 " service connections. Ignoring request to transition to vr"
1464 " flinger.");
1465 mVrFlingerRequestsDisplay = false;
1466 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001467 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001468
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001469 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001470
Steven Thomas0123ac62018-07-12 11:32:34 -07001471 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001472 LOG_ALWAYS_FATAL_IF(!display);
1473 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001474 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1475 // called below. Clear the reference now so we don't accidentally use it
1476 // later.
1477 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001478
Steven Thomasb02664d2017-07-26 18:48:28 -07001479 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001480 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001481 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001482
Steven Thomasb02664d2017-07-26 18:48:28 -07001483 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001484 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Pique90c115d2018-09-18 21:39:42 -07001485 getBE().mHwc = getFactory().createHWComposer(
1486 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -07001487 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001488
David Sodman105b7dc2017-11-04 20:28:14 -07001489 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1490 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001491
1492 if (vrFlingerRequestsDisplay) {
1493 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001494 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001495
1496 mVisibleRegionsDirty = true;
1497 invalidateHwcGeometry();
1498
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001499 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001500 display = getDefaultDisplayDeviceLocked();
1501 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001502 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001503
Steven Thomasb02664d2017-07-26 18:48:28 -07001504 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski075d3172018-05-24 15:50:06 -07001505 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001506 const nsecs_t period = activeConfig->getVsyncPeriod();
1507 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001508
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001509 // The present fences returned from vr_hwc are not an accurate
1510 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001511 if (mUseScheduler) {
1512 mScheduler->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() || !hasSyncFramework);
1513 } else {
1514 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1515 !hasSyncFramework);
1516 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001517
Steven Thomasb02664d2017-07-26 18:48:28 -07001518 // Use phase of 0 since phase is not known.
1519 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001520 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1521 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001522
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001523 resyncToHardwareVsync(false);
1524
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001525 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001526 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001527}
1528
Mathias Agopian4fec8732012-06-29 14:12:52 -07001529void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001530 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001531 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001532 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001533 if (mUseScheduler) {
1534 // This call is made each time SF wakes up and creates a new frame.
1535 mScheduler->incrementFrameCounter();
1536 }
Dan Stoza50182882016-07-08 12:02:20 -07001537 bool frameMissed = !mHadClientComposition &&
1538 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001539 (mPreviousPresentFence->getSignalTime() ==
1540 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001541 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001542 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001543 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001544 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001545 if (mPropagateBackpressure) {
1546 signalLayerUpdate();
1547 break;
1548 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001549 }
Dan Stoza50182882016-07-08 12:02:20 -07001550
Steven Thomas050b2c82017-03-06 11:45:16 -08001551 // Now that we're going to make it to the handleMessageTransaction()
1552 // call below it's safe to call updateVrFlinger(), which will
1553 // potentially trigger a display handoff.
1554 updateVrFlinger();
1555
Dan Stoza6b9454d2014-11-07 16:00:59 -08001556 bool refreshNeeded = handleMessageTransaction();
1557 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001558 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001559 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001560 // Signal a refresh if a transaction modified the window state,
1561 // a new buffer was latched, or if HWC has requested a full
1562 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001563 signalRefresh();
1564 }
1565 break;
1566 }
1567 case MessageQueue::REFRESH: {
1568 handleMessageRefresh();
1569 break;
1570 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001571 }
1572}
1573
Dan Stoza6b9454d2014-11-07 16:00:59 -08001574bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001575 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001576 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001577 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001578 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001579 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001580 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001581}
1582
Mathias Agopian4fec8732012-06-29 14:12:52 -07001583void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001584 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001585
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001586 mRefreshPending = false;
1587
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001588 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001589 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001590 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001591 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001592 for (const auto& [token, display] : mDisplays) {
1593 beginFrame(display);
1594 prepareFrame(display);
1595 doDebugFlashRegions(display, repaintEverything);
1596 doComposition(display, repaintEverything);
1597 }
1598
Adrian Roos1e1a1282017-11-01 19:05:31 +01001599 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001600 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001601
1602 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001603 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001604
Dan Stozabfbffeb2016-07-21 14:49:33 -07001605 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001606 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001607 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001608 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001609 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001610
Alec Mouri86770e52018-09-24 22:40:58 +00001611 // Setup RenderEngine sync fences if native sync is supported.
1612 if (getBE().mRenderEngine->useNativeFenceSync()) {
1613 if (mHadClientComposition) {
1614 base::unique_fd flushFence(getRenderEngine().flush());
1615 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1616 getBE().flushFence = new Fence(std::move(flushFence));
1617 } else {
1618 // Cleanup for hygiene.
1619 getBE().flushFence = Fence::NO_FENCE;
1620 }
1621 }
1622
Jorim Jaggi90535212018-05-23 23:44:06 +02001623 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001624
David Sodman7e4ae112018-02-09 15:02:28 -08001625 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001626 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001627 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001628 compositionInfo.hwc.hwcLayer = nullptr;
1629 }
David Sodmanba340492018-08-05 21:51:33 -07001630 }
David Sodman7e4ae112018-02-09 15:02:28 -08001631
1632 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001633}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001634
David Sodmanfa9b2af2017-12-24 13:28:59 -08001635
1636bool SurfaceFlinger::handleMessageInvalidate() {
1637 ATRACE_CALL();
1638 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001639}
1640
David Sodman79bba0e2018-08-05 18:07:49 -07001641void SurfaceFlinger::calculateWorkingSet() {
1642 ATRACE_CALL();
1643 ALOGV(__FUNCTION__);
1644
David Sodman79bba0e2018-08-05 18:07:49 -07001645 // build the h/w work list
1646 if (CC_UNLIKELY(mGeometryInvalid)) {
1647 mGeometryInvalid = false;
1648 for (const auto& [token, display] : mDisplays) {
1649 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001650 if (!displayId) {
1651 continue;
1652 }
David Sodman79bba0e2018-08-05 18:07:49 -07001653
Dominik Laskowski075d3172018-05-24 15:50:06 -07001654 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
1655 for (size_t i = 0; i < currentLayers.size(); i++) {
1656 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001657
Dominik Laskowski075d3172018-05-24 15:50:06 -07001658 if (!layer->hasHwcLayer(*displayId)) {
1659 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1660 layer->forceClientComposition(*displayId);
1661 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001662 }
1663 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001664
1665 layer->setGeometry(display, i);
1666 if (mDebugDisableHWC || mDebugRegion) {
1667 layer->forceClientComposition(*displayId);
1668 }
David Sodman79bba0e2018-08-05 18:07:49 -07001669 }
1670 }
1671 }
1672
1673 // Set the per-frame data
1674 for (const auto& [token, display] : mDisplays) {
1675 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001676 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001677 continue;
1678 }
1679
1680 if (mDrawingState.colorMatrixChanged) {
1681 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001682 status_t result =
1683 getHwComposer().setColorTransform(*displayId, mDrawingState.colorMatrix);
Dominik Laskowski34157762018-10-31 13:07:19 -07001684 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %s: %d",
1685 to_string(*displayId).c_str(), result);
David Sodman79bba0e2018-08-05 18:07:49 -07001686 }
1687 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1688 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001689 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001690 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1691 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1692 !display->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001693 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001694 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1695 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1696 !display->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001697 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001698 }
1699
Peiyong Lind3788632018-09-18 16:01:31 -07001700 // TODO(b/111562338) remove when composer 2.3 is shipped.
1701 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001702 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001703 }
1704
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001705 if (layer->getRoundedCornerState().radius > 0.0f) {
1706 layer->forceClientComposition(*displayId);
1707 }
1708
Dominik Laskowski075d3172018-05-24 15:50:06 -07001709 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001710 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001711 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001712 continue;
1713 }
1714
Dominik Laskowski075d3172018-05-24 15:50:06 -07001715 layer->setPerFrameData(*displayId, display->getTransform(), display->getViewport(),
1716 display->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001717 }
1718
Peiyong Lin13effd12018-07-24 17:01:47 -07001719 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001720 ColorMode colorMode;
1721 Dataspace dataSpace;
1722 RenderIntent renderIntent;
1723 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1724 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1725 }
1726 }
1727
1728 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001729
1730 for (const auto& [token, display] : mDisplays) {
1731 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001732 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001733 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001734
1735 if (displayId) {
1736 if (!layer->setHwcLayer(*displayId)) {
1737 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1738 }
1739 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001740 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001741
Dominik Laskowski05275f12018-11-01 15:03:24 -07001742 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001743 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1744 }
1745 }
David Sodman79bba0e2018-08-05 18:07:49 -07001746}
1747
David Sodmanfa9b2af2017-12-24 13:28:59 -08001748void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001749{
1750 // is debugging enabled
1751 if (CC_LIKELY(!mDebugRegion))
1752 return;
1753
David Sodmanfa9b2af2017-12-24 13:28:59 -08001754 if (display->isPoweredOn()) {
1755 // transform the dirty region into this screen's coordinate space
1756 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1757 if (!dirtyRegion.isEmpty()) {
1758 // redraw the whole screen
1759 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001760
David Sodmanfa9b2af2017-12-24 13:28:59 -08001761 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001762 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001763 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001764
Alec Mouri0a9c7b82018-11-16 13:05:25 -08001765 display->queueBuffer(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001766 }
1767 }
1768
David Sodmanfa9b2af2017-12-24 13:28:59 -08001769 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001770
1771 if (mDebugRegion > 1) {
1772 usleep(mDebugRegion * 1000);
1773 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001774
Dominik Laskowski05275f12018-11-01 15:03:24 -07001775 prepareFrame(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001776}
1777
Adrian Roos1e1a1282017-11-01 19:05:31 +01001778void SurfaceFlinger::doTracing(const char* where) {
1779 ATRACE_CALL();
1780 ATRACE_NAME(where);
1781 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001782 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001783 }
1784}
1785
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001786void SurfaceFlinger::logLayerStats() {
1787 ATRACE_CALL();
1788 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001789 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001790 if (display->isPrimary()) {
1791 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001792 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001793 }
1794 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001795
1796 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001797 }
1798}
1799
David Sodman2b406362017-12-15 13:33:47 -08001800void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001801{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001802 ATRACE_CALL();
1803 ALOGV("preComposition");
1804
David Sodman2b406362017-12-15 13:33:47 -08001805 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1806
Mathias Agopiancd60f992012-08-16 16:28:27 -07001807 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001808 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001809 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001810 needExtraInvalidate = true;
1811 }
Robert Carr2047fae2016-11-28 14:09:09 -08001812 });
1813
Mathias Agopiancd60f992012-08-16 16:28:27 -07001814 if (needExtraInvalidate) {
1815 signalLayerUpdate();
1816 }
1817}
1818
Ana Krulece588e312018-09-18 12:32:24 -07001819void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1820 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001821 // Update queue of past composite+present times and determine the
1822 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001823 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001824 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001825 while (!getBE().mCompositePresentTimes.empty()) {
1826 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001827 // Cached values should have been updated before calling this method,
1828 // which helps avoid duplicate syscalls.
1829 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1830 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1831 break;
1832 }
1833 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001834 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001835 }
1836
1837 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001838 while (getBE().mCompositePresentTimes.size() > 16) {
1839 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001840 }
1841
Ana Krulece588e312018-09-18 12:32:24 -07001842 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001843}
1844
Ana Krulece588e312018-09-18 12:32:24 -07001845void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1846 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001847 // Integer division and modulo round toward 0 not -inf, so we need to
1848 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001849 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1850 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1851 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001852
Brian Andersond0010582017-03-07 13:20:31 -08001853 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1854 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001855 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001856 }
1857
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001858 // Snap the latency to a value that removes scheduling jitter from the
1859 // composition and present times, which often have >1ms of jitter.
1860 // Reducing jitter is important if an app attempts to extrapolate
1861 // something (such as user input) to an accurate diasplay time.
1862 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1863 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001864 nsecs_t bias = stats.vsyncPeriod / 2;
1865 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1866 nsecs_t snappedCompositeToPresentLatency =
1867 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001868
David Sodman99974d22017-11-28 12:04:33 -08001869 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001870 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1871 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001872 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001873}
1874
David Sodman2b406362017-12-15 13:33:47 -08001875void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001876{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001877 ATRACE_CALL();
1878 ALOGV("postComposition");
1879
Brian Anderson3546a3f2016-07-14 11:51:14 -07001880 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001881 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001882 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001883 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001884 }
1885
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001886 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001887 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001888
David Sodman73beded2017-11-15 11:56:06 -08001889 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001890 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001891 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001892 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001893 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001894 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001895 } else {
1896 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1897 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001898
David Sodman73beded2017-11-15 11:56:06 -08001899 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001900 mPreviousPresentFence =
Dominik Laskowski075d3172018-05-24 15:50:06 -07001901 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001902 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001903 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001904
Ana Krulece588e312018-09-18 12:32:24 -07001905 DisplayStatInfo stats;
1906 if (mUseScheduler) {
1907 mScheduler->getDisplayStatInfo(&stats);
1908 } else {
1909 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1910 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
1911 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001912
David Sodman2b406362017-12-15 13:33:47 -08001913 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001914 // when we started doing work for this frame, but that should be okay
1915 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07001916 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001917 CompositorTiming compositorTiming;
1918 {
David Sodman99974d22017-11-28 12:04:33 -08001919 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1920 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001921 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001922
Robert Carr2047fae2016-11-28 14:09:09 -08001923 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001924 bool frameLatched = layer->onPostComposition(display->getId(), glCompositionDoneFenceTime,
1925 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001926 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001927 recordBufferingStats(layer->getName().string(),
1928 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001929 }
Robert Carr2047fae2016-11-28 14:09:09 -08001930 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001931
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001932 if (presentFenceTime->isValid()) {
Ana Krulece588e312018-09-18 12:32:24 -07001933 if (mUseScheduler) {
1934 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001935 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001936 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
1937 enableHardwareVsync();
1938 } else {
1939 disableHardwareVsync(false);
1940 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001941 }
1942 }
1943
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001944 if (!hasSyncFramework) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001945 if (display && getHwComposer().isConnected(*display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07001946 if (mUseScheduler) {
1947 mScheduler->enableHardwareVsync();
1948 } else {
1949 enableHardwareVsync();
1950 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001951 }
1952 }
1953
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001954 if (mAnimCompositionPending) {
1955 mAnimCompositionPending = false;
1956
Brian Anderson4e606e32017-03-16 15:34:57 -07001957 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001958 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001959 std::move(presentFenceTime));
Dominik Laskowski075d3172018-05-24 15:50:06 -07001960 } else if (display && getHwComposer().isConnected(*display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001961 // The HWC doesn't support present fences, so use the refresh
1962 // timestamp instead.
Dominik Laskowski075d3172018-05-24 15:50:06 -07001963 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001964 mAnimFrameTracker.setActualPresentTime(presentTime);
1965 }
1966 mAnimFrameTracker.advanceFrame();
1967 }
Dan Stozab90cf072015-03-05 11:05:59 -08001968
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001969 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001970 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001971 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001972 }
1973
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001974 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001975
Dominik Laskowski075d3172018-05-24 15:50:06 -07001976 if (display && getHwComposer().isConnected(*display->getId()) && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08001977 return;
1978 }
1979
1980 nsecs_t currentTime = systemTime();
1981 if (mHasPoweredOff) {
1982 mHasPoweredOff = false;
1983 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001984 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001985 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001986 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1987 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001988 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001989 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001990 }
David Sodman4a36e932017-11-07 14:29:47 -08001991 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001992 }
David Sodman4a36e932017-11-07 14:29:47 -08001993 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001994
1995 {
1996 std::lock_guard lock(mTexturePoolMutex);
1997 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1998 if (refillCount > 0) {
1999 const size_t offset = mTexturePool.size();
2000 mTexturePool.resize(mTexturePoolSize);
2001 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2002 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2003 }
2004 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002005
Marissa Wallfda30bb2018-10-12 11:34:28 -07002006 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002007 mTransactionCompletedThread.sendCallbacks();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002008}
2009
2010void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002011 ATRACE_CALL();
2012 ALOGV("rebuildLayerStacks");
2013
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002014 // We need to clear these out now as these may be holding on to a
2015 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2016 // also holds a reference. When the set of visible layers is recomputed,
2017 // some layers may be destroyed if the only thing keeping them alive was
2018 // that list of visible layers associated with each display. The layer
2019 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2020 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2021 for (const auto& [token, display] : mDisplays) {
2022 getBE().mCompositionInfo[token].clear();
2023 }
2024
Mathias Agopiancd60f992012-08-16 16:28:27 -07002025 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002026 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002027 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002028 mVisibleRegionsDirty = false;
2029 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002030
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002031 for (const auto& pair : mDisplays) {
2032 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07002033 Region opaqueRegion;
2034 Region dirtyRegion;
2035 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002036 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07002037 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002038 const Rect bounds = display->getBounds();
2039 if (display->isPoweredOn()) {
2040 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002041
Jeff Sharkey76488112017-02-27 14:15:18 -07002042 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002043 bool hwcLayerDestroyed = false;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002044 const auto displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002045 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002046 Region drawRegion(tr.transform(
2047 layer->visibleNonTransparentRegion));
2048 drawRegion.andSelf(bounds);
2049 if (!drawRegion.isEmpty()) {
2050 layersSortedByZ.add(layer);
2051 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002052 // Clear out the HWC layer if this layer was
2053 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002054 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002055 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002056 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002057 // WM changes display->layerStack upon sleep/awake.
2058 // Here we make sure we delete the HWC layers even if
2059 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002060 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002061 }
2062
2063 // If a layer is not going to get a release fence because
2064 // it is invisible, but it is also going to release its
2065 // old buffer, add it to the list of layers needing
2066 // fences.
2067 if (hwcLayerDestroyed) {
2068 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2069 mLayersWithQueuedFrames.cend(), layer);
2070 if (found != mLayersWithQueuedFrames.cend()) {
2071 layersNeedingFences.add(layer);
2072 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002073 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002074 });
2075 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002076 display->setVisibleLayersSortedByZ(layersSortedByZ);
2077 display->setLayersNeedingFences(layersNeedingFences);
2078 display->undefinedRegion.set(bounds);
2079 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2080 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002081 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002082 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002083}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002084
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002085// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002086// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002087// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002088// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002089// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002090// The returned HDR data space is one of
2091// - Dataspace::UNKNOWN
2092// - Dataspace::BT2020_HLG
2093// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002094Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2095 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07002096 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002097 *outHdrDataSpace = Dataspace::UNKNOWN;
2098
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002099 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002100 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002101 case Dataspace::V0_SCRGB:
2102 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002103 case Dataspace::BT2020:
2104 case Dataspace::BT2020_ITU:
2105 case Dataspace::BT2020_LINEAR:
2106 case Dataspace::DISPLAY_BT2020:
2107 bestDataSpace = Dataspace::DISPLAY_BT2020;
2108 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002109 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002110 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002111 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002112 case Dataspace::BT2020_PQ:
2113 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002114 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002115 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002116 case Dataspace::BT2020_HLG:
2117 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002118 // When there's mixed PQ content and HLG content, we set the HDR
2119 // data space to be BT2020_PQ and convert HLG to PQ.
2120 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2121 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002122 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002123 break;
2124 default:
2125 break;
2126 }
Romain Guy54f154a2017-10-24 21:40:32 +01002127 }
2128
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002129 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002130}
2131
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002132// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002133void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2134 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002135 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2136 *outMode = ColorMode::NATIVE;
2137 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002138 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002139 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002140 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002141
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002142 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002143 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002144
Peiyong Lindfde5112018-06-05 10:58:41 -07002145 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002146 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002147 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002148 if (isHdr) {
2149 bestDataSpace = hdrDataSpace;
2150 }
2151
Chia-I Wu0d711262018-05-21 15:19:35 -07002152 RenderIntent intent;
2153 switch (mDisplayColorSetting) {
2154 case DisplayColorSetting::MANAGED:
2155 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002156 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002157 break;
2158 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002159 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002160 break;
2161 default: // vendor display color setting
2162 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2163 break;
2164 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002165
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002166 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002167}
2168
David Sodmanfa9b2af2017-12-24 13:28:59 -08002169void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002170{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002171 bool dirty = !display->getDirtyRegion(false).isEmpty();
2172 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2173 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002174
David Sodmanfa9b2af2017-12-24 13:28:59 -08002175 // If nothing has changed (!dirty), don't recompose.
2176 // If something changed, but we don't currently have any visible layers,
2177 // and didn't when we last did a composition, then skip it this time.
2178 // The second rule does two things:
2179 // - When all layers are removed from a display, we'll emit one black
2180 // frame, then nothing more until we get new layers.
2181 // - When a display is created with a private layer stack, we won't
2182 // emit any black frames until a layer is added to the layer stack.
2183 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002184
Dominik Laskowski075d3172018-05-24 15:50:06 -07002185 const char flagPrefix[] = {'-', '+'};
2186 static_cast<void>(flagPrefix);
2187 ALOGV_IF(display->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2188 __FUNCTION__, mustRecompose ? "doing" : "skipping", display->getDebugName().c_str(),
2189 flagPrefix[dirty], flagPrefix[empty], flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002190
David Sodmanfa9b2af2017-12-24 13:28:59 -08002191 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002192
David Sodmanfa9b2af2017-12-24 13:28:59 -08002193 if (mustRecompose) {
2194 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002195 }
2196}
2197
David Sodmanfa9b2af2017-12-24 13:28:59 -08002198void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002199{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002200 if (!display->isPoweredOn()) {
2201 return;
David Sodman2b406362017-12-15 13:33:47 -08002202 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002203
Dominik Laskowski05275f12018-11-01 15:03:24 -07002204 status_t result = display->prepareFrame(getHwComposer(),
2205 getBE().mCompositionInfo[display->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002206 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
2207 display->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002208}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002209
David Sodmanfa9b2af2017-12-24 13:28:59 -08002210void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002211 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002212 ALOGV("doComposition");
2213
David Sodmanfa9b2af2017-12-24 13:28:59 -08002214 if (display->isPoweredOn()) {
2215 // transform the dirty region into this screen's coordinate space
2216 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002217
David Sodmanfa9b2af2017-12-24 13:28:59 -08002218 // repaint the framebuffer (if needed)
2219 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002220
David Sodmanfa9b2af2017-12-24 13:28:59 -08002221 display->dirtyRegion.clear();
2222 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002223 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002224 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002225}
2226
David Sodmanfa9b2af2017-12-24 13:28:59 -08002227void SurfaceFlinger::postFrame()
2228{
2229 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002230 const auto display = getDefaultDisplayDeviceLocked();
2231 if (display && getHwComposer().isConnected(*display->getId())) {
2232 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002233 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2234 logFrameStats();
2235 }
2236 }
2237}
2238
2239void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002240{
Mathias Agopian841cde52012-03-01 15:44:37 -08002241 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002242 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002243
David Sodmanfa9b2af2017-12-24 13:28:59 -08002244 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002245
David Sodmanfa9b2af2017-12-24 13:28:59 -08002246 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002247 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002248 if (displayId) {
2249 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002250 }
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002251 display->onPresentDisplayCompleted();
David Sodman15094112018-10-11 09:39:37 -07002252 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002253 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002254
Chia-I Wu7b549592017-11-15 09:14:57 -08002255 // The layer buffer from the previous frame (if any) is released
2256 // by HWC only when the release fence from this frame (if any) is
2257 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002258 if (displayId && layer->hasHwcLayer(*displayId)) {
2259 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2260 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002261 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002262
2263 // If the layer was client composited in the previous frame, we
2264 // need to merge with the previous client target acquire fence.
2265 // Since we do not track that, always merge with the current
2266 // client target acquire fence when it is available, even though
2267 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002268 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002269 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002270 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002271 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002272
David Sodman15094112018-10-11 09:39:37 -07002273 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002274 }
Chia-I Wu83806892017-11-16 10:50:20 -08002275
2276 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002277 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002278 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002279 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002280 sp<Fence> presentFence =
2281 displayId ? getBE().mHwc->getPresentFence(*displayId) : Fence::NO_FENCE;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002282 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002283 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002284 }
2285 }
2286
Dominik Laskowski075d3172018-05-24 15:50:06 -07002287 if (displayId) {
2288 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002289 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002290 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002291}
2292
Mathias Agopian87baae12012-07-31 12:38:26 -07002293void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002294{
Mathias Agopian841cde52012-03-01 15:44:37 -08002295 ATRACE_CALL();
2296
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002297 // here we keep a copy of the drawing state (that is the state that's
2298 // going to be overwritten by handleTransactionLocked()) outside of
2299 // mStateLock so that the side-effects of the State assignment
2300 // don't happen with mStateLock held (which can cause deadlocks).
2301 State drawingState(mDrawingState);
2302
Mathias Agopianca4d3602011-05-19 15:38:14 -07002303 Mutex::Autolock _l(mStateLock);
2304 const nsecs_t now = systemTime();
2305 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002306
Mathias Agopianca4d3602011-05-19 15:38:14 -07002307 // Here we're guaranteed that some transaction flags are set
2308 // so we can call handleTransactionLocked() unconditionally.
2309 // We call getTransactionFlags(), which will also clear the flags,
2310 // with mStateLock held to guarantee that mCurrentState won't change
2311 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002312
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002313 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002314 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002315 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002316
Mathias Agopianca4d3602011-05-19 15:38:14 -07002317 mLastTransactionTime = systemTime() - now;
2318 mDebugInTransaction = 0;
2319 invalidateHwcGeometry();
2320 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002321}
2322
Lloyd Piqueba04e622017-12-14 17:11:26 -08002323void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2324 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002325 const std::optional<DisplayIdentificationInfo> info =
2326 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002327
Dominik Laskowski075d3172018-05-24 15:50:06 -07002328 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002329 continue;
2330 }
2331
Lloyd Piqueba04e622017-12-14 17:11:26 -08002332 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002333 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002334 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002335 mPhysicalDisplayTokens[info->id] = new BBinder();
2336 DisplayDeviceState state;
2337 state.displayId = info->id;
2338 state.isSecure = true; // All physical displays are currently considered secure.
2339 state.displayName = info->name;
2340 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2341 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002342 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002343 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002344 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002345
Dominik Laskowski075d3172018-05-24 15:50:06 -07002346 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2347 if (index >= 0) {
2348 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2349 mInterceptor->saveDisplayDeletion(state.sequenceId);
2350 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002351 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002352 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002353 }
2354
2355 processDisplayChangesLocked();
2356 }
2357
2358 mPendingHotplugEvents.clear();
2359}
2360
Lloyd Pique99d3da52018-01-22 17:48:03 -08002361sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002362 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
2363 const DisplayDeviceState& state, const sp<DisplaySurface>& dispSurface,
2364 const sp<IGraphicBufferProducer>& producer) {
2365 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
2366 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002367 creationArgs.isSecure = state.isSecure;
2368 creationArgs.displaySurface = dispSurface;
2369 creationArgs.hasWideColorGamut = false;
2370 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002371
Dominik Laskowski075d3172018-05-24 15:50:06 -07002372 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2373 creationArgs.isPrimary = isInternalDisplay;
2374
2375 if (useColorManagement && displayId) {
2376 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002377 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002378 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002379 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002380 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002381
Dominik Laskowski7e045462018-05-30 13:02:02 -07002382 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002383 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002384 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002385 }
tangrobin6753a022018-08-10 10:58:54 +08002386 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002387
Dominik Laskowski075d3172018-05-24 15:50:06 -07002388 if (displayId) {
2389 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002390 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002391 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002392 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002393
Lloyd Pique90c115d2018-09-18 21:39:42 -07002394 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002395 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002396 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002397
Lloyd Pique99d3da52018-01-22 17:48:03 -08002398 // Make sure that composition can never be stalled by a virtual display
2399 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002400 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002401 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002402 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2403 }
2404
Dominik Laskowski075d3172018-05-24 15:50:06 -07002405 creationArgs.displayInstallOrientation =
2406 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002407
Lloyd Pique99d3da52018-01-22 17:48:03 -08002408 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002409 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002410
Lloyd Pique90c115d2018-09-18 21:39:42 -07002411 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002412
2413 if (maxFrameBufferAcquiredBuffers >= 3) {
2414 nativeWindowSurface->preallocateBuffers();
2415 }
2416
2417 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002418 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002419 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002420 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002421 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002422 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002423 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002424 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002425 if (!state.isVirtual()) {
2426 LOG_ALWAYS_FATAL_IF(!displayId);
2427 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002428 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002429
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002430 display->setLayerStack(state.layerStack);
2431 display->setProjection(state.orientation, state.viewport, state.frame);
2432 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002433
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002434 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002435}
2436
Lloyd Pique347200f2017-12-14 17:00:15 -08002437void SurfaceFlinger::processDisplayChangesLocked() {
2438 // here we take advantage of Vector's copy-on-write semantics to
2439 // improve performance by skipping the transaction entirely when
2440 // know that the lists are identical
2441 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2442 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2443 if (!curr.isIdenticalTo(draw)) {
2444 mVisibleRegionsDirty = true;
2445 const size_t cc = curr.size();
2446 size_t dc = draw.size();
2447
2448 // find the displays that were removed
2449 // (ie: in drawing state but not in current state)
2450 // also handle displays that changed
2451 // (ie: displays that are in both lists)
2452 for (size_t i = 0; i < dc;) {
2453 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2454 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002455 // Save display IDs before disconnecting.
2456 const auto internalDisplayId = getInternalDisplayId();
2457 const auto externalDisplayId = getExternalDisplayId();
2458
Lloyd Pique347200f2017-12-14 17:00:15 -08002459 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002460 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2461 display->disconnect(getHwComposer());
2462 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002463 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002464 if (mUseScheduler) {
2465 mScheduler->hotplugReceived(mAppConnectionHandle,
2466 EventThread::DisplayType::Primary, false);
2467 } else {
2468 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2469 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002470 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002471 if (mUseScheduler) {
2472 mScheduler->hotplugReceived(mAppConnectionHandle,
2473 EventThread::DisplayType::External, false);
2474 } else {
2475 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2476 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002477 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002478 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002479 } else {
2480 // this display is in both lists. see if something changed.
2481 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002482 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002483 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2484 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2485 if (state_binder != draw_binder) {
2486 // changing the surface is like destroying and
2487 // recreating the DisplayDevice, so we just remove it
2488 // from the drawing state, so that it get re-added
2489 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002490 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2491 display->disconnect(getHwComposer());
2492 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002493 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002494 mDrawingState.displays.removeItemsAt(i);
2495 dc--;
2496 // at this point we must loop to the next item
2497 continue;
2498 }
2499
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002500 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002501 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002502 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002503 }
2504 if ((state.orientation != draw[i].orientation) ||
2505 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002506 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002507 }
2508 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002509 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002510 }
2511 }
2512 }
2513 ++i;
2514 }
2515
2516 // find displays that were added
2517 // (ie: in current state but not in drawing state)
2518 for (size_t i = 0; i < cc; i++) {
2519 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2520 const DisplayDeviceState& state(curr[i]);
2521
2522 sp<DisplaySurface> dispSurface;
2523 sp<IGraphicBufferProducer> producer;
2524 sp<IGraphicBufferProducer> bqProducer;
2525 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002526 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002527
Dominik Laskowski075d3172018-05-24 15:50:06 -07002528 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002529 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002530 // Virtual displays without a surface are dormant:
2531 // they have external state (layer stack, projection,
2532 // etc.) but no internal state (i.e. a DisplayDevice).
2533 if (state.surface != nullptr) {
2534 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002535 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002536 int width = 0;
2537 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2538 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2539 int height = 0;
2540 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2541 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2542 int intFormat = 0;
2543 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2544 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002545 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002546
Dominik Laskowski075d3172018-05-24 15:50:06 -07002547 displayId =
2548 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002549 }
2550
2551 // TODO: Plumb requested format back up to consumer
2552
2553 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002554 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002555 bqProducer, bqConsumer,
2556 state.displayName);
2557
2558 dispSurface = vds;
2559 producer = vds;
2560 }
2561 } else {
2562 ALOGE_IF(state.surface != nullptr,
2563 "adding a supported display, but rendering "
2564 "surface is provided (%p), ignoring it",
2565 state.surface.get());
2566
Dominik Laskowski075d3172018-05-24 15:50:06 -07002567 displayId = state.displayId;
2568 LOG_ALWAYS_FATAL_IF(!displayId);
2569 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002570 producer = bqProducer;
2571 }
2572
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002573 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002574 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002575 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002576 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002577 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002578 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002579 LOG_ALWAYS_FATAL_IF(!displayId);
2580
2581 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002582 if (mUseScheduler) {
2583 mScheduler->hotplugReceived(mAppConnectionHandle,
2584 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002585 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002586 } else {
2587 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2588 true);
2589 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002590 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002591 if (mUseScheduler) {
2592 mScheduler->hotplugReceived(mAppConnectionHandle,
2593 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002594 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002595 } else {
2596 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2597 true);
2598 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002599 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002600 }
2601 }
2602 }
2603 }
2604 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002605
2606 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002607}
2608
Mathias Agopian87baae12012-07-31 12:38:26 -07002609void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002610{
Dan Stoza7dde5992015-05-22 09:51:44 -07002611 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002612 mCurrentState.traverseInZOrder([](Layer* layer) {
2613 layer->notifyAvailableFrames();
2614 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002615
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002616 /*
2617 * Traversal of the children
2618 * (perform the transaction for each of them if needed)
2619 */
2620
Robert Carr720e5062018-07-30 17:45:14 -07002621 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002622 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002623 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002624 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002625 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002626
2627 const uint32_t flags = layer->doTransaction(0);
2628 if (flags & Layer::eVisibleRegion)
2629 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002630
2631 if (flags & Layer::eInputInfoChanged) {
2632 inputChanged = true;
2633 }
Robert Carr2047fae2016-11-28 14:09:09 -08002634 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002635 }
2636
2637 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002638 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002639 */
2640
Mathias Agopiane57f2922012-08-09 16:29:12 -07002641 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002642 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002643 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002644 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002645
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002646 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002647 // The transform hint might have changed for some layers
2648 // (either because a display has changed, or because a layer
2649 // as changed).
2650 //
2651 // Walk through all the layers in currentLayers,
2652 // and update their transform hint.
2653 //
2654 // If a layer is visible only on a single display, then that
2655 // display is used to calculate the hint, otherwise we use the
2656 // default display.
2657 //
2658 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2659 // the hint is set before we acquire a buffer from the surface texture.
2660 //
2661 // NOTE: layer transactions have taken place already, so we use their
2662 // drawing state. However, SurfaceFlinger's own transaction has not
2663 // happened yet, so we must use the current state layer list
2664 // (soon to become the drawing state list).
2665 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002666 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002667 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002668 bool first = true;
2669 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002670 // NOTE: we rely on the fact that layers are sorted by
2671 // layerStack first (so we don't have to traverse the list
2672 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002673 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002674 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002675 currentlayerStack = layerStack;
2676 // figure out if this layerstack is mirrored
2677 // (more than one display) if so, pick the default display,
2678 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002679 hintDisplay = nullptr;
2680 for (const auto& [token, display] : mDisplays) {
2681 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2682 if (hintDisplay) {
2683 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002684 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002685 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002686 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002687 }
2688 }
2689 }
2690 }
Chet Haase91d25932013-04-11 15:24:55 -07002691
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002692 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002693 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2694 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002695
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002696 // could be null when this layer is using a layerStack
2697 // that is not visible on any display. Also can occur at
2698 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002699 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002700 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002701
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002702 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002703 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002704 if (hintDisplay) {
2705 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002706 }
Robert Carr2047fae2016-11-28 14:09:09 -08002707
2708 first = false;
2709 });
Mathias Agopian84300952012-11-21 16:02:13 -08002710 }
2711
2712
Mathias Agopian3559b072012-08-15 13:46:03 -07002713 /*
2714 * Perform our own transaction if needed
2715 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002716
2717 if (mLayersAdded) {
2718 mLayersAdded = false;
2719 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002720 mVisibleRegionsDirty = true;
2721 }
2722
2723 // some layers might have been removed, so
2724 // we need to update the regions they're exposing.
2725 if (mLayersRemoved) {
2726 mLayersRemoved = false;
2727 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002728 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002729 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002730 // this layer is not visible anymore
2731 // TODO: we could traverse the tree from front to back and
2732 // compute the actual visible region
2733 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002734 Region visibleReg;
2735 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002736 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002737 }
Robert Carr2047fae2016-11-28 14:09:09 -08002738 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002739 }
2740
2741 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002742
Robert Carr720e5062018-07-30 17:45:14 -07002743 if ((inputChanged || mVisibleRegionsDirty) && mInputFlinger) {
2744 updateInputWindows();
2745 }
2746
Riley Andrews03414a12014-07-01 14:22:59 -07002747 updateCursorAsync();
2748}
2749
Robert Carr720e5062018-07-30 17:45:14 -07002750void SurfaceFlinger::updateInputWindows() {
2751 ATRACE_CALL();
2752
2753 Vector<InputWindowInfo> inputHandles;
2754
2755 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2756 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002757 // When calculating the screen bounds we ignore the transparent region since it may
2758 // result in an unwanted offset.
2759 inputHandles.add(layer->fillInputInfo(
2760 layer->computeScreenBounds(false /* reduceTransparentRegion */)));
Robert Carr720e5062018-07-30 17:45:14 -07002761 }
2762 });
2763 mInputFlinger->setInputWindows(inputHandles);
2764}
2765
Riley Andrews03414a12014-07-01 14:22:59 -07002766void SurfaceFlinger::updateCursorAsync()
2767{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002768 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002769 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002770 continue;
2771 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002772
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002773 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2774 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002775 }
2776 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002777}
2778
chaviw61626f22018-11-15 16:26:27 -08002779void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2780 if (layer->hasReadyFrame()) {
2781 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2782 if (layer->shouldPresentNow(expectedPresentTime)) {
2783 bool ignored = false;
2784 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
2785 }
2786 }
2787 layer->releasePendingBuffer(systemTime());
2788}
2789
Mathias Agopian4fec8732012-06-29 14:12:52 -07002790void SurfaceFlinger::commitTransaction()
2791{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002792 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002793 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002794 for (const auto& l : mLayersPendingRemoval) {
2795 recordBufferingStats(l->getName().string(),
2796 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002797
2798 // We need to release the HWC layers when the Layer is removed
2799 // from the current state otherwise the HWC layer just continues
2800 // showing at its last configured state until we eventually
2801 // abandon the buffer queue.
2802 if (l->isRemovedFromCurrentState()) {
Robert Carr3aee9892018-11-07 12:53:41 -08002803 l->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* child) {
chaviw61626f22018-11-15 16:26:27 -08002804 child->destroyHwcLayersForAllDisplays();
2805 latchAndReleaseBuffer(child);
Robert Carr3aee9892018-11-07 12:53:41 -08002806 });
Robert Carr2e102c92018-10-23 12:11:15 -07002807 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002808 }
2809 mLayersPendingRemoval.clear();
2810 }
2811
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002812 // If this transaction is part of a window animation then the next frame
2813 // we composite should be considered an animation as well.
2814 mAnimCompositionPending = mAnimTransactionPending;
2815
Mathias Agopian4fec8732012-06-29 14:12:52 -07002816 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002817 // clear the "changed" flags in current state
2818 mCurrentState.colorMatrixChanged = false;
2819
Robert Carr1f0a16a2016-10-24 16:27:39 -07002820 mDrawingState.traverseInZOrder([](Layer* layer) {
2821 layer->commitChildList();
2822 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002823 mTransactionPending = false;
2824 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002825 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002826}
2827
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002828void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2829 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002830 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002831 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002832
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002833 Region aboveOpaqueLayers;
2834 Region aboveCoveredLayers;
2835 Region dirty;
2836
Mathias Agopian87baae12012-07-31 12:38:26 -07002837 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002838
Robert Carr2047fae2016-11-28 14:09:09 -08002839 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002840 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002841 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002842
Jesse Hall01e29052013-02-19 16:13:35 -08002843 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002844 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002845 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002846 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002847
Mathias Agopianab028732010-03-16 16:41:46 -07002848 /*
2849 * opaqueRegion: area of a surface that is fully opaque.
2850 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002851 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002852
2853 /*
2854 * visibleRegion: area of a surface that is visible on screen
2855 * and not fully transparent. This is essentially the layer's
2856 * footprint minus the opaque regions above it.
2857 * Areas covered by a translucent surface are considered visible.
2858 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002859 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002860
2861 /*
2862 * coveredRegion: area of a surface that is covered by all
2863 * visible regions above it (which includes the translucent areas).
2864 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002865 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002866
Jesse Halla8026d22012-09-25 13:25:04 -07002867 /*
2868 * transparentRegion: area of a surface that is hinted to be completely
2869 * transparent. This is only used to tell when the layer has no visible
2870 * non-transparent regions and can be removed from the layer list. It
2871 * does not affect the visibleRegion of this layer or any layers
2872 * beneath it. The hint may not be correct if apps don't respect the
2873 * SurfaceView restrictions (which, sadly, some don't).
2874 */
2875 Region transparentRegion;
2876
Mathias Agopianab028732010-03-16 16:41:46 -07002877
2878 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002879 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002880 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002881 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07002882
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002883 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002884 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002885 if (!visibleRegion.isEmpty()) {
2886 // Remove the transparent area from the visible region
2887 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002888 if (tr.preserveRects()) {
2889 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002890 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002891 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002892 // transformation too complex, can't do the
2893 // transparent region optimization.
2894 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002895 }
Mathias Agopianab028732010-03-16 16:41:46 -07002896 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002897
Mathias Agopianab028732010-03-16 16:41:46 -07002898 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002899 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002900 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002901 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002902 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002903 // the opaque region is the layer's footprint
2904 opaqueRegion = visibleRegion;
2905 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002906 }
2907 }
2908
Robert Carre5f4f692018-01-12 13:12:28 -08002909 if (visibleRegion.isEmpty()) {
2910 layer->clearVisibilityRegions();
2911 return;
2912 }
2913
Mathias Agopianab028732010-03-16 16:41:46 -07002914 // Clip the covered region to the visible region
2915 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2916
2917 // Update aboveCoveredLayers for next (lower) layer
2918 aboveCoveredLayers.orSelf(visibleRegion);
2919
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002920 // subtract the opaque region covered by the layers above us
2921 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002922
2923 // compute this layer's dirty region
2924 if (layer->contentDirty) {
2925 // we need to invalidate the whole region
2926 dirty = visibleRegion;
2927 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002928 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002929 layer->contentDirty = false;
2930 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002931 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002932 * the exposed region consists of two components:
2933 * 1) what's VISIBLE now and was COVERED before
2934 * 2) what's EXPOSED now less what was EXPOSED before
2935 *
2936 * note that (1) is conservative, we start with the whole
2937 * visible region but only keep what used to be covered by
2938 * something -- which mean it may have been exposed.
2939 *
2940 * (2) handles areas that were not covered by anything but got
2941 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002942 */
Mathias Agopianab028732010-03-16 16:41:46 -07002943 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002944 const Region oldVisibleRegion = layer->visibleRegion;
2945 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002946 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2947 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002948 }
2949 dirty.subtractSelf(aboveOpaqueLayers);
2950
2951 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002952 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002953
Mathias Agopianab028732010-03-16 16:41:46 -07002954 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002955 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002956
Jesse Halla8026d22012-09-25 13:25:04 -07002957 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002958 layer->setVisibleRegion(visibleRegion);
2959 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002960 layer->setVisibleNonTransparentRegion(
2961 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002962 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002963
Mathias Agopian87baae12012-07-31 12:38:26 -07002964 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002965}
2966
Chia-I Wuab0c3192017-08-01 11:29:00 -07002967void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002968 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002969 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2970 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002971 }
2972 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002973}
2974
Dan Stoza6b9454d2014-11-07 16:00:59 -08002975bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002976{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002977 ALOGV("handlePageFlip");
2978
Brian Andersond6927fb2016-07-23 23:37:30 -07002979 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002980
Mathias Agopian4fec8732012-06-29 14:12:52 -07002981 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002982 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002983 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002984
2985 // Store the set of layers that need updates. This set must not change as
2986 // buffers are being latched, as this could result in a deadlock.
2987 // Example: Two producers share the same command stream and:
2988 // 1.) Layer 0 is latched
2989 // 2.) Layer 0 gets a new frame
2990 // 2.) Layer 1 gets a new frame
2991 // 3.) Layer 1 is latched.
2992 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2993 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002994 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002995 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002996 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002997 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2998 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002999 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003000 } else {
3001 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003002 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003003 } else {
3004 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003005 }
Robert Carr2047fae2016-11-28 14:09:09 -08003006 });
3007
Dan Stoza9e56aa02015-11-02 13:00:03 -08003008 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri86770e52018-09-24 22:40:58 +00003009 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
Dan Stozaee44edd2015-03-23 15:50:23 -07003010 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003011 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07003012 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06003013 newDataLatched = true;
3014 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003015 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003016
Alec Mouri86770e52018-09-24 22:40:58 +00003017 // Clear the renderengine fence here...
3018 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3019 // clear instead of sp::clear.
3020 getBE().flushFence = Fence::NO_FENCE;
3021
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003022 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003023
3024 // If we will need to wake up at some time in the future to deal with a
3025 // queued frame that shouldn't be displayed during this vsync period, wake
3026 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003027 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003028 signalLayerUpdate();
3029 }
3030
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003031 // enter boot animation on first buffer latch
3032 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3033 ALOGI("Enter boot animation");
3034 mBootStage = BootStage::BOOTANIMATION;
3035 }
3036
Dan Stoza6b9454d2014-11-07 16:00:59 -08003037 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003038 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003039}
3040
Mathias Agopianad456f92011-01-13 17:53:01 -08003041void SurfaceFlinger::invalidateHwcGeometry()
3042{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003043 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003044}
3045
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003046void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& display,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003047 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003048 // We only need to actually compose the display if:
3049 // 1) It is being handled by hardware composer, which may need this to
3050 // keep its virtual display state machine in sync, or
3051 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski34157762018-10-31 13:07:19 -07003052 if (!display->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003053 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003054 return;
3055 }
3056
Dan Stoza9e56aa02015-11-02 13:00:03 -08003057 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003058 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003059
3060 // swap buffers (presentation)
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003061 display->queueBuffer(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003062}
3063
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003064bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003065 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003066
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003067 const Region bounds(display->bounds());
3068 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003069 const auto displayId = display->getId();
3070 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003071 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003072
Peiyong Lind3788632018-09-18 16:01:31 -07003073 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003074 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003075 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003076
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003077 // Framebuffer will live in this scope for GPU composition.
3078 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
3079
Dan Stoza9e56aa02015-11-02 13:00:03 -08003080 if (hasClientComposition) {
3081 ALOGV("hasClientComposition");
3082
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003083 sp<GraphicBuffer> buf = display->dequeueBuffer();
3084
3085 if (buf == nullptr) {
3086 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3087 "client composition for this frame",
3088 display->getDisplayName().c_str());
3089 return false;
3090 }
3091
3092 // Bind the framebuffer in this scope.
3093 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3094 buf->getNativeBuffer());
3095
3096 if (fbo->getStatus() != NO_ERROR) {
3097 ALOGW("Binding buffer for display [%s] failed with status: %d",
3098 display->getDisplayName().c_str(), fbo->getStatus());
3099 return false;
3100 }
3101
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003102 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003103 if (display->hasWideColorGamut()) {
3104 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003105 }
3106 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003107 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003108 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003109
Dominik Laskowski7e045462018-05-30 13:02:02 -07003110 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003111 const bool skipClientColorTransform =
3112 getBE().mHwc
3113 ->hasDisplayCapability(displayId,
3114 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003115
Peiyong Lind3788632018-09-18 16:01:31 -07003116 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003117 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3118 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003119 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003120 }
3121
Chia-I Wud49d6692018-06-27 07:17:41 +08003122 // The current enhanced saturation matrix is designed to enhance Display P3,
3123 // thus we only apply this matrix when the render intent is not colorimetric
3124 // and the output color space is Display P3.
3125 needsEnhancedColorMatrix =
3126 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3127 outputDataspace == Dataspace::DISPLAY_P3);
3128 if (needsEnhancedColorMatrix) {
3129 colorMatrix *= mEnhancedSaturationMatrix;
3130 }
3131
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003132 display->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003133
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003134 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003135 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003136 // when using overlays, we assume a fully transparent framebuffer
3137 // NOTE: we could reduce how much we need to clear, for instance
3138 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003139 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003140 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003141 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003142 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003143 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003144 // we're left with the letterbox region
3145 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003146 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003147
3148 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003149 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003150
Mathias Agopianb9494d52012-04-18 02:28:45 -07003151 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003152 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003153 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003154 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003155 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003156 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003157
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003158 const Rect& bounds = display->getBounds();
3159 const Rect& scissor = display->getScissor();
3160 if (scissor != bounds) {
3161 // scissor doesn't match the screen's dimensions, so we
3162 // need to clear everything outside of it and enable
3163 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003164
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003165 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003166 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003167 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003168 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003169
Mathias Agopian85d751c2012-08-29 16:59:24 -07003170 /*
3171 * and then, render the layers targeted at the framebuffer
3172 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003173
Dan Stoza9e56aa02015-11-02 13:00:03 -08003174 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003175 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003176 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003177 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003178 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003179 displayTransform.transform(layer->visibleRegion)));
3180 ALOGV("Layer: %s", layer->getName().string());
3181 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003182 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003183 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003184 case HWC2::Composition::Cursor:
3185 case HWC2::Composition::Device:
3186 case HWC2::Composition::Sideband:
3187 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003188 LOG_ALWAYS_FATAL_IF(!displayId);
David Sodmanc1498e62018-09-12 14:36:26 -07003189 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003190 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
David Sodmanc1498e62018-09-12 14:36:26 -07003191 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003192 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003193 // never clear the very first layer since we're
3194 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003195 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003196 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003197 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003198 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003199 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003200 if (layer->hasColorTransform()) {
3201 mat4 tmpMatrix;
3202 if (applyColorMatrix) {
3203 tmpMatrix = mDrawingState.colorMatrix;
3204 }
3205 tmpMatrix *= layer->getColorTransform();
3206 if (needsEnhancedColorMatrix) {
3207 tmpMatrix *= mEnhancedSaturationMatrix;
3208 }
3209 getRenderEngine().setColorTransform(tmpMatrix);
3210 } else {
3211 getRenderEngine().setColorTransform(colorMatrix);
3212 }
David Sodmanc1498e62018-09-12 14:36:26 -07003213 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003214 break;
3215 }
3216 default:
3217 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003218 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003219 } else {
3220 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003221 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003222 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003223 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003224
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003225 // Perform some cleanup steps if we used client composition.
3226 if (hasClientComposition) {
3227 getRenderEngine().setColorTransform(mat4());
3228 getBE().mRenderEngine->disableScissor();
3229 display->finishBuffer();
3230 // Clear out error flags here so that we don't wait until next
3231 // composition to log.
3232 getRenderEngine().checkErrors();
3233 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003234 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003235}
3236
Chia-I Wu28e3a252018-09-07 12:05:02 -07003237void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003238 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003239 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003240}
3241
Dan Stoza7d89d062015-04-30 13:29:25 -07003242status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003243 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003244 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003245 const sp<Layer>& lbc,
3246 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003247{
Dan Stoza7d89d062015-04-30 13:29:25 -07003248 // add this layer to the current state list
3249 {
3250 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003251 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003252 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3253 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003254 return NO_MEMORY;
3255 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003256 if (parent == nullptr) {
3257 mCurrentState.layersSortedByZ.add(lbc);
3258 } else {
Robert Carr2e102c92018-10-23 12:11:15 -07003259 if (parent->isRemovedFromCurrentState()) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003260 ALOGE("addClientLayer called with a removed parent");
chaviw61626f22018-11-15 16:26:27 -08003261 lbc->onRemovedFromCurrentState();
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003262 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003263 parent->addChild(lbc);
3264 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003265
Yiwei Zhang243b3782018-05-15 17:40:04 -07003266 if (gbc != nullptr) {
3267 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3268 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3269 mMaxGraphicBufferProducerListSize,
3270 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3271 mGraphicBufferProducerList.size(),
3272 mMaxGraphicBufferProducerListSize, mNumLayers);
3273 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003274 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003275 }
3276
Mathias Agopian96f08192010-06-02 23:28:45 -07003277 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003278 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003279
Dan Stoza7d89d062015-04-30 13:29:25 -07003280 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003281}
3282
Robert Carr8d2711b2018-11-14 16:36:18 -08003283status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003284 Mutex::Autolock _l(mStateLock);
Robert Carr8d2711b2018-11-14 16:36:18 -08003285 return removeLayerLocked(mStateLock, layer);
chaviwca27f252018-02-06 16:46:39 -08003286}
Robert Carr7f9b8992017-03-10 11:08:39 -08003287
Robert Carr8d2711b2018-11-14 16:36:18 -08003288status_t SurfaceFlinger::removeLayerLocked(const Mutex& lock, const sp<Layer>& layer) {
chaviw5aedec92018-10-22 10:40:38 -07003289 if (layer->isLayerDetached()) {
3290 return NO_ERROR;
3291 }
3292
Robert Carr1f0a16a2016-10-24 16:27:39 -07003293 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003294 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003295 if (p != nullptr) {
Chia-I Wufae51c42017-06-15 12:53:59 -07003296 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003297 } else {
3298 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003299 }
3300
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003301 layer->onRemovedFromCurrentState();
Robert Carr2e102c92018-10-23 12:11:15 -07003302
3303 markLayerPendingRemovalLocked(lock, layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003304 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003305}
3306
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003307uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003308 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003309}
3310
Mathias Agopian3f844832013-08-07 21:24:32 -07003311uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003312 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003313}
3314
Mathias Agopian3f844832013-08-07 21:24:32 -07003315uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003316 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003317}
3318
3319uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003320 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003321 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003322 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003323 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003324 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003325 }
3326 return old;
3327}
3328
chaviwca27f252018-02-06 16:46:39 -08003329bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3330 for (const ComposerState& state : states) {
3331 // Here we need to check that the interface we're given is indeed
3332 // one of our own. A malicious client could give us a nullptr
3333 // IInterface, or one of its own or even one of our own but a
3334 // different type. All these situations would cause us to crash.
3335 if (state.client == nullptr) {
3336 return true;
3337 }
3338
3339 sp<IBinder> binder = IInterface::asBinder(state.client);
3340 if (binder == nullptr) {
3341 return true;
3342 }
3343
3344 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3345 return true;
3346 }
3347 }
3348 return false;
3349}
3350
Mathias Agopian8b33f032012-07-24 20:43:54 -07003351void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003352 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003353 const Vector<DisplayState>& displays,
3354 uint32_t flags)
3355{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003356 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003357 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003358 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003359
chaviwca27f252018-02-06 16:46:39 -08003360 if (containsAnyInvalidClientState(states)) {
3361 return;
3362 }
3363
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003364 if (flags & eAnimation) {
3365 // For window updates that are part of an animation we must wait for
3366 // previous animation "frames" to be handled.
3367 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003368 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003369 if (CC_UNLIKELY(err != NO_ERROR)) {
3370 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003371 // caller after a few seconds.
3372 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3373 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003374 mAnimTransactionPending = false;
3375 break;
3376 }
3377 }
3378 }
3379
chaviwca27f252018-02-06 16:46:39 -08003380 for (const DisplayState& display : displays) {
3381 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003382 }
3383
Marissa Walle2ffb422018-10-12 11:33:52 -07003384 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003385 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003386 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003387 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003388 // If the state doesn't require a traversal and there are callbacks, send them now
3389 if (!(clientStateFlags & eTraversalNeeded)) {
3390 mTransactionCompletedThread.sendCallbacks();
3391 }
3392 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003393
3394 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3395 // as destroyed should only occur after setting all other states. This is to allow for a
3396 // child re-parent to happen before marking its original parent as destroyed (which would
3397 // then mark the child as destroyed).
3398 for (const ComposerState& state : states) {
3399 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003400 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003401
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003402 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3403 // anyway. This can be used as a flush mechanism for previous async transactions.
3404 // Empty animation transaction can be used to simulate back-pressure, so also force a
3405 // transaction for empty animation transactions.
3406 if (transactionFlags == 0 &&
3407 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003408 transactionFlags = eTransactionNeeded;
3409 }
3410
Mathias Agopian386aa982011-11-07 21:58:03 -08003411 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003412 if (mInterceptor->isEnabled()) {
3413 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003414 }
Irvel468051e2016-06-13 16:44:44 -07003415
Mathias Agopian386aa982011-11-07 21:58:03 -08003416 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003417 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3418 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003419 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003420
3421 // if this is a synchronous transaction, wait for it to take effect
3422 // before returning.
3423 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003424 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003425 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003426 if (flags & eAnimation) {
3427 mAnimTransactionPending = true;
3428 }
3429 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003430 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3431 if (CC_UNLIKELY(err != NO_ERROR)) {
3432 // just in case something goes wrong in SF, return to the
3433 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003434 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3435 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003436 break;
3437 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003438 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003439 }
3440}
3441
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003442uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3443 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3444 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003445
Mathias Agopiane57f2922012-08-09 16:29:12 -07003446 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003447 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3448
3449 const uint32_t what = s.what;
3450 if (what & DisplayState::eSurfaceChanged) {
3451 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3452 state.surface = s.surface;
3453 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003454 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003455 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003456 if (what & DisplayState::eLayerStackChanged) {
3457 if (state.layerStack != s.layerStack) {
3458 state.layerStack = s.layerStack;
3459 flags |= eDisplayTransactionNeeded;
3460 }
3461 }
3462 if (what & DisplayState::eDisplayProjectionChanged) {
3463 if (state.orientation != s.orientation) {
3464 state.orientation = s.orientation;
3465 flags |= eDisplayTransactionNeeded;
3466 }
3467 if (state.frame != s.frame) {
3468 state.frame = s.frame;
3469 flags |= eDisplayTransactionNeeded;
3470 }
3471 if (state.viewport != s.viewport) {
3472 state.viewport = s.viewport;
3473 flags |= eDisplayTransactionNeeded;
3474 }
3475 }
3476 if (what & DisplayState::eDisplaySizeChanged) {
3477 if (state.width != s.width) {
3478 state.width = s.width;
3479 flags |= eDisplayTransactionNeeded;
3480 }
3481 if (state.height != s.height) {
3482 state.height = s.height;
3483 flags |= eDisplayTransactionNeeded;
3484 }
3485 }
3486
Mathias Agopiane57f2922012-08-09 16:29:12 -07003487 return flags;
3488}
3489
Robert Carrd4ae7f32018-06-07 16:10:57 -07003490bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3491 IPCThreadState* ipc = IPCThreadState::self();
3492 const int pid = ipc->getCallingPid();
3493 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003494 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003495 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003496 return false;
3497 }
3498 return true;
3499}
3500
chaviwca27f252018-02-06 16:46:39 -08003501uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3502 const layer_state_t& s = composerState.state;
3503 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3504
Mathias Agopian13127d82013-03-05 17:47:11 -08003505 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003506 if (layer == nullptr) {
3507 return 0;
3508 }
3509
chaviw8b3871a2017-11-01 17:41:01 -07003510 uint32_t flags = 0;
3511
Garfield Tan8a3083e2018-12-03 13:21:07 -08003512 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003513 bool geometryAppliesWithResize =
3514 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003515
3516 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3517 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003518 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003519 layer->pushPendingState();
3520 }
3521
chaviw8b3871a2017-11-01 17:41:01 -07003522 if (what & layer_state_t::ePositionChanged) {
3523 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3524 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003525 }
chaviw8b3871a2017-11-01 17:41:01 -07003526 }
3527 if (what & layer_state_t::eLayerChanged) {
3528 // NOTE: index needs to be calculated before we update the state
3529 const auto& p = layer->getParent();
3530 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003531 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003532 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003533 mCurrentState.layersSortedByZ.removeAt(idx);
3534 mCurrentState.layersSortedByZ.add(layer);
3535 // we need traversal (state changed)
3536 // AND transaction (list changed)
3537 flags |= eTransactionNeeded|eTraversalNeeded;
3538 }
chaviw8b3871a2017-11-01 17:41:01 -07003539 } else {
3540 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003541 flags |= eTransactionNeeded|eTraversalNeeded;
3542 }
3543 }
chaviw8b3871a2017-11-01 17:41:01 -07003544 }
3545 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003546 // NOTE: index needs to be calculated before we update the state
3547 const auto& p = layer->getParent();
3548 if (p == nullptr) {
3549 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3550 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3551 mCurrentState.layersSortedByZ.removeAt(idx);
3552 mCurrentState.layersSortedByZ.add(layer);
3553 // we need traversal (state changed)
3554 // AND transaction (list changed)
3555 flags |= eTransactionNeeded|eTraversalNeeded;
3556 }
3557 } else {
3558 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3559 flags |= eTransactionNeeded|eTraversalNeeded;
3560 }
chaviw8b3871a2017-11-01 17:41:01 -07003561 }
3562 }
3563 if (what & layer_state_t::eSizeChanged) {
3564 if (layer->setSize(s.w, s.h)) {
3565 flags |= eTraversalNeeded;
3566 }
3567 }
3568 if (what & layer_state_t::eAlphaChanged) {
3569 if (layer->setAlpha(s.alpha))
3570 flags |= eTraversalNeeded;
3571 }
3572 if (what & layer_state_t::eColorChanged) {
3573 if (layer->setColor(s.color))
3574 flags |= eTraversalNeeded;
3575 }
Peiyong Lind3788632018-09-18 16:01:31 -07003576 if (what & layer_state_t::eColorTransformChanged) {
3577 if (layer->setColorTransform(s.colorTransform)) {
3578 flags |= eTraversalNeeded;
3579 }
3580 }
chaviw8b3871a2017-11-01 17:41:01 -07003581 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003582 // TODO: b/109894387
3583 //
3584 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3585 // rotation. To see the problem observe that if we have a square parent, and a child
3586 // of the same size, then we rotate the child 45 degrees around it's center, the child
3587 // must now be cropped to a non rectangular 8 sided region.
3588 //
3589 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3590 // private API, and the WindowManager only uses rotation in one case, which is on a top
3591 // level layer in which cropping is not an issue.
3592 //
3593 // However given that abuse of rotation matrices could lead to surfaces extending outside
3594 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3595 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3596 // transformations.
3597 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003598 flags |= eTraversalNeeded;
3599 }
3600 if (what & layer_state_t::eTransparentRegionChanged) {
3601 if (layer->setTransparentRegionHint(s.transparentRegion))
3602 flags |= eTraversalNeeded;
3603 }
3604 if (what & layer_state_t::eFlagsChanged) {
3605 if (layer->setFlags(s.flags, s.mask))
3606 flags |= eTraversalNeeded;
3607 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003608 if (what & layer_state_t::eCropChanged_legacy) {
3609 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003610 flags |= eTraversalNeeded;
3611 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003612 if (what & layer_state_t::eCornerRadiusChanged) {
3613 if (layer->setCornerRadius(s.cornerRadius))
3614 flags |= eTraversalNeeded;
3615 }
chaviw8b3871a2017-11-01 17:41:01 -07003616 if (what & layer_state_t::eLayerStackChanged) {
3617 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3618 // We only allow setting layer stacks for top level layers,
3619 // everything else inherits layer stack from its parent.
3620 if (layer->hasParent()) {
3621 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3622 layer->getName().string());
3623 } else if (idx < 0) {
3624 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3625 "that also does not appear in the top level layer list. Something"
3626 " has gone wrong.", layer->getName().string());
3627 } else if (layer->setLayerStack(s.layerStack)) {
3628 mCurrentState.layersSortedByZ.removeAt(idx);
3629 mCurrentState.layersSortedByZ.add(layer);
3630 // we need traversal (state changed)
3631 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003632 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003633 }
3634 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003635 if (what & layer_state_t::eDeferTransaction_legacy) {
3636 if (s.barrierHandle_legacy != nullptr) {
3637 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3638 } else if (s.barrierGbp_legacy != nullptr) {
3639 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003640 if (authenticateSurfaceTextureLocked(gbp)) {
3641 const auto& otherLayer =
3642 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003643 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003644 } else {
3645 ALOGE("Attempt to defer transaction to to an"
3646 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003647 }
3648 }
chaviw8b3871a2017-11-01 17:41:01 -07003649 // We don't trigger a traversal here because if no other state is
3650 // changed, we don't want this to cause any more work
3651 }
3652 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003653 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003654 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003655 if (!hadParent) {
3656 mCurrentState.layersSortedByZ.remove(layer);
3657 }
chaviw8b3871a2017-11-01 17:41:01 -07003658 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003659 }
chaviw8b3871a2017-11-01 17:41:01 -07003660 }
3661 if (what & layer_state_t::eReparentChildren) {
3662 if (layer->reparentChildren(s.reparentHandle)) {
3663 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003664 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003665 }
chaviw8b3871a2017-11-01 17:41:01 -07003666 if (what & layer_state_t::eDetachChildren) {
3667 layer->detachChildren();
3668 }
3669 if (what & layer_state_t::eOverrideScalingModeChanged) {
3670 layer->setOverrideScalingMode(s.overrideScalingMode);
3671 // We don't trigger a traversal here because if no other state is
3672 // changed, we don't want this to cause any more work
3673 }
Marissa Wall61c58622018-07-18 10:12:20 -07003674 if (what & layer_state_t::eTransformChanged) {
3675 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3676 }
3677 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3678 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3679 flags |= eTraversalNeeded;
3680 }
3681 if (what & layer_state_t::eCropChanged) {
3682 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3683 }
Marissa Wall861616d2018-10-22 12:52:23 -07003684 if (what & layer_state_t::eFrameChanged) {
3685 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3686 }
Marissa Wall61c58622018-07-18 10:12:20 -07003687 if (what & layer_state_t::eBufferChanged) {
3688 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3689 }
3690 if (what & layer_state_t::eAcquireFenceChanged) {
3691 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3692 }
3693 if (what & layer_state_t::eDataspaceChanged) {
3694 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3695 }
3696 if (what & layer_state_t::eHdrMetadataChanged) {
3697 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3698 }
3699 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3700 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3701 }
3702 if (what & layer_state_t::eApiChanged) {
3703 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3704 }
3705 if (what & layer_state_t::eSidebandStreamChanged) {
3706 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3707 }
Robert Carr720e5062018-07-30 17:45:14 -07003708 if (what & layer_state_t::eInputInfoChanged) {
3709 layer->setInputInfo(s.inputInfo);
3710 flags |= eTraversalNeeded;
3711 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003712 std::vector<sp<CallbackHandle>> callbackHandles;
3713 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3714 mTransactionCompletedThread.run();
3715 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3716 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3717 }
3718 }
3719 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3720 // Do not put anything that updates layer state or modifies flags after
3721 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003722 return flags;
3723}
3724
chaviwca27f252018-02-06 16:46:39 -08003725void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3726 const layer_state_t& state = composerState.state;
3727 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3728
3729 sp<Layer> layer(client->getLayerUser(state.surface));
3730 if (layer == nullptr) {
3731 return;
3732 }
3733
chaviwca27f252018-02-06 16:46:39 -08003734 if (state.what & layer_state_t::eDestroySurface) {
3735 removeLayerLocked(mStateLock, layer);
3736 }
3737}
3738
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003739status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003740 const String8& name,
3741 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003742 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003743 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003744 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003745{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003746 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003747 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003748 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003749 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003750 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003751
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003752 status_t result = NO_ERROR;
3753
3754 sp<Layer> layer;
3755
Cody Northropbc755282017-03-31 12:00:08 -06003756 String8 uniqueName = getUniqueLayerName(name);
3757
Mathias Agopian3165cc22012-08-08 19:42:09 -07003758 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003759 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003760 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3761 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003762
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003763 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003764 case ISurfaceComposerClient::eFXSurfaceBufferState:
3765 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3766 break;
chaviw13fdc492017-06-27 12:40:18 -07003767 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003768 // check if buffer size is set for color layer.
3769 if (w > 0 || h > 0) {
3770 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3771 int(w), int(h));
3772 return BAD_VALUE;
3773 }
3774
chaviw13fdc492017-06-27 12:40:18 -07003775 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003776 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003777 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003778 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003779 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003780 // check if buffer size is set for container layer.
3781 if (w > 0 || h > 0) {
3782 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3783 int(w), int(h));
3784 return BAD_VALUE;
3785 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07003786 result = createContainerLayer(client,
3787 uniqueName, w, h, flags,
3788 handle, &layer);
3789 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003790 default:
3791 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003792 break;
3793 }
3794
Dan Stoza7d89d062015-04-30 13:29:25 -07003795 if (result != NO_ERROR) {
3796 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003797 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003798
Chia-I Wuab0c3192017-08-01 11:29:00 -07003799 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3800 // TODO b/64227542
3801 if (windowType == 441731) {
3802 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3803 layer->setPrimaryDisplayOnly();
3804 }
3805
Albert Chaulk479c60c2017-01-27 14:21:34 -05003806 layer->setInfo(windowType, ownerUid);
3807
Robert Carr1f0a16a2016-10-24 16:27:39 -07003808 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003809 if (result != NO_ERROR) {
3810 return result;
3811 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003812 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003813
3814 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003815 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003816}
3817
Cody Northropbc755282017-03-31 12:00:08 -06003818String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3819{
3820 bool matchFound = true;
3821 uint32_t dupeCounter = 0;
3822
3823 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3824 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3825
Dan Stoza436ccf32018-06-21 12:10:12 -07003826 // Grab the state lock since we're accessing mCurrentState
3827 Mutex::Autolock lock(mStateLock);
3828
Cody Northropbc755282017-03-31 12:00:08 -06003829 // Loop over layers until we're sure there is no matching name
3830 while (matchFound) {
3831 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003832 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003833 if (layer->getName() == uniqueName) {
3834 matchFound = true;
3835 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3836 }
3837 });
3838 }
3839
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003840 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3841 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003842
3843 return uniqueName;
3844}
3845
Marissa Wallfd668622018-05-10 10:21:13 -07003846status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3847 uint32_t w, uint32_t h, uint32_t flags,
3848 PixelFormat& format, sp<IBinder>* handle,
3849 sp<IGraphicBufferProducer>* gbp,
3850 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003851 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003852 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003853 case PIXEL_FORMAT_TRANSPARENT:
3854 case PIXEL_FORMAT_TRANSLUCENT:
3855 format = PIXEL_FORMAT_RGBA_8888;
3856 break;
3857 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003858 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003859 break;
3860 }
3861
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003862 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003863 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003864 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003865 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003866 *handle = layer->getHandle();
3867 *gbp = layer->getProducer();
3868 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003869 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003870
Marissa Wallfd668622018-05-10 10:21:13 -07003871 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003872 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003873}
3874
Marissa Wall61c58622018-07-18 10:12:20 -07003875status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3876 uint32_t w, uint32_t h, uint32_t flags,
3877 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003878 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003879 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003880 *handle = layer->getHandle();
3881 *outLayer = layer;
3882
3883 return NO_ERROR;
3884}
3885
chaviw13fdc492017-06-27 12:40:18 -07003886status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003887 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003888 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003889{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003890 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003891 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003892 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003893}
3894
Robert Carr6b3f6c52018-08-13 13:05:17 -07003895status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3896 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3897 sp<IBinder>* handle, sp<Layer>* outLayer)
3898{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003899 *outLayer =
3900 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003901 *handle = (*outLayer)->getHandle();
3902 return NO_ERROR;
3903}
3904
3905
Mathias Agopianac9fa422013-02-11 16:40:36 -08003906status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003907{
Robert Carr9524cb32017-02-13 11:32:32 -08003908 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003909 status_t err = NO_ERROR;
3910 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003911 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003912 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003913 err = removeLayer(l);
3914 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3915 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003916 }
3917 return err;
3918}
3919
Robert Carr2e102c92018-10-23 12:11:15 -07003920void SurfaceFlinger::markLayerPendingRemovalLocked(const Mutex&, const sp<Layer>& layer) {
3921 mLayersPendingRemoval.add(layer);
3922 mLayersRemoved = true;
3923 setTransactionFlags(eTransactionNeeded);
3924}
3925
3926void SurfaceFlinger::onHandleDestroyed(const sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003927{
Robert Carr2e102c92018-10-23 12:11:15 -07003928 Mutex::Autolock lock(mStateLock);
3929 markLayerPendingRemovalLocked(mStateLock, layer);
Rob Carr4bba3702018-10-08 21:53:30 +00003930}
3931
Mathias Agopianb60314a2012-04-10 22:09:54 -07003932// ---------------------------------------------------------------------------
3933
Andy McFadden13a082e2012-08-24 10:16:42 -07003934void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003935 const auto displayToken = getInternalDisplayToken();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003936 if (!displayToken) return;
3937
Jesse Hall01e29052013-02-19 16:13:35 -08003938 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003939 Vector<ComposerState> state;
3940 Vector<DisplayState> displays;
3941 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003942 d.what = DisplayState::eDisplayProjectionChanged |
3943 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003944 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003945 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003946 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003947 d.frame.makeInvalid();
3948 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003949 d.width = 0;
3950 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003951 displays.add(d);
3952 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003953
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003954 const auto display = getDisplayDevice(displayToken);
3955 if (!display) return;
3956
3957 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3958
Dominik Laskowski075d3172018-05-24 15:50:06 -07003959 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003960 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003961 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003962
Brian Andersond0010582017-03-07 13:20:31 -08003963 // Use phase of 0 since phase is not known.
3964 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07003965 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
3966 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003967}
3968
3969void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003970 // Async since we may be called from the main thread.
3971 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003972}
3973
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003974void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3975 bool stateLockHeld) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003976 if (display->isVirtual()) {
3977 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003978 return;
3979 }
3980
Dominik Laskowski075d3172018-05-24 15:50:06 -07003981 const auto displayId = display->getId();
3982 LOG_ALWAYS_FATAL_IF(!displayId);
3983
Dominik Laskowski34157762018-10-31 13:07:19 -07003984 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003985
3986 int currentMode = display->getPowerMode();
3987 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003988 return;
3989 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003990
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003991 display->setPowerMode(mode);
3992
Lloyd Pique4dccc412018-01-22 17:21:36 -08003993 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003994 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003995 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003996 if (idx < 0) {
3997 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3998 return;
3999 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07004000 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07004001 }
4002
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004003 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004004 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004005 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004006 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004007 if (mUseScheduler) {
4008 mScheduler->onScreenAcquired(mAppConnectionHandle);
4009 } else {
4010 mEventThread->onScreenAcquired();
4011 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004012 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004013 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004014
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004015 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004016 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004017 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004018
4019 struct sched_param param = {0};
4020 param.sched_priority = 1;
4021 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4022 ALOGW("Couldn't set SCHED_FIFO on display on");
4023 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004024 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004025 // Turn off the display
4026 struct sched_param param = {0};
4027 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4028 ALOGW("Couldn't set SCHED_OTHER on display off");
4029 }
4030
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004031 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004032 if (mUseScheduler) {
4033 mScheduler->disableHardwareVsync(true);
4034 } else {
4035 disableHardwareVsync(true); // also cancels any in-progress resync
4036 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004037 if (mUseScheduler) {
4038 mScheduler->onScreenReleased(mAppConnectionHandle);
4039 } else {
4040 mEventThread->onScreenReleased();
4041 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004042 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004043
Dominik Laskowski075d3172018-05-24 15:50:06 -07004044 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004045 mVisibleRegionsDirty = true;
4046 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004047 } else if (mode == HWC_POWER_MODE_DOZE ||
4048 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004049 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004050 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004051 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004052 if (mUseScheduler) {
4053 mScheduler->onScreenAcquired(mAppConnectionHandle);
4054 } else {
4055 mEventThread->onScreenAcquired();
4056 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004057 resyncToHardwareVsync(true);
4058 }
4059 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4060 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004061 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004062 if (mUseScheduler) {
4063 mScheduler->disableHardwareVsync(true);
4064 } else {
4065 disableHardwareVsync(true); // also cancels any in-progress resync
4066 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004067 if (mUseScheduler) {
4068 mScheduler->onScreenReleased(mAppConnectionHandle);
4069 } else {
4070 mEventThread->onScreenReleased();
4071 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004072 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004073 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004074 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004075 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004076 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004077 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004078
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004079 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004080 mTimeStats->setPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004081 }
4082
Dominik Laskowski34157762018-10-31 13:07:19 -07004083 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004084}
4085
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004086void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004087 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004088 const auto display = getDisplayDevice(displayToken);
4089 if (!display) {
4090 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4091 displayToken.get());
4092 } else if (display->isVirtual()) {
4093 ALOGW("Attempt to set power mode %d for virtual display", mode);
4094 } else {
4095 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004096 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004097 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004098}
4099
4100// ---------------------------------------------------------------------------
4101
Lloyd Pique755e3192018-01-31 16:46:15 -08004102status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4103 NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004104 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004105
Mathias Agopianbd115332013-04-18 16:41:04 -07004106 IPCThreadState* ipc = IPCThreadState::self();
4107 const int pid = ipc->getCallingPid();
4108 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004109
Mathias Agopianbd115332013-04-18 16:41:04 -07004110 if ((uid != AID_SHELL) &&
4111 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004112 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4113 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004114 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004115 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004116 // (this would indicate SF is stuck, but we want to be able to
4117 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004118 status_t err = mStateLock.timedLock(s2ns(1));
4119 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004120 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004121 StringAppendF(&result,
4122 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4123 "(no locks held)\n",
4124 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004125 }
4126
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004127 bool dumpAll = true;
4128 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004129 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004130
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004131 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004132 if ((index < numArgs) &&
4133 (args[index] == String16("--list"))) {
4134 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004135 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004136 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004137 }
4138
4139 if ((index < numArgs) &&
4140 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004141 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004142 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004143 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004144 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004145
4146 if ((index < numArgs) &&
4147 (args[index] == String16("--latency-clear"))) {
4148 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004149 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004150 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004151 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004152
4153 if ((index < numArgs) &&
4154 (args[index] == String16("--dispsync"))) {
4155 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004156 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004157 dumpAll = false;
4158 }
Dan Stozab90cf072015-03-05 11:05:59 -08004159
4160 if ((index < numArgs) &&
4161 (args[index] == String16("--static-screen"))) {
4162 index++;
4163 dumpStaticScreenStats(result);
4164 dumpAll = false;
4165 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004166
4167 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004168 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004169 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004170 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004171 dumpAll = false;
4172 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004173
4174 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4175 index++;
4176 dumpWideColorInfo(result);
4177 dumpAll = false;
4178 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004179
4180 if ((index < numArgs) &&
4181 (args[index] == String16("--enable-layer-stats"))) {
4182 index++;
4183 mLayerStats.enable();
4184 dumpAll = false;
4185 }
4186
4187 if ((index < numArgs) &&
4188 (args[index] == String16("--disable-layer-stats"))) {
4189 index++;
4190 mLayerStats.disable();
4191 dumpAll = false;
4192 }
4193
4194 if ((index < numArgs) &&
4195 (args[index] == String16("--clear-layer-stats"))) {
4196 index++;
4197 mLayerStats.clear();
4198 dumpAll = false;
4199 }
4200
4201 if ((index < numArgs) &&
4202 (args[index] == String16("--dump-layer-stats"))) {
4203 index++;
4204 mLayerStats.dump(result);
4205 dumpAll = false;
4206 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004207
4208 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004209 (args[index] == String16("--frame-composition"))) {
4210 index++;
4211 dumpFrameCompositionInfo(result);
4212 dumpAll = false;
4213 }
4214
4215 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004216 (args[index] == String16("--display-identification"))) {
4217 index++;
4218 dumpDisplayIdentificationData(result);
4219 dumpAll = false;
4220 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004221
4222 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4223 index++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004224 mTimeStats->parseArgs(asProto, args, index, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004225 dumpAll = false;
4226 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004227 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004228
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004229 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004230 if (asProto) {
4231 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4232 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4233 } else {
4234 dumpAllLocked(args, index, result);
4235 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004236 }
4237
Mathias Agopian9795c422009-08-26 16:36:26 -07004238 if (locked) {
4239 mStateLock.unlock();
4240 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004241 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004242 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004243 return NO_ERROR;
4244}
4245
Yiwei Zhang5434a782018-12-05 18:06:32 -08004246void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */, size_t& /* index */,
4247 std::string& result) const {
4248 mCurrentState.traverseInZOrder(
4249 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004250}
4251
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004252void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004253 std::string& result) const {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004254 String8 name;
4255 if (index < args.size()) {
4256 name = String8(args[index]);
4257 index++;
4258 }
4259
Dominik Laskowski075d3172018-05-24 15:50:06 -07004260 if (const auto displayId = getInternalDisplayId();
4261 displayId && getHwComposer().isConnected(*displayId)) {
4262 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004263 const nsecs_t period = activeConfig->getVsyncPeriod();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004264 StringAppendF(&result, "%" PRId64 "\n", period);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004265 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004266
4267 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004268 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004269 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004270 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004271 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004272 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004273 }
Robert Carr2047fae2016-11-28 14:09:09 -08004274 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004275 }
4276}
4277
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004278void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004279 std::string& /* result */) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004280 String8 name;
4281 if (index < args.size()) {
4282 name = String8(args[index]);
4283 index++;
4284 }
4285
Robert Carr2047fae2016-11-28 14:09:09 -08004286 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004287 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004288 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004289 }
Robert Carr2047fae2016-11-28 14:09:09 -08004290 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004291
Svetoslavd85084b2014-03-20 10:28:31 -07004292 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004293}
4294
Jamie Gennis6547ff42013-07-16 20:12:42 -07004295// This should only be called from the main thread. Otherwise it would need
4296// the lock and should use mCurrentState rather than mDrawingState.
4297void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004298 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004299 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004300 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004301
4302 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4303}
4304
Yiwei Zhang5434a782018-12-05 18:06:32 -08004305void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004306 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004307
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004308 if (isLayerTripleBufferingDisabled())
4309 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004310
Yiwei Zhang5434a782018-12-05 18:06:32 -08004311 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4312 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4313 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4314 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4315 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4316 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004317 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004318}
4319
Yiwei Zhang5434a782018-12-05 18:06:32 -08004320void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4321 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004322 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4323 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004324 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004325 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004326 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004327 }
David Sodman4a36e932017-11-07 14:29:47 -08004328 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004329 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004330 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004331 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4332 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004333}
4334
Dan Stozae77c7662016-05-13 11:37:28 -07004335void SurfaceFlinger::recordBufferingStats(const char* layerName,
4336 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004337 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4338 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004339 for (const auto& segment : history) {
4340 if (!segment.usedThirdBuffer) {
4341 stats.twoBufferTime += segment.totalTime;
4342 }
4343 if (segment.occupancyAverage < 1.0f) {
4344 stats.doubleBufferedTime += segment.totalTime;
4345 } else if (segment.occupancyAverage < 2.0f) {
4346 stats.tripleBufferedTime += segment.totalTime;
4347 }
4348 ++stats.numSegments;
4349 stats.totalTime += segment.totalTime;
4350 }
4351}
4352
Yiwei Zhang5434a782018-12-05 18:06:32 -08004353void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4354 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004355
4356 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4357 const size_t count = currentLayers.size();
4358 for (size_t i=0 ; i<count ; i++) {
4359 currentLayers[i]->dumpFrameEvents(result);
4360 }
4361}
4362
Yiwei Zhang5434a782018-12-05 18:06:32 -08004363void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004364 result.append("Buffering stats:\n");
4365 result.append(" [Layer name] <Active time> <Two buffer> "
4366 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004367 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004368 typedef std::tuple<std::string, float, float, float> BufferTuple;
4369 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004370 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004371 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004372 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004373 if (stats.numSegments == 0) {
4374 continue;
4375 }
4376 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4377 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4378 stats.totalTime;
4379 float doubleBufferRatio = static_cast<float>(
4380 stats.doubleBufferedTime) / stats.totalTime;
4381 float tripleBufferRatio = static_cast<float>(
4382 stats.tripleBufferedTime) / stats.totalTime;
4383 sorted.insert({activeTime, {name, twoBufferRatio,
4384 doubleBufferRatio, tripleBufferRatio}});
4385 }
4386 for (const auto& sortedPair : sorted) {
4387 float activeTime = sortedPair.first;
4388 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004389 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4390 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004391 }
4392 result.append("\n");
4393}
4394
Yiwei Zhang5434a782018-12-05 18:06:32 -08004395void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004396 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004397 const auto displayId = display->getId();
4398 if (!displayId) {
4399 continue;
4400 }
4401 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004402 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004403 continue;
4404 }
4405
Yiwei Zhang5434a782018-12-05 18:06:32 -08004406 StringAppendF(&result,
4407 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4408 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004409 uint8_t port;
4410 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004411 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004412 result.append("no identification data\n");
4413 continue;
4414 }
4415
4416 if (!isEdid(data)) {
4417 result.append("unknown identification data: ");
4418 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004419 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004420 }
4421 result.append("\n");
4422 continue;
4423 }
4424
4425 const auto edid = parseEdid(data);
4426 if (!edid) {
4427 result.append("invalid EDID: ");
4428 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004429 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004430 }
4431 result.append("\n");
4432 continue;
4433 }
4434
Yiwei Zhang5434a782018-12-05 18:06:32 -08004435 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004436 result.append(edid->displayName.data(), edid->displayName.length());
4437 result.append("\"\n");
4438 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004439}
4440
Yiwei Zhang5434a782018-12-05 18:06:32 -08004441void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4442 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4443 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4444 StringAppendF(&result, "DisplayColorSetting: %s\n",
4445 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004446
4447 // TODO: print out if wide-color mode is active or not
4448
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004449 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004450 const auto displayId = display->getId();
4451 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004452 continue;
4453 }
4454
Yiwei Zhang5434a782018-12-05 18:06:32 -08004455 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004456 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004457 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004458 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004459 }
4460
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004461 ColorMode currentMode = display->getActiveColorMode();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004462 StringAppendF(&result, " Current color mode: %s (%d)\n",
4463 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004464 }
4465 result.append("\n");
4466}
4467
Yiwei Zhang5434a782018-12-05 18:06:32 -08004468void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004469 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004470 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4471 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004472 continue;
4473 }
4474
Dominik Laskowski05275f12018-11-01 15:03:24 -07004475 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004476 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4477 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004478 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004479 compositionInfo.dump(result, nullptr);
4480 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004481 }
4482 }
David Sodman7e4ae112018-02-09 15:02:28 -08004483}
4484
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004485LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004486 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004487 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4488 const State& state = useDrawing ? mDrawingState : mCurrentState;
4489 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004490 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004491 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004492 });
4493
4494 return layersProto;
4495}
4496
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004497LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004498 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004499
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004500 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004501 resolution->set_w(display.getWidth());
4502 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004503
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004504 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4505 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4506 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004507
Dominik Laskowski075d3172018-05-24 15:50:06 -07004508 const auto displayId = display.getId();
4509 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004510 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004511 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004512 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004513 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004514 }
4515 });
4516
4517 return layersProto;
4518}
4519
Mathias Agopian74d211a2013-04-22 16:55:35 +02004520void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004521 std::string& result) const {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004522 bool colorize = false;
4523 if (index < args.size()
4524 && (args[index] == String16("--color"))) {
4525 colorize = true;
4526 index++;
4527 }
4528
4529 Colorizer colorizer(colorize);
4530
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004531 // figure out if we're stuck somewhere
4532 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004533 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004534 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4535
4536 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004537 * Dump library configuration.
4538 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004539
4540 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004541 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004542 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004543 appendSfConfigString(result);
4544 appendUiConfigString(result);
4545 appendGuiConfigString(result);
4546 result.append("\n");
4547
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004548 result.append("\nDisplay identification data:\n");
4549 dumpDisplayIdentificationData(result);
4550
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004551 result.append("\nWide-Color information:\n");
4552 dumpWideColorInfo(result);
4553
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004554 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004555 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004556 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004557 result.append(SyncFeatures::getInstance().toString());
4558 result.append("\n");
4559
Andy McFadden41d67d72014-04-25 16:58:34 -07004560 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004561 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004562 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004563
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004564 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4565 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004566 if (const auto displayId = getInternalDisplayId();
4567 displayId && getHwComposer().isConnected(*displayId)) {
4568 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004569 StringAppendF(&result,
4570 "Display %s: app phase %" PRId64 " ns, "
4571 "sf phase %" PRId64 " ns, "
4572 "early app phase %" PRId64 " ns, "
4573 "early sf phase %" PRId64 " ns, "
4574 "early app gl phase %" PRId64 " ns, "
4575 "early sf gl phase %" PRId64 " ns, "
4576 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4577 to_string(*displayId).c_str(), vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
4578 appEarlyOffset, sfEarlyOffset, appEarlyGlOffset, sfEarlyGlOffset,
4579 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004580 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004581 result.append("\n");
4582
Dan Stozab90cf072015-03-05 11:05:59 -08004583 // Dump static screen stats
4584 result.append("\n");
4585 dumpStaticScreenStats(result);
4586 result.append("\n");
4587
Yiwei Zhang5434a782018-12-05 18:06:32 -08004588 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004589
Dan Stozae77c7662016-05-13 11:37:28 -07004590 dumpBufferingStats(result);
4591
Andy McFadden4803b742012-09-24 19:07:20 -07004592 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004593 * Dump the visible layer list
4594 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004595 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004596 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4597 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4598 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004599 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004600
Chia-I Wu2f884132018-09-13 15:17:58 -07004601 {
4602 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4603 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004604 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004605 result.append("\n");
4606 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004607
David Sodman7e4ae112018-02-09 15:02:28 -08004608 result.append("\nFrame-Composition information:\n");
4609 dumpFrameCompositionInfo(result);
4610 result.append("\n");
4611
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004612 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004613 * Dump Display state
4614 */
4615
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004616 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004617 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004618 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004619 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004620 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004621 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004622 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004623
4624 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004625 * Dump SurfaceFlinger global state
4626 */
4627
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004628 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004629 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004630 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004631
David Sodmanbc815282017-11-05 18:57:52 -08004632 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004633
Dominik Laskowski075d3172018-05-24 15:50:06 -07004634 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004635 display->undefinedRegion.dump(result, "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004636 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4637 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004638 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004639 StringAppendF(&result,
4640 " transaction-flags : %08x\n"
4641 " gpu_to_cpu_unsupported : %d\n",
4642 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004643
Dominik Laskowski075d3172018-05-24 15:50:06 -07004644 if (const auto displayId = getInternalDisplayId();
4645 displayId && getHwComposer().isConnected(*displayId)) {
4646 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004647 StringAppendF(&result,
4648 " refresh-rate : %f fps\n"
4649 " x-dpi : %f\n"
4650 " y-dpi : %f\n",
4651 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4652 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004653 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004654
Yiwei Zhang5434a782018-12-05 18:06:32 -08004655 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004656
Yiwei Zhang5434a782018-12-05 18:06:32 -08004657 StringAppendF(&result, " use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004658 /*
4659 * VSYNC state
4660 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004661 if (mUseScheduler) {
4662 mScheduler->dump(mAppConnectionHandle, result);
4663 } else {
4664 mEventThread->dump(result);
4665 }
Dan Stozae22aec72016-08-01 13:20:59 -07004666 result.append("\n");
4667
4668 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004669 * Tracing state
4670 */
4671 mTracing.dump(result);
4672 result.append("\n");
4673
4674 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004675 * HWC layer minidump
4676 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004677 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004678 const auto displayId = display->getId();
4679 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004680 continue;
4681 }
4682
Yiwei Zhang5434a782018-12-05 18:06:32 -08004683 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004684 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004685 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004686 result.append("\n");
4687 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004688
4689 /*
4690 * Dump HWComposer state
4691 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004692 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004693 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004694 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004695 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004696 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004697 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004698
4699 /*
4700 * Dump gralloc state
4701 */
4702 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4703 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004704
4705 /*
4706 * Dump VrFlinger state if in use.
4707 */
4708 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4709 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004710 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004711 result.append("\n");
4712 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004713}
4714
Dominik Laskowski075d3172018-05-24 15:50:06 -07004715const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004716 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004717 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004718 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004719 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004720 }
4721 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004722
Dominik Laskowski34157762018-10-31 13:07:19 -07004723 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004724 static const Vector<sp<Layer>> empty;
4725 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004726}
4727
Keun young Park63f165f2012-08-31 10:53:36 -07004728bool SurfaceFlinger::startDdmConnection()
4729{
4730 void* libddmconnection_dso =
4731 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4732 if (!libddmconnection_dso) {
4733 return false;
4734 }
4735 void (*DdmConnection_start)(const char* name);
4736 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004737 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004738 if (!DdmConnection_start) {
4739 dlclose(libddmconnection_dso);
4740 return false;
4741 }
4742 (*DdmConnection_start)(getServiceName());
4743 return true;
4744}
4745
Chia-I Wu28f320b2018-05-03 11:02:56 -07004746void SurfaceFlinger::updateColorMatrixLocked() {
4747 mat4 colorMatrix;
4748 if (mGlobalSaturationFactor != 1.0f) {
4749 // Rec.709 luma coefficients
4750 float3 luminance{0.213f, 0.715f, 0.072f};
4751 luminance *= 1.0f - mGlobalSaturationFactor;
4752 mat4 saturationMatrix = mat4(
4753 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4754 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4755 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4756 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4757 );
4758 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4759 } else {
4760 colorMatrix = mClientColorMatrix * mDaltonizer();
4761 }
4762
4763 if (mCurrentState.colorMatrix != colorMatrix) {
4764 mCurrentState.colorMatrix = colorMatrix;
4765 mCurrentState.colorMatrixChanged = true;
4766 setTransactionFlags(eTransactionNeeded);
4767 }
4768}
4769
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004770status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004771#pragma clang diagnostic push
4772#pragma clang diagnostic error "-Wswitch-enum"
4773 switch (static_cast<ISurfaceComposerTag>(code)) {
4774 // These methods should at minimum make sure that the client requested
4775 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004776 case BOOT_FINISHED:
4777 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004778 case CREATE_CONNECTION:
4779 case CREATE_DISPLAY:
4780 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004781 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004782 case GET_ACTIVE_COLOR_MODE:
4783 case GET_ANIMATION_FRAME_STATS:
4784 case GET_HDR_CAPABILITIES:
4785 case SET_ACTIVE_CONFIG:
4786 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004787 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004788 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004789 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
4790 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004791 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4792 IPCThreadState* ipc = IPCThreadState::self();
4793 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4794 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004795 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004796 }
Robert Carr1db73f62016-12-21 12:58:51 -08004797 return OK;
4798 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004799 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004800 IPCThreadState* ipc = IPCThreadState::self();
4801 const int pid = ipc->getCallingPid();
4802 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004803 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4804 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004805 return PERMISSION_DENIED;
4806 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004807 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004808 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004809 // Used by apps to hook Choreographer to SurfaceFlinger.
4810 case CREATE_DISPLAY_EVENT_CONNECTION:
4811 // The following calls are currently used by clients that do not
4812 // request necessary permissions. However, they do not expose any secret
4813 // information, so it is OK to pass them.
4814 case AUTHENTICATE_SURFACE:
4815 case GET_ACTIVE_CONFIG:
4816 case GET_BUILT_IN_DISPLAY:
4817 case GET_DISPLAY_COLOR_MODES:
4818 case GET_DISPLAY_CONFIGS:
4819 case GET_DISPLAY_STATS:
4820 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4821 // Calling setTransactionState is safe, because you need to have been
4822 // granted a reference to Client* and Handle* to do anything with it.
4823 case SET_TRANSACTION_STATE:
4824 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004825 case CREATE_SCOPED_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004826 case GET_COLOR_MANAGEMENT:
Peiyong Lin0256f722018-08-31 15:45:10 -07004827 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004828 return OK;
4829 }
4830 case CAPTURE_LAYERS:
4831 case CAPTURE_SCREEN: {
4832 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004833 IPCThreadState* ipc = IPCThreadState::self();
4834 const int pid = ipc->getCallingPid();
4835 const int uid = ipc->getCallingUid();
4836 if ((uid != AID_GRAPHICS) &&
4837 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4838 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4839 return PERMISSION_DENIED;
4840 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004841 return OK;
4842 }
4843 // The following codes are deprecated and should never be allowed to access SF.
4844 case CONNECT_DISPLAY_UNUSED:
4845 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4846 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4847 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004848 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004849 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004850
4851 // These codes are used for the IBinder protocol to either interrogate the recipient
4852 // side of the transaction for its canonical interface descriptor or to dump its state.
4853 // We let them pass by default.
4854 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4855 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4856 code == IBinder::SYSPROPS_TRANSACTION) {
4857 return OK;
4858 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004859 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004860 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004861 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004862 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4863 return OK;
4864 }
4865 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4866 return PERMISSION_DENIED;
4867#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004868}
4869
Ana Krulec13be8ad2018-08-21 02:43:56 +00004870status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4871 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004872 status_t credentialCheck = CheckTransactCodeCredentials(code);
4873 if (credentialCheck != OK) {
4874 return credentialCheck;
4875 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004876
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004877 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4878 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004879 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004880 IPCThreadState* ipc = IPCThreadState::self();
4881 const int uid = ipc->getCallingUid();
4882 if (CC_UNLIKELY(uid != AID_SYSTEM
4883 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004884 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004885 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004886 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004887 return PERMISSION_DENIED;
4888 }
4889 int n;
4890 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004891 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004892 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004893 return NO_ERROR;
4894 case 1002: // SHOW_UPDATES
4895 n = data.readInt32();
4896 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004897 invalidateHwcGeometry();
4898 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004899 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004900 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004901 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004902 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004903 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004904 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004905 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004906 setTransactionFlags(
4907 eTransactionNeeded|
4908 eDisplayTransactionNeeded|
4909 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004910 return NO_ERROR;
4911 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004912 case 1006:{ // send empty update
4913 signalRefresh();
4914 return NO_ERROR;
4915 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004916 case 1008: // toggle use of hw composer
4917 n = data.readInt32();
4918 mDebugDisableHWC = n ? 1 : 0;
4919 invalidateHwcGeometry();
4920 repaintEverything();
4921 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004922 case 1009: // toggle use of transform hint
4923 n = data.readInt32();
4924 mDebugDisableTransformHint = n ? 1 : 0;
4925 invalidateHwcGeometry();
4926 repaintEverything();
4927 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004928 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004929 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004930 reply->writeInt32(0);
4931 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004932 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004933 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004934 return NO_ERROR;
4935 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004936 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004937 if (!display) {
4938 return NAME_NOT_FOUND;
4939 }
4940
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004941 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004942 return NO_ERROR;
4943 }
4944 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004945 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004946 // daltonize
4947 n = data.readInt32();
4948 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004949 case 1:
4950 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4951 break;
4952 case 2:
4953 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4954 break;
4955 case 3:
4956 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4957 break;
4958 default:
4959 mDaltonizer.setType(ColorBlindnessType::None);
4960 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004961 }
4962 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004963 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004964 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004965 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004966 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004967
4968 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004969 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004970 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004971 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004972 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004973 // apply a color matrix
4974 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004975 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004976 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004977 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004978 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004979 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004980 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004981 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004982 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004983 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004984 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004985
4986 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4987 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004988 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004989 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4990 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4991 }
4992
Chia-I Wu28f320b2018-05-03 11:02:56 -07004993 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004994 return NO_ERROR;
4995 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004996 // This is an experimental interface
4997 // Needs to be shifted to proper binder interface when we productize
4998 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004999 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005000 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005001 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005002 return NO_ERROR;
5003 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005004 case 1017: {
5005 n = data.readInt32();
5006 mForceFullDamage = static_cast<bool>(n);
5007 return NO_ERROR;
5008 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005009 case 1018: { // Modify Choreographer's phase offset
5010 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005011 if (mUseScheduler) {
5012 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5013 } else {
5014 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5015 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005016 return NO_ERROR;
5017 }
5018 case 1019: { // Modify SurfaceFlinger's phase offset
5019 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005020 if (mUseScheduler) {
5021 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5022 } else {
5023 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5024 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005025 return NO_ERROR;
5026 }
Irvel468051e2016-06-13 16:44:44 -07005027 case 1020: { // Layer updates interceptor
5028 n = data.readInt32();
5029 if (n) {
5030 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005031 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005032 }
5033 else{
5034 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005035 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005036 }
5037 return NO_ERROR;
5038 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005039 case 1021: { // Disable HWC virtual displays
5040 n = data.readInt32();
5041 mUseHwcVirtualDisplays = !n;
5042 return NO_ERROR;
5043 }
Romain Guy0147a172017-06-01 13:53:56 -07005044 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005045 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005046 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005047
Chia-I Wu28f320b2018-05-03 11:02:56 -07005048 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005049 return NO_ERROR;
5050 }
Romain Guy54f154a2017-10-24 21:40:32 +01005051 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005052 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005053 invalidateHwcGeometry();
5054 repaintEverything();
5055 return NO_ERROR;
5056 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005057 // Deprecate, use 1030 to check whether the device is color managed.
5058 case 1024: {
5059 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005060 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005061 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005062 n = data.readInt32();
5063 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005064 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005065 mTracing.enable();
5066 doTracing("tracing.enable");
5067 reply->writeInt32(NO_ERROR);
5068 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005069 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005070 status_t err = mTracing.disable();
5071 reply->writeInt32(err);
5072 }
5073 return NO_ERROR;
5074 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005075 case 1026: { // Get layer tracing status
5076 reply->writeBool(mTracing.isEnabled());
5077 return NO_ERROR;
5078 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005079 // Is a DisplayColorSetting supported?
5080 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005081 const auto display = getDefaultDisplayDevice();
5082 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005083 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005084 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005085
5086 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5087 switch (setting) {
5088 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005089 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005090 break;
5091 case DisplayColorSetting::UNMANAGED:
5092 reply->writeBool(true);
5093 break;
5094 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005095 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005096 break;
5097 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005098 reply->writeBool(
5099 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005100 break;
5101 }
5102 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005103 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005104 // Is VrFlinger active?
5105 case 1028: {
5106 Mutex::Autolock _l(mStateLock);
5107 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5108 return NO_ERROR;
5109 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005110 // Is device color managed?
5111 case 1030: {
5112 reply->writeBool(useColorManagement);
5113 return NO_ERROR;
5114 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005115 // Override default composition data space
5116 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5117 // && adb shell stop zygote && adb shell start zygote
5118 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5119 // adb shell stop zygote && adb shell start zygote
5120 case 1031: {
5121 Mutex::Autolock _l(mStateLock);
5122 n = data.readInt32();
5123 if (n) {
5124 n = data.readInt32();
5125 if (n) {
5126 Dataspace dataspace = static_cast<Dataspace>(n);
5127 if (!validateCompositionDataspace(dataspace)) {
5128 return BAD_VALUE;
5129 }
5130 mDefaultCompositionDataspace = dataspace;
5131 }
5132 n = data.readInt32();
5133 if (n) {
5134 Dataspace dataspace = static_cast<Dataspace>(n);
5135 if (!validateCompositionDataspace(dataspace)) {
5136 return BAD_VALUE;
5137 }
5138 mWideColorGamutCompositionDataspace = dataspace;
5139 }
5140 } else {
5141 // restore composition data space.
5142 mDefaultCompositionDataspace = defaultCompositionDataspace;
5143 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5144 }
5145 return NO_ERROR;
5146 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005147 }
5148 }
5149 return err;
5150}
5151
Steven Thomas6d8110b2017-08-31 18:24:21 -07005152void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005153 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005154 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005155}
5156
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005157// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5158class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005159public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005160 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5161 ~WindowDisconnector() {
5162 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005163 }
5164
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005165private:
5166 ANativeWindow* mWindow;
5167 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005168};
5169
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005170status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005171 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5172 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005173 uint32_t reqWidth, uint32_t reqHeight,
5174 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005175 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005176 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005177
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005178 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005179
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005180 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5181
Chia-I Wu20261cb2018-08-23 12:55:44 -07005182 sp<DisplayDevice> display;
5183 {
5184 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005185
Chia-I Wu20261cb2018-08-23 12:55:44 -07005186 display = getDisplayDeviceLocked(displayToken);
5187 if (!display) return BAD_VALUE;
5188
Chia-I Wucb023152018-08-28 12:57:23 -07005189 // set the requested width/height to the logical display viewport size
5190 // by default
5191 if (reqWidth == 0 || reqHeight == 0) {
5192 reqWidth = uint32_t(display->getViewport().width());
5193 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005194 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005195 }
5196
Peiyong Lin0e003c92018-09-17 11:09:51 -07005197 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5198 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005199
5200 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005201 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005202 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5203 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005204}
5205
5206status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005207 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5208 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005209 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005210 ATRACE_CALL();
5211
5212 class LayerRenderArea : public RenderArea {
5213 public:
Robert Carr578038f2018-03-09 12:25:24 -08005214 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005215 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5216 bool childrenOnly)
5217 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005218 mLayer(layer),
5219 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005220 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005221 mFlinger(flinger),
5222 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005223 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005224 Rect getBounds() const override {
5225 const Layer::State& layerState(mLayer->getDrawingState());
Vishnu Nair88a11f22018-11-28 18:30:57 -08005226 return mLayer->getBufferSize(layerState);
chaviwa76b2712017-09-20 12:02:26 -07005227 }
Marissa Wall61c58622018-07-18 10:12:20 -07005228 int getHeight() const override {
Vishnu Nair88a11f22018-11-28 18:30:57 -08005229 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005230 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005231 int getWidth() const override {
5232 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
5233 }
chaviwa76b2712017-09-20 12:02:26 -07005234 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005235 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005236 Rect getSourceCrop() const override {
5237 if (mCrop.isEmpty()) {
5238 return getBounds();
5239 } else {
5240 return mCrop;
5241 }
5242 }
Robert Carr578038f2018-03-09 12:25:24 -08005243 class ReparentForDrawing {
5244 public:
5245 const sp<Layer>& oldParent;
5246 const sp<Layer>& newParent;
5247
5248 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5249 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005250 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005251 }
Robert Carr15eae092018-03-23 13:43:53 -07005252 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005253 };
5254
5255 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005256 const Rect sourceCrop = getSourceCrop();
5257 // no need to check rotation because there is none
5258 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5259 sourceCrop.height() != getReqHeight();
5260
Robert Carr578038f2018-03-09 12:25:24 -08005261 if (!mChildrenOnly) {
5262 mTransform = mLayer->getTransform().inverse();
5263 drawLayers();
5264 } else {
5265 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005266 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005267 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5268 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005269
5270 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5271 drawLayers();
5272 }
5273 }
chaviwa76b2712017-09-20 12:02:26 -07005274
chaviwa76b2712017-09-20 12:02:26 -07005275 private:
chaviw7206d492017-11-10 16:16:12 -08005276 const sp<Layer> mLayer;
5277 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005278
5279 // In the "childrenOnly" case we reparent the children to a screenshot
5280 // layer which has no properties set and which does not draw.
5281 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005282 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005283 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005284
5285 SurfaceFlinger* mFlinger;
5286 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005287 };
5288
5289 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5290 auto parent = layerHandle->owner.promote();
5291
Robert Carr2e102c92018-10-23 12:11:15 -07005292 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005293 ALOGE("captureLayers called with a removed parent");
5294 return NAME_NOT_FOUND;
5295 }
5296
Robert Carr578038f2018-03-09 12:25:24 -08005297 const int uid = IPCThreadState::self()->getCallingUid();
5298 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5299 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5300 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5301 return PERMISSION_DENIED;
5302 }
5303
chaviw7206d492017-11-10 16:16:12 -08005304 Rect crop(sourceCrop);
5305 if (sourceCrop.width() <= 0) {
5306 crop.left = 0;
Vishnu Nair88a11f22018-11-28 18:30:57 -08005307 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005308 }
5309
5310 if (sourceCrop.height() <= 0) {
5311 crop.top = 0;
Vishnu Nair88a11f22018-11-28 18:30:57 -08005312 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005313 }
5314
5315 int32_t reqWidth = crop.width() * frameScale;
5316 int32_t reqHeight = crop.height() * frameScale;
5317
Chia-I Wu20261cb2018-08-23 12:55:44 -07005318 // really small crop or frameScale
5319 if (reqWidth <= 0) {
5320 reqWidth = 1;
5321 }
5322 if (reqHeight <= 0) {
5323 reqHeight = 1;
5324 }
5325
Peiyong Lin0e003c92018-09-17 11:09:51 -07005326 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005327
Robert Carr578038f2018-03-09 12:25:24 -08005328 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005329 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5330 if (!layer->isVisible()) {
5331 return;
Robert Carr578038f2018-03-09 12:25:24 -08005332 } else if (childrenOnly && layer == parent.get()) {
5333 return;
chaviwa76b2712017-09-20 12:02:26 -07005334 }
5335 visitor(layer);
5336 });
5337 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005338 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005339}
5340
5341status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5342 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005343 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005344 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005345 bool useIdentityTransform) {
5346 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005347
Peiyong Lin0e003c92018-09-17 11:09:51 -07005348 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005349 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5350 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005351 *outBuffer =
5352 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5353 static_cast<android_pixel_format>(reqPixelFormat), 1,
5354 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005355
5356 // This mutex protects syncFd and captureResult for communication of the return values from the
5357 // main thread back to this Binder thread
5358 std::mutex captureMutex;
5359 std::condition_variable captureCondition;
5360 std::unique_lock<std::mutex> captureLock(captureMutex);
5361 int syncFd = -1;
5362 std::optional<status_t> captureResult;
5363
Robert Carr03480e22018-01-04 16:02:06 -08005364 const int uid = IPCThreadState::self()->getCallingUid();
5365 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5366
Dominik Laskowski8c001672018-05-30 16:52:06 -07005367 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005368 // If there is a refresh pending, bug out early and tell the binder thread to try again
5369 // after the refresh.
5370 if (mRefreshPending) {
5371 ATRACE_NAME("Skipping screenshot for now");
5372 std::unique_lock<std::mutex> captureLock(captureMutex);
5373 captureResult = std::make_optional<status_t>(EAGAIN);
5374 captureCondition.notify_one();
5375 return;
5376 }
5377
5378 status_t result = NO_ERROR;
5379 int fd = -1;
5380 {
5381 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005382 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005383 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5384 useIdentityTransform, forSystem, &fd);
5385 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005386 }
5387
5388 {
5389 std::unique_lock<std::mutex> captureLock(captureMutex);
5390 syncFd = fd;
5391 captureResult = std::make_optional<status_t>(result);
5392 captureCondition.notify_one();
5393 }
5394 });
5395
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005396 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005397 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005398 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005399 while (*captureResult == EAGAIN) {
5400 captureResult.reset();
5401 result = postMessageAsync(message);
5402 if (result != NO_ERROR) {
5403 return result;
5404 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005405 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005406 }
5407 result = *captureResult;
5408 }
5409
5410 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005411 sync_wait(syncFd, -1);
5412 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005413 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005414
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005415 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005416}
5417
chaviwa76b2712017-09-20 12:02:26 -07005418void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005419 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005420 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005421 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005422
Lloyd Pique144e1162017-12-20 16:44:52 -08005423 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005424
chaviwa76b2712017-09-20 12:02:26 -07005425 const auto reqWidth = renderArea.getReqWidth();
5426 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005427 const auto sourceCrop = renderArea.getSourceCrop();
5428 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005429
Peiyong Lin0e003c92018-09-17 11:09:51 -07005430 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005431 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005432
Mathias Agopian180f10d2013-04-10 22:55:41 -07005433 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005434 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005435
5436 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005437 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005438 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005439
chaviw50da5042018-04-09 13:49:37 -07005440 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005441 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005442 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005443
chaviwa76b2712017-09-20 12:02:26 -07005444 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005445 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005446 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005447 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005448 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005449}
5450
chaviwa76b2712017-09-20 12:02:26 -07005451status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5452 TraverseLayersFunction traverseLayers,
5453 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005454 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005455 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005456 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005457 ATRACE_CALL();
5458
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005459 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005460
5461 traverseLayers([&](Layer* layer) {
5462 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5463 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005464
Robert Carr03480e22018-01-04 16:02:06 -08005465 // We allow the system server to take screenshots of secure layers for
5466 // use in situations like the Screen-rotation animation and place
5467 // the impetus on WindowManager to not persist them.
5468 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005469 ALOGW("FB is protected: PERMISSION_DENIED");
5470 return PERMISSION_DENIED;
5471 }
5472
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005473 // this binds the given EGLImage as a framebuffer for the
5474 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005475 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005476 if (bufferBond.getStatus() != NO_ERROR) {
5477 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005478 return INVALID_OPERATION;
5479 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005480
Dan Stozaabcda352017-06-01 14:37:39 -07005481 // this will in fact render into our dequeued buffer
5482 // via an FBO, which means we didn't have to create
5483 // an EGLSurface and therefore we're not
5484 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005485 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005486
Alec Mouri492bc572018-09-11 21:40:04 +00005487 base::unique_fd syncFd = getRenderEngine().flush();
5488 if (syncFd < 0) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005489 getRenderEngine().finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005490 }
Alec Mouri492bc572018-09-11 21:40:04 +00005491 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005492
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005493 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005494}
5495
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005496// ---------------------------------------------------------------------------
5497
Dan Stoza412903f2017-04-27 13:42:17 -07005498void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5499 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005500}
5501
Dan Stoza412903f2017-04-27 13:42:17 -07005502void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5503 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005504}
5505
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005506void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005507 const LayerVector::Visitor& visitor) {
5508 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005509 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005510 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005511 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005512 continue;
5513 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005514 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005515 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005516 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005517 return;
5518 }
chaviwa76b2712017-09-20 12:02:26 -07005519 if (!layer->isVisible()) {
5520 return;
5521 }
5522 visitor(layer);
5523 });
5524 }
5525}
5526
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005527}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005528
Lloyd Pique074e8122018-07-26 12:57:23 -07005529
Mathias Agopian3f844832013-08-07 21:24:32 -07005530#if defined(__gl_h_)
5531#error "don't include gl/gl.h in this file"
5532#endif
5533
5534#if defined(__gl2_h_)
5535#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005536#endif