blob: 4d685590cb4f4e59c269ae1358a1e8002e2d13a0 [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
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800382 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800383 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
Dan Stoza9e56aa02015-11-02 13:00:03 -0800737 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700738}
739
Romain Guy11d63f42017-07-20 12:47:14 -0700740void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700741 Mutex::Autolock _l(mStateLock);
742
Romain Guy11d63f42017-07-20 12:47:14 -0700743 char value[PROPERTY_VALUE_MAX];
744
745 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800746 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700747 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800748 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100749
750 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700751 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700752}
753
Mathias Agopiana67e4182012-06-19 17:26:12 -0700754void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800755 // Start boot animation service by setting a property mailbox
756 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700757 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800758 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700759 if (mStartPropertySetThread->join() != NO_ERROR) {
760 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800761 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700762}
763
Mathias Agopian875d8e12013-06-07 15:35:48 -0700764size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800765 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700766}
767
Mathias Agopian875d8e12013-06-07 15:35:48 -0700768size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800769 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700770}
771
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800772// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800773
Jamie Gennis582270d2011-08-17 18:19:00 -0700774bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800775 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800776 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800777 return authenticateSurfaceTextureLocked(bufferProducer);
778}
779
780bool SurfaceFlinger::authenticateSurfaceTextureLocked(
781 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800782 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800783 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800784}
785
Brian Anderson6b376712017-04-04 10:51:39 -0700786status_t SurfaceFlinger::getSupportedFrameTimestamps(
787 std::vector<FrameEvent>* outSupported) const {
788 *outSupported = {
789 FrameEvent::REQUESTED_PRESENT,
790 FrameEvent::ACQUIRE,
791 FrameEvent::LATCH,
792 FrameEvent::FIRST_REFRESH_START,
793 FrameEvent::LAST_REFRESH_START,
794 FrameEvent::GPU_COMPOSITION_DONE,
795 FrameEvent::DEQUEUE_READY,
796 FrameEvent::RELEASE,
797 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700798 ConditionalLock _l(mStateLock,
799 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700800 if (!getHwComposer().hasCapability(
801 HWC2::Capability::PresentFenceIsNotReliable)) {
802 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
803 }
804 return NO_ERROR;
805}
806
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700807status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
808 Vector<DisplayInfo>* configs) {
809 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700810 return BAD_VALUE;
811 }
812
Dominik Laskowski075d3172018-05-24 15:50:06 -0700813 const auto displayId = getPhysicalDisplayId(displayToken);
814 if (!displayId) {
815 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700816 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700817
Mathias Agopian8b736f12012-08-13 17:54:26 -0700818 // TODO: Not sure if display density should handled by SF any longer
819 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700820 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700821 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700822 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800823 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700824 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700825 }
826 return density;
827 }
828 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700829 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700830 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700831 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700832 return getDensityFromProperty("ro.sf.lcd_density"); }
833 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700834
Dan Stoza7f7da322014-05-02 15:26:25 -0700835 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700836
Steven Thomas6d8110b2017-08-31 18:24:21 -0700837 ConditionalLock _l(mStateLock,
838 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700839 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700840 DisplayInfo info = DisplayInfo();
841
Dan Stoza9e56aa02015-11-02 13:00:03 -0800842 float xdpi = hwConfig->getDpiX();
843 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700844
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700845 info.w = hwConfig->getWidth();
846 info.h = hwConfig->getHeight();
847 // Default display viewport to display width and height
848 info.viewportW = info.w;
849 info.viewportH = info.h;
850
Dominik Laskowski075d3172018-05-24 15:50:06 -0700851 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700852 // The density of the device is provided by a build property
853 float density = Density::getBuildDensity() / 160.0f;
854 if (density == 0) {
855 // the build doesn't provide a density -- this is wrong!
856 // use xdpi instead
857 ALOGE("ro.sf.lcd_density must be defined as a build property");
858 density = xdpi / 160.0f;
859 }
860 if (Density::getEmuDensity()) {
861 // if "qemu.sf.lcd_density" is specified, it overrides everything
862 xdpi = ydpi = density = Density::getEmuDensity();
863 density /= 160.0f;
864 }
865 info.density = density;
866
867 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700868 const auto display = getDefaultDisplayDeviceLocked();
869 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700870
871 // This is for screenrecord
872 const Rect viewport = display->getViewport();
873 if (viewport.isValid()) {
874 info.viewportW = uint32_t(viewport.getWidth());
875 info.viewportH = uint32_t(viewport.getHeight());
876 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700877 } else {
878 // TODO: where should this value come from?
879 static const int TV_DENSITY = 213;
880 info.density = TV_DENSITY / 160.0f;
881 info.orientation = 0;
882 }
883
Dan Stoza7f7da322014-05-02 15:26:25 -0700884 info.xdpi = xdpi;
885 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800886 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900887 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800888
Andy McFadden91b2ca82014-06-13 14:04:23 -0700889 // This is how far in advance a buffer must be queued for
890 // presentation at a given time. If you want a buffer to appear
891 // on the screen at time N, you must submit the buffer before
892 // (N - presentationDeadline).
893 //
894 // Normally it's one full refresh period (to give SF a chance to
895 // latch the buffer), but this can be reduced by configuring a
896 // DispSync offset. Any additional delays introduced by the hardware
897 // composer or panel must be accounted for here.
898 //
899 // We add an additional 1ms to allow for processing time and
900 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800901 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800902 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700903
904 // All non-virtual displays are currently considered secure.
905 info.secure = true;
906
Dominik Laskowski075d3172018-05-24 15:50:06 -0700907 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700908 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800909 std::swap(info.w, info.h);
910 }
911
Michael Wright28f24d02016-07-12 13:30:53 -0700912 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700913 }
914
Dan Stoza7f7da322014-05-02 15:26:25 -0700915 return NO_ERROR;
916}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700917
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700918status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
919 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700920 return BAD_VALUE;
921 }
922
Ana Krulece588e312018-09-18 12:32:24 -0700923 if (mUseScheduler) {
924 mScheduler->getDisplayStatInfo(stats);
925 } else {
926 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
927 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
928 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700929 return NO_ERROR;
930}
931
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700932int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
933 const auto display = getDisplayDevice(displayToken);
934 if (!display) {
935 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800936 return BAD_VALUE;
937 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700938
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700939 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700940}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700941
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700942void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700943 if (display->isVirtual()) {
944 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
945 return;
946 }
947
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700948 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700949 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700950 return;
951 }
952
Dominik Laskowski075d3172018-05-24 15:50:06 -0700953 const auto displayId = display->getId();
954 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700955
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700956 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700957 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700958}
959
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700960status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700961 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700962 Vector<DisplayInfo> configs;
963 getDisplayConfigs(displayToken, &configs);
964 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
965 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
966 configs.size());
967 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700968 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700969 const auto display = getDisplayDevice(displayToken);
970 if (!display) {
971 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
972 displayToken.get());
973 } else if (display->isVirtual()) {
974 ALOGW("Attempt to set active config %d for virtual display", mode);
975 } else {
976 setActiveConfigInternal(display, mode);
977 }
978 }));
979
Mathias Agopian888c8222012-08-04 21:10:38 -0700980 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700981}
Dominik Laskowski075d3172018-05-24 15:50:06 -0700982
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700983status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
984 Vector<ColorMode>* outColorModes) {
985 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700986 return BAD_VALUE;
987 }
988
Dominik Laskowski075d3172018-05-24 15:50:06 -0700989 const auto displayId = getPhysicalDisplayId(displayToken);
990 if (!displayId) {
991 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -0700992 }
993
Peiyong Lina52f0292018-03-14 17:26:31 -0700994 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700995 {
996 ConditionalLock _l(mStateLock,
997 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700998 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -0700999 }
Michael Wright28f24d02016-07-12 13:30:53 -07001000 outColorModes->clear();
1001 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1002
1003 return NO_ERROR;
1004}
1005
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001006ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1007 if (const auto display = getDisplayDevice(displayToken)) {
1008 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001009 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001010 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001011}
1012
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001013void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1014 Dataspace dataSpace, RenderIntent renderIntent) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001015 if (display->isVirtual()) {
1016 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
1017 return;
1018 }
1019
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001020 ColorMode currentMode = display->getActiveColorMode();
1021 Dataspace currentDataSpace = display->getCompositionDataSpace();
1022 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001023
Peiyong Lin38e9a562018-04-10 16:24:20 -07001024 if (mode == currentMode && dataSpace == currentDataSpace &&
1025 renderIntent == currentRenderIntent) {
1026 return;
1027 }
1028
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001029 display->setActiveColorMode(mode);
1030 display->setCompositionDataSpace(dataSpace);
1031 display->setActiveRenderIntent(renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001032
Dominik Laskowski075d3172018-05-24 15:50:06 -07001033 const auto displayId = display->getId();
1034 LOG_ALWAYS_FATAL_IF(!displayId);
1035 getHwComposer().setActiveColorMode(*displayId, mode, renderIntent);
1036
Dominik Laskowski34157762018-10-31 13:07:19 -07001037 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), display=%s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001038 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
Dominik Laskowski34157762018-10-31 13:07:19 -07001039 renderIntent, to_string(*displayId).c_str());
Michael Wright28f24d02016-07-12 13:30:53 -07001040}
1041
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001042status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001043 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001044 Vector<ColorMode> modes;
1045 getDisplayColorModes(displayToken, &modes);
1046 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1047 if (mode < ColorMode::NATIVE || !exists) {
1048 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1049 decodeColorMode(mode).c_str(), mode, displayToken.get());
1050 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001051 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001052 const auto display = getDisplayDevice(displayToken);
1053 if (!display) {
1054 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1055 decodeColorMode(mode).c_str(), mode, displayToken.get());
1056 } else if (display->isVirtual()) {
1057 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1058 decodeColorMode(mode).c_str(), mode);
1059 } else {
1060 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1061 RenderIntent::COLORIMETRIC);
1062 }
1063 }));
1064
Michael Wright28f24d02016-07-12 13:30:53 -07001065 return NO_ERROR;
1066}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001067
Svetoslavd85084b2014-03-20 10:28:31 -07001068status_t SurfaceFlinger::clearAnimationFrameStats() {
1069 Mutex::Autolock _l(mStateLock);
1070 mAnimFrameTracker.clearStats();
1071 return NO_ERROR;
1072}
1073
1074status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1075 Mutex::Autolock _l(mStateLock);
1076 mAnimFrameTracker.getStats(outStats);
1077 return NO_ERROR;
1078}
1079
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001080status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1081 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001082 Mutex::Autolock _l(mStateLock);
1083
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001084 const auto display = getDisplayDeviceLocked(displayToken);
1085 if (!display) {
1086 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001087 return BAD_VALUE;
1088 }
1089
Peiyong Linfb069302018-04-25 14:34:31 -07001090 // At this point the DisplayDeivce should already be set up,
1091 // meaning the luminance information is already queried from
1092 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001093 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001094 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1095 capabilities.getDesiredMaxLuminance(),
1096 capabilities.getDesiredMaxAverageLuminance(),
1097 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001098
1099 return NO_ERROR;
1100}
1101
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001102status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1103 ui::PixelFormat* outFormat,
1104 ui::Dataspace* outDataspace,
1105 uint8_t* outComponentMask) const {
1106 if (!outFormat || !outDataspace || !outComponentMask) {
1107 return BAD_VALUE;
1108 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001109 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001110 if (!display || !display->getId()) {
1111 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1112 return BAD_VALUE;
1113 }
1114 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1115 outDataspace, outComponentMask);
1116}
1117
Kevin DuBois74e53772018-11-19 10:52:38 -08001118status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1119 bool enable, uint8_t componentMask,
1120 uint64_t maxFrames) const {
1121 const auto display = getDisplayDevice(displayToken);
1122 if (!display || !display->getId()) {
1123 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1124 return BAD_VALUE;
1125 }
1126
1127 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1128 componentMask, maxFrames);
1129}
1130
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001131status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1132 uint64_t maxFrames, uint64_t timestamp,
1133 DisplayedFrameStats* outStats) const {
1134 const auto display = getDisplayDevice(displayToken);
1135 if (!display || !display->getId()) {
1136 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1137 return BAD_VALUE;
1138 }
1139
1140 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1141 outStats);
1142}
1143
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001144status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001145 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001146 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001147
Chia-I Wu90f669f2017-10-05 14:24:41 -07001148 if (mInjectVSyncs == enable) {
1149 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001150 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001151
Ana Krulec98b5b242018-08-10 15:03:23 -07001152 // TODO(akrulec): Part of the Injector should be refactored, so that it
1153 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001154 if (enable) {
1155 ALOGV("VSync Injections enabled");
1156 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001157 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001158 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001159 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001160 impl::EventThread::InterceptVSyncsCallback(),
1161 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001162 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001163 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001164 } else {
1165 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001166 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001167 }
1168
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001169 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001170 }));
1171
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001172 return NO_ERROR;
1173}
1174
1175status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001176 Mutex::Autolock _l(mStateLock);
1177
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001178 if (!mInjectVSyncs) {
1179 ALOGE("VSync Injections not enabled");
1180 return BAD_VALUE;
1181 }
1182 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1183 ALOGV("Injecting VSync inside SurfaceFlinger");
1184 mVSyncInjector->onInjectSyncEvent(when);
1185 }
1186 return NO_ERROR;
1187}
1188
Lloyd Pique755e3192018-01-31 16:46:15 -08001189status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1190 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001191 // Try to acquire a lock for 1s, fail gracefully
1192 const status_t err = mStateLock.timedLock(s2ns(1));
1193 const bool locked = (err == NO_ERROR);
1194 if (!locked) {
1195 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1196 return TIMED_OUT;
1197 }
1198
1199 outLayers->clear();
1200 mCurrentState.traverseInZOrder([&](Layer* layer) {
1201 outLayers->push_back(layer->getLayerDebugInfo());
1202 });
1203
1204 mStateLock.unlock();
1205 return NO_ERROR;
1206}
1207
Peiyong Linc6780972018-10-28 15:24:08 -07001208status_t SurfaceFlinger::getCompositionPreference(
1209 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1210 Dataspace* outWideColorGamutDataspace,
1211 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001212 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001213 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001214 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001215 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001216 return NO_ERROR;
1217}
1218
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001219// ----------------------------------------------------------------------------
1220
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001221sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1222 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001223 if (mUseScheduler) {
1224 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1225 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1226 } else {
1227 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1228 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001229 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001230 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1231 return mSFEventThread->createEventConnection();
1232 } else {
1233 return mEventThread->createEventConnection();
1234 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001235 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001236}
1237
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001238// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001239
1240void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001241 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001242}
1243
1244void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001245 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001246}
1247
1248void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001249 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001250}
1251
1252void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001253 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001254 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001255}
1256
1257status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001258 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001259 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001260}
1261
1262status_t SurfaceFlinger::postMessageSync(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 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001265 if (res == NO_ERROR) {
1266 msg->wait();
1267 }
1268 return res;
1269}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001270
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001271void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001272 do {
1273 waitForEvent();
1274 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001275}
1276
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001277void SurfaceFlinger::enableHardwareVsync() {
1278 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001279 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001280 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001281 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001282 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001283 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001284}
1285
Jesse Hall948fe0c2013-10-14 12:56:09 -07001286void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001287 Mutex::Autolock _l(mHWVsyncLock);
1288
Jesse Hall948fe0c2013-10-14 12:56:09 -07001289 if (makeAvailable) {
1290 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001291 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1292 if (mUseScheduler) {
1293 mScheduler->makeHWSyncAvailable(true);
1294 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001295 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001296 // Hardware vsync is not currently available, so abort the resync
1297 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001298 return;
1299 }
1300
Dominik Laskowski075d3172018-05-24 15:50:06 -07001301 const auto displayId = getInternalDisplayId();
1302 if (!displayId || !getHwComposer().isConnected(*displayId)) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001303 return;
1304 }
1305
Dominik Laskowski075d3172018-05-24 15:50:06 -07001306 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001307 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001308
Ana Krulece588e312018-09-18 12:32:24 -07001309 if (mUseScheduler) {
1310 mScheduler->setVsyncPeriod(period);
1311 } else {
1312 mPrimaryDispSync->reset();
1313 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001314
Ana Krulece588e312018-09-18 12:32:24 -07001315 if (!mPrimaryHWVsyncEnabled) {
1316 mPrimaryDispSync->beginResync();
1317 mEventControlThread->setVsyncEnabled(true);
1318 mPrimaryHWVsyncEnabled = true;
1319 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001320 }
1321}
1322
Jesse Hall948fe0c2013-10-14 12:56:09 -07001323void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001324 Mutex::Autolock _l(mHWVsyncLock);
1325 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001326 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001327 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001328 mPrimaryHWVsyncEnabled = false;
1329 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001330 if (makeUnavailable) {
1331 mHWVsyncAvailable = false;
1332 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001333}
1334
Tim Murray4a4e4a22016-04-19 16:29:23 +00001335void SurfaceFlinger::resyncWithRateLimit() {
1336 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001337
1338 // No explicit locking is needed here since EventThread holds a lock while calling this method
1339 static nsecs_t sLastResyncAttempted = 0;
1340 const nsecs_t now = systemTime();
1341 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001342 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001343 }
Dan Stoza57164302017-05-08 14:03:54 -07001344 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001345}
1346
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001347void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1348 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001349 ATRACE_NAME("SF onVsync");
1350
Steven Thomas3cfac282017-02-06 12:29:30 -08001351 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001352 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001353 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001354 return;
1355 }
1356
Dominik Laskowski075d3172018-05-24 15:50:06 -07001357 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001358 return;
1359 }
1360
Dominik Laskowski075d3172018-05-24 15:50:06 -07001361 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001362 // For now, we don't do anything with external display vsyncs.
1363 return;
1364 }
1365
Ana Krulece588e312018-09-18 12:32:24 -07001366 if (mUseScheduler) {
1367 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001368 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001369 bool needsHwVsync = false;
1370 { // Scope for the lock
1371 Mutex::Autolock _l(mHWVsyncLock);
1372 if (mPrimaryHWVsyncEnabled) {
1373 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1374 }
1375 }
1376
1377 if (needsHwVsync) {
1378 enableHardwareVsync();
1379 } else {
1380 disableHardwareVsync(false);
1381 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001382 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001383}
1384
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001385void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001386 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1387 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001388}
1389
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001390void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001391 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001392 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001393 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001394
Lloyd Piqueba04e622017-12-14 17:11:26 -08001395 // Ignore events that do not have the right sequenceId.
1396 if (sequenceId != getBE().mComposerSequenceId) {
1397 return;
1398 }
1399
Steven Thomasb02664d2017-07-26 18:48:28 -07001400 // Only lock if we're not on the main thread. This function is normally
1401 // called on a hwbinder thread, but for the primary display it's called on
1402 // the main thread with the state lock already held, so don't attempt to
1403 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001404 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001405
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001406 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001407
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001408 if (std::this_thread::get_id() == mMainThreadId) {
1409 // Process all pending hot plug events immediately if we are on the main thread.
1410 processDisplayHotplugEventsLocked();
1411 }
1412
Lloyd Piqueba04e622017-12-14 17:11:26 -08001413 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001414}
1415
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001416void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001417 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001418 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001419 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001420 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001421 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001422}
1423
Dominik Laskowski075d3172018-05-24 15:50:06 -07001424void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001425 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001426 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001427 if (const auto displayId = getInternalDisplayId()) {
1428 getHwComposer().setVsyncEnabled(*displayId,
1429 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1430 }
Mathias Agopian86303202012-07-24 22:46:10 -07001431}
1432
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001433// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001434void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001435 if (mUseScheduler) {
1436 mScheduler->disableHardwareVsync(true);
1437 } else {
1438 disableHardwareVsync(true);
1439 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001440 // Clear the drawing state so that the logic inside of
1441 // handleTransactionLocked will fire. It will determine the delta between
1442 // mCurrentState and mDrawingState and re-apply all changes when we make the
1443 // transition.
1444 mDrawingState.displays.clear();
1445 mDisplays.clear();
1446}
1447
Steven Thomas050b2c82017-03-06 11:45:16 -08001448void SurfaceFlinger::updateVrFlinger() {
1449 if (!mVrFlinger)
1450 return;
1451 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001452 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001453 return;
1454 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001455
David Sodman105b7dc2017-11-04 20:28:14 -07001456 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001457 ALOGE("Vr flinger is only supported for remote hardware composer"
1458 " service connections. Ignoring request to transition to vr"
1459 " flinger.");
1460 mVrFlingerRequestsDisplay = false;
1461 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001462 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001463
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001464 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001465
Steven Thomas0123ac62018-07-12 11:32:34 -07001466 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001467 LOG_ALWAYS_FATAL_IF(!display);
1468 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001469 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1470 // called below. Clear the reference now so we don't accidentally use it
1471 // later.
1472 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001473
Steven Thomasb02664d2017-07-26 18:48:28 -07001474 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001475 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001476 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001477
Steven Thomasb02664d2017-07-26 18:48:28 -07001478 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001479 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Pique90c115d2018-09-18 21:39:42 -07001480 getBE().mHwc = getFactory().createHWComposer(
1481 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -07001482 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001483
David Sodman105b7dc2017-11-04 20:28:14 -07001484 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1485 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001486
1487 if (vrFlingerRequestsDisplay) {
1488 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001489 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001490
1491 mVisibleRegionsDirty = true;
1492 invalidateHwcGeometry();
1493
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001494 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001495 display = getDefaultDisplayDeviceLocked();
1496 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001497 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001498
Steven Thomasb02664d2017-07-26 18:48:28 -07001499 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski075d3172018-05-24 15:50:06 -07001500 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001501 const nsecs_t period = activeConfig->getVsyncPeriod();
1502 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001503
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001504 // The present fences returned from vr_hwc are not an accurate
1505 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001506 if (mUseScheduler) {
1507 mScheduler->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() || !hasSyncFramework);
1508 } else {
1509 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1510 !hasSyncFramework);
1511 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001512
Steven Thomasb02664d2017-07-26 18:48:28 -07001513 // Use phase of 0 since phase is not known.
1514 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001515 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1516 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001517
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001518 resyncToHardwareVsync(false);
1519
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001520 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001521 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001522}
1523
Mathias Agopian4fec8732012-06-29 14:12:52 -07001524void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001525 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001526 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001527 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001528 if (mUseScheduler) {
1529 // This call is made each time SF wakes up and creates a new frame.
1530 mScheduler->incrementFrameCounter();
1531 }
Dan Stoza50182882016-07-08 12:02:20 -07001532 bool frameMissed = !mHadClientComposition &&
1533 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001534 (mPreviousPresentFence->getSignalTime() ==
1535 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001536 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001537 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001538 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001539 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001540 if (mPropagateBackpressure) {
1541 signalLayerUpdate();
1542 break;
1543 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001544 }
Dan Stoza50182882016-07-08 12:02:20 -07001545
Steven Thomas050b2c82017-03-06 11:45:16 -08001546 // Now that we're going to make it to the handleMessageTransaction()
1547 // call below it's safe to call updateVrFlinger(), which will
1548 // potentially trigger a display handoff.
1549 updateVrFlinger();
1550
Dan Stoza6b9454d2014-11-07 16:00:59 -08001551 bool refreshNeeded = handleMessageTransaction();
1552 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001553 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001554 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001555 // Signal a refresh if a transaction modified the window state,
1556 // a new buffer was latched, or if HWC has requested a full
1557 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001558 signalRefresh();
1559 }
1560 break;
1561 }
1562 case MessageQueue::REFRESH: {
1563 handleMessageRefresh();
1564 break;
1565 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001566 }
1567}
1568
Dan Stoza6b9454d2014-11-07 16:00:59 -08001569bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001570 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001571
1572 // Apply any ready transactions in the queues if there are still transactions that have not been
1573 // applied, wake up during the next vsync period and check again
1574 bool transactionNeeded = false;
1575 if (!flushTransactionQueues()) {
1576 transactionNeeded = true;
1577 }
1578
Mathias Agopian4fec8732012-06-29 14:12:52 -07001579 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001580 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001581 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001582
1583 if (transactionNeeded) {
1584 setTransactionFlags(eTransactionNeeded);
1585 }
1586
1587 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001588}
1589
Mathias Agopian4fec8732012-06-29 14:12:52 -07001590void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001591 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001592
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001593 mRefreshPending = false;
1594
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001595 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001596 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001597 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001598 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001599 for (const auto& [token, display] : mDisplays) {
1600 beginFrame(display);
1601 prepareFrame(display);
1602 doDebugFlashRegions(display, repaintEverything);
1603 doComposition(display, repaintEverything);
1604 }
1605
Adrian Roos1e1a1282017-11-01 19:05:31 +01001606 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001607 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001608
1609 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001610 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001611
Dan Stozabfbffeb2016-07-21 14:49:33 -07001612 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001613 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001614 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001615 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001616 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001617
Alec Mouri86770e52018-09-24 22:40:58 +00001618 // Setup RenderEngine sync fences if native sync is supported.
1619 if (getBE().mRenderEngine->useNativeFenceSync()) {
1620 if (mHadClientComposition) {
1621 base::unique_fd flushFence(getRenderEngine().flush());
1622 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1623 getBE().flushFence = new Fence(std::move(flushFence));
1624 } else {
1625 // Cleanup for hygiene.
1626 getBE().flushFence = Fence::NO_FENCE;
1627 }
1628 }
1629
Jorim Jaggi90535212018-05-23 23:44:06 +02001630 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001631
David Sodman7e4ae112018-02-09 15:02:28 -08001632 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001633 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001634 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001635 compositionInfo.hwc.hwcLayer = nullptr;
1636 }
David Sodmanba340492018-08-05 21:51:33 -07001637 }
David Sodman7e4ae112018-02-09 15:02:28 -08001638
1639 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001640}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001641
David Sodmanfa9b2af2017-12-24 13:28:59 -08001642
1643bool SurfaceFlinger::handleMessageInvalidate() {
1644 ATRACE_CALL();
1645 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001646}
1647
David Sodman79bba0e2018-08-05 18:07:49 -07001648void SurfaceFlinger::calculateWorkingSet() {
1649 ATRACE_CALL();
1650 ALOGV(__FUNCTION__);
1651
David Sodman79bba0e2018-08-05 18:07:49 -07001652 // build the h/w work list
1653 if (CC_UNLIKELY(mGeometryInvalid)) {
1654 mGeometryInvalid = false;
1655 for (const auto& [token, display] : mDisplays) {
1656 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001657 if (!displayId) {
1658 continue;
1659 }
David Sodman79bba0e2018-08-05 18:07:49 -07001660
Dominik Laskowski075d3172018-05-24 15:50:06 -07001661 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
1662 for (size_t i = 0; i < currentLayers.size(); i++) {
1663 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001664
Dominik Laskowski075d3172018-05-24 15:50:06 -07001665 if (!layer->hasHwcLayer(*displayId)) {
1666 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1667 layer->forceClientComposition(*displayId);
1668 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001669 }
1670 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001671
1672 layer->setGeometry(display, i);
1673 if (mDebugDisableHWC || mDebugRegion) {
1674 layer->forceClientComposition(*displayId);
1675 }
David Sodman79bba0e2018-08-05 18:07:49 -07001676 }
1677 }
1678 }
1679
1680 // Set the per-frame data
1681 for (const auto& [token, display] : mDisplays) {
1682 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001683 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001684 continue;
1685 }
1686
1687 if (mDrawingState.colorMatrixChanged) {
1688 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001689 status_t result =
1690 getHwComposer().setColorTransform(*displayId, mDrawingState.colorMatrix);
Dominik Laskowski34157762018-10-31 13:07:19 -07001691 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %s: %d",
1692 to_string(*displayId).c_str(), result);
David Sodman79bba0e2018-08-05 18:07:49 -07001693 }
1694 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1695 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001696 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001697 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1698 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1699 !display->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001700 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001701 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1702 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1703 !display->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001704 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001705 }
1706
Peiyong Lind3788632018-09-18 16:01:31 -07001707 // TODO(b/111562338) remove when composer 2.3 is shipped.
1708 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001709 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001710 }
1711
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001712 if (layer->getRoundedCornerState().radius > 0.0f) {
1713 layer->forceClientComposition(*displayId);
1714 }
1715
Dominik Laskowski075d3172018-05-24 15:50:06 -07001716 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001717 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001718 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001719 continue;
1720 }
1721
Dominik Laskowski075d3172018-05-24 15:50:06 -07001722 layer->setPerFrameData(*displayId, display->getTransform(), display->getViewport(),
1723 display->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001724 }
1725
Peiyong Lin13effd12018-07-24 17:01:47 -07001726 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001727 ColorMode colorMode;
1728 Dataspace dataSpace;
1729 RenderIntent renderIntent;
1730 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1731 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1732 }
1733 }
1734
1735 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001736
1737 for (const auto& [token, display] : mDisplays) {
1738 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001739 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001740 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001741
1742 if (displayId) {
1743 if (!layer->setHwcLayer(*displayId)) {
1744 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1745 }
1746 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001747 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001748
Dominik Laskowski05275f12018-11-01 15:03:24 -07001749 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001750 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1751 }
1752 }
David Sodman79bba0e2018-08-05 18:07:49 -07001753}
1754
David Sodmanfa9b2af2017-12-24 13:28:59 -08001755void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001756{
1757 // is debugging enabled
1758 if (CC_LIKELY(!mDebugRegion))
1759 return;
1760
David Sodmanfa9b2af2017-12-24 13:28:59 -08001761 if (display->isPoweredOn()) {
1762 // transform the dirty region into this screen's coordinate space
1763 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1764 if (!dirtyRegion.isEmpty()) {
1765 // redraw the whole screen
1766 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001767
David Sodmanfa9b2af2017-12-24 13:28:59 -08001768 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001769 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001770 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001771
Alec Mouri0a9c7b82018-11-16 13:05:25 -08001772 display->queueBuffer(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001773 }
1774 }
1775
David Sodmanfa9b2af2017-12-24 13:28:59 -08001776 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001777
1778 if (mDebugRegion > 1) {
1779 usleep(mDebugRegion * 1000);
1780 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001781
Dominik Laskowski05275f12018-11-01 15:03:24 -07001782 prepareFrame(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001783}
1784
Adrian Roos1e1a1282017-11-01 19:05:31 +01001785void SurfaceFlinger::doTracing(const char* where) {
1786 ATRACE_CALL();
1787 ATRACE_NAME(where);
1788 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001789 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001790 }
1791}
1792
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001793void SurfaceFlinger::logLayerStats() {
1794 ATRACE_CALL();
1795 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001796 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001797 if (display->isPrimary()) {
1798 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001799 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001800 }
1801 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001802
1803 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001804 }
1805}
1806
David Sodman2b406362017-12-15 13:33:47 -08001807void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001808{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001809 ATRACE_CALL();
1810 ALOGV("preComposition");
1811
David Sodman2b406362017-12-15 13:33:47 -08001812 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1813
Mathias Agopiancd60f992012-08-16 16:28:27 -07001814 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001815 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001816 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001817 needExtraInvalidate = true;
1818 }
Robert Carr2047fae2016-11-28 14:09:09 -08001819 });
1820
Mathias Agopiancd60f992012-08-16 16:28:27 -07001821 if (needExtraInvalidate) {
1822 signalLayerUpdate();
1823 }
1824}
1825
Ana Krulece588e312018-09-18 12:32:24 -07001826void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1827 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001828 // Update queue of past composite+present times and determine the
1829 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001830 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001831 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001832 while (!getBE().mCompositePresentTimes.empty()) {
1833 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001834 // Cached values should have been updated before calling this method,
1835 // which helps avoid duplicate syscalls.
1836 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1837 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1838 break;
1839 }
1840 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001841 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001842 }
1843
1844 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001845 while (getBE().mCompositePresentTimes.size() > 16) {
1846 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001847 }
1848
Ana Krulece588e312018-09-18 12:32:24 -07001849 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001850}
1851
Ana Krulece588e312018-09-18 12:32:24 -07001852void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1853 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001854 // Integer division and modulo round toward 0 not -inf, so we need to
1855 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001856 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1857 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1858 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001859
Brian Andersond0010582017-03-07 13:20:31 -08001860 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1861 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001862 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001863 }
1864
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001865 // Snap the latency to a value that removes scheduling jitter from the
1866 // composition and present times, which often have >1ms of jitter.
1867 // Reducing jitter is important if an app attempts to extrapolate
1868 // something (such as user input) to an accurate diasplay time.
1869 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1870 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001871 nsecs_t bias = stats.vsyncPeriod / 2;
1872 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1873 nsecs_t snappedCompositeToPresentLatency =
1874 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001875
David Sodman99974d22017-11-28 12:04:33 -08001876 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001877 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1878 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001879 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001880}
1881
David Sodman2b406362017-12-15 13:33:47 -08001882void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001883{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001884 ATRACE_CALL();
1885 ALOGV("postComposition");
1886
Brian Anderson3546a3f2016-07-14 11:51:14 -07001887 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001888 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001889 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001890 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001891 }
1892
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001893 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001894 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001895
David Sodman73beded2017-11-15 11:56:06 -08001896 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001897 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001898 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001899 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001900 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001901 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001902 } else {
1903 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1904 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001905
David Sodman73beded2017-11-15 11:56:06 -08001906 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001907 mPreviousPresentFence =
Dominik Laskowski075d3172018-05-24 15:50:06 -07001908 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001909 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001910 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001911
Ana Krulece588e312018-09-18 12:32:24 -07001912 DisplayStatInfo stats;
1913 if (mUseScheduler) {
1914 mScheduler->getDisplayStatInfo(&stats);
1915 } else {
1916 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1917 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
1918 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001919
David Sodman2b406362017-12-15 13:33:47 -08001920 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001921 // when we started doing work for this frame, but that should be okay
1922 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07001923 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001924 CompositorTiming compositorTiming;
1925 {
David Sodman99974d22017-11-28 12:04:33 -08001926 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1927 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001928 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001929
Robert Carr2047fae2016-11-28 14:09:09 -08001930 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001931 bool frameLatched = layer->onPostComposition(display->getId(), glCompositionDoneFenceTime,
1932 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001933 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001934 recordBufferingStats(layer->getName().string(),
1935 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001936 }
Robert Carr2047fae2016-11-28 14:09:09 -08001937 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001938
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001939 if (presentFenceTime->isValid()) {
Ana Krulece588e312018-09-18 12:32:24 -07001940 if (mUseScheduler) {
1941 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001942 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001943 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
1944 enableHardwareVsync();
1945 } else {
1946 disableHardwareVsync(false);
1947 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001948 }
1949 }
1950
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001951 if (!hasSyncFramework) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001952 if (display && getHwComposer().isConnected(*display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07001953 if (mUseScheduler) {
1954 mScheduler->enableHardwareVsync();
1955 } else {
1956 enableHardwareVsync();
1957 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001958 }
1959 }
1960
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001961 if (mAnimCompositionPending) {
1962 mAnimCompositionPending = false;
1963
Brian Anderson4e606e32017-03-16 15:34:57 -07001964 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001965 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001966 std::move(presentFenceTime));
Dominik Laskowski075d3172018-05-24 15:50:06 -07001967 } else if (display && getHwComposer().isConnected(*display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001968 // The HWC doesn't support present fences, so use the refresh
1969 // timestamp instead.
Dominik Laskowski075d3172018-05-24 15:50:06 -07001970 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001971 mAnimFrameTracker.setActualPresentTime(presentTime);
1972 }
1973 mAnimFrameTracker.advanceFrame();
1974 }
Dan Stozab90cf072015-03-05 11:05:59 -08001975
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001976 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001977 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001978 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001979 }
1980
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001981 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001982
Dominik Laskowski075d3172018-05-24 15:50:06 -07001983 if (display && getHwComposer().isConnected(*display->getId()) && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08001984 return;
1985 }
1986
1987 nsecs_t currentTime = systemTime();
1988 if (mHasPoweredOff) {
1989 mHasPoweredOff = false;
1990 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001991 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001992 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001993 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1994 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001995 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001996 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001997 }
David Sodman4a36e932017-11-07 14:29:47 -08001998 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001999 }
David Sodman4a36e932017-11-07 14:29:47 -08002000 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002001
2002 {
2003 std::lock_guard lock(mTexturePoolMutex);
2004 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
2005 if (refillCount > 0) {
2006 const size_t offset = mTexturePool.size();
2007 mTexturePool.resize(mTexturePoolSize);
2008 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2009 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2010 }
2011 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002012
Marissa Wallfda30bb2018-10-12 11:34:28 -07002013 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002014 mTransactionCompletedThread.sendCallbacks();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002015}
2016
2017void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002018 ATRACE_CALL();
2019 ALOGV("rebuildLayerStacks");
2020
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002021 // We need to clear these out now as these may be holding on to a
2022 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2023 // also holds a reference. When the set of visible layers is recomputed,
2024 // some layers may be destroyed if the only thing keeping them alive was
2025 // that list of visible layers associated with each display. The layer
2026 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2027 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2028 for (const auto& [token, display] : mDisplays) {
2029 getBE().mCompositionInfo[token].clear();
2030 }
2031
Mathias Agopiancd60f992012-08-16 16:28:27 -07002032 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002033 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002034 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002035 mVisibleRegionsDirty = false;
2036 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002037
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002038 for (const auto& pair : mDisplays) {
2039 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07002040 Region opaqueRegion;
2041 Region dirtyRegion;
2042 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002043 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07002044 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002045 const Rect bounds = display->getBounds();
2046 if (display->isPoweredOn()) {
2047 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002048
Jeff Sharkey76488112017-02-27 14:15:18 -07002049 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002050 bool hwcLayerDestroyed = false;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002051 const auto displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002052 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002053 Region drawRegion(tr.transform(
2054 layer->visibleNonTransparentRegion));
2055 drawRegion.andSelf(bounds);
2056 if (!drawRegion.isEmpty()) {
2057 layersSortedByZ.add(layer);
2058 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002059 // Clear out the HWC layer if this layer was
2060 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002061 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002062 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002063 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002064 // WM changes display->layerStack upon sleep/awake.
2065 // Here we make sure we delete the HWC layers even if
2066 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002067 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002068 }
2069
2070 // If a layer is not going to get a release fence because
2071 // it is invisible, but it is also going to release its
2072 // old buffer, add it to the list of layers needing
2073 // fences.
2074 if (hwcLayerDestroyed) {
2075 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2076 mLayersWithQueuedFrames.cend(), layer);
2077 if (found != mLayersWithQueuedFrames.cend()) {
2078 layersNeedingFences.add(layer);
2079 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002080 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002081 });
2082 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002083 display->setVisibleLayersSortedByZ(layersSortedByZ);
2084 display->setLayersNeedingFences(layersNeedingFences);
2085 display->undefinedRegion.set(bounds);
2086 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2087 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002088 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002089 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002090}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002091
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002092// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002093// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002094// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002095// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002096// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002097// The returned HDR data space is one of
2098// - Dataspace::UNKNOWN
2099// - Dataspace::BT2020_HLG
2100// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002101Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2102 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002103 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002104 *outHdrDataSpace = Dataspace::UNKNOWN;
2105
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002106 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002107 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002108 case Dataspace::V0_SCRGB:
2109 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002110 case Dataspace::BT2020:
2111 case Dataspace::BT2020_ITU:
2112 case Dataspace::BT2020_LINEAR:
2113 case Dataspace::DISPLAY_BT2020:
2114 bestDataSpace = Dataspace::DISPLAY_BT2020;
2115 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002116 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002117 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002118 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002119 case Dataspace::BT2020_PQ:
2120 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002121 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002122 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002123 case Dataspace::BT2020_HLG:
2124 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002125 // When there's mixed PQ content and HLG content, we set the HDR
2126 // data space to be BT2020_PQ and convert HLG to PQ.
2127 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2128 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002129 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002130 break;
2131 default:
2132 break;
2133 }
Romain Guy54f154a2017-10-24 21:40:32 +01002134 }
2135
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002136 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002137}
2138
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002139// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002140void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2141 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002142 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2143 *outMode = ColorMode::NATIVE;
2144 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002145 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002146 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002147 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002148
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002149 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002150 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002151
Peiyong Lindfde5112018-06-05 10:58:41 -07002152 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002153 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002154 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002155 if (isHdr) {
2156 bestDataSpace = hdrDataSpace;
2157 }
2158
Chia-I Wu0d711262018-05-21 15:19:35 -07002159 RenderIntent intent;
2160 switch (mDisplayColorSetting) {
2161 case DisplayColorSetting::MANAGED:
2162 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002163 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002164 break;
2165 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002166 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002167 break;
2168 default: // vendor display color setting
2169 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2170 break;
2171 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002172
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002173 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002174}
2175
David Sodmanfa9b2af2017-12-24 13:28:59 -08002176void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002177{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002178 bool dirty = !display->getDirtyRegion(false).isEmpty();
2179 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2180 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002181
David Sodmanfa9b2af2017-12-24 13:28:59 -08002182 // If nothing has changed (!dirty), don't recompose.
2183 // If something changed, but we don't currently have any visible layers,
2184 // and didn't when we last did a composition, then skip it this time.
2185 // The second rule does two things:
2186 // - When all layers are removed from a display, we'll emit one black
2187 // frame, then nothing more until we get new layers.
2188 // - When a display is created with a private layer stack, we won't
2189 // emit any black frames until a layer is added to the layer stack.
2190 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002191
Dominik Laskowski075d3172018-05-24 15:50:06 -07002192 const char flagPrefix[] = {'-', '+'};
2193 static_cast<void>(flagPrefix);
2194 ALOGV_IF(display->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2195 __FUNCTION__, mustRecompose ? "doing" : "skipping", display->getDebugName().c_str(),
2196 flagPrefix[dirty], flagPrefix[empty], flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002197
David Sodmanfa9b2af2017-12-24 13:28:59 -08002198 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002199
David Sodmanfa9b2af2017-12-24 13:28:59 -08002200 if (mustRecompose) {
2201 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002202 }
2203}
2204
David Sodmanfa9b2af2017-12-24 13:28:59 -08002205void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002206{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002207 if (!display->isPoweredOn()) {
2208 return;
David Sodman2b406362017-12-15 13:33:47 -08002209 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002210
Dominik Laskowski05275f12018-11-01 15:03:24 -07002211 status_t result = display->prepareFrame(getHwComposer(),
2212 getBE().mCompositionInfo[display->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002213 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
2214 display->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002215}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002216
David Sodmanfa9b2af2017-12-24 13:28:59 -08002217void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002218 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002219 ALOGV("doComposition");
2220
David Sodmanfa9b2af2017-12-24 13:28:59 -08002221 if (display->isPoweredOn()) {
2222 // transform the dirty region into this screen's coordinate space
2223 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002224
David Sodmanfa9b2af2017-12-24 13:28:59 -08002225 // repaint the framebuffer (if needed)
2226 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002227
David Sodmanfa9b2af2017-12-24 13:28:59 -08002228 display->dirtyRegion.clear();
2229 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002230 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002231 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002232}
2233
David Sodmanfa9b2af2017-12-24 13:28:59 -08002234void SurfaceFlinger::postFrame()
2235{
2236 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002237 const auto display = getDefaultDisplayDeviceLocked();
2238 if (display && getHwComposer().isConnected(*display->getId())) {
2239 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002240 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2241 logFrameStats();
2242 }
2243 }
2244}
2245
2246void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002247{
Mathias Agopian841cde52012-03-01 15:44:37 -08002248 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002249 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002250
David Sodmanfa9b2af2017-12-24 13:28:59 -08002251 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002252
David Sodmanfa9b2af2017-12-24 13:28:59 -08002253 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002254 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002255 if (displayId) {
2256 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002257 }
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002258 display->onPresentDisplayCompleted();
David Sodman15094112018-10-11 09:39:37 -07002259 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002260 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002261
Chia-I Wu7b549592017-11-15 09:14:57 -08002262 // The layer buffer from the previous frame (if any) is released
2263 // by HWC only when the release fence from this frame (if any) is
2264 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002265 if (displayId && layer->hasHwcLayer(*displayId)) {
2266 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2267 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002268 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002269
2270 // If the layer was client composited in the previous frame, we
2271 // need to merge with the previous client target acquire fence.
2272 // Since we do not track that, always merge with the current
2273 // client target acquire fence when it is available, even though
2274 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002275 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002276 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002277 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002278 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002279
David Sodman15094112018-10-11 09:39:37 -07002280 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002281 }
Chia-I Wu83806892017-11-16 10:50:20 -08002282
2283 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002284 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002285 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002286 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002287 sp<Fence> presentFence =
2288 displayId ? getBE().mHwc->getPresentFence(*displayId) : Fence::NO_FENCE;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002289 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002290 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002291 }
2292 }
2293
Dominik Laskowski075d3172018-05-24 15:50:06 -07002294 if (displayId) {
2295 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002296 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002297 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002298}
2299
Mathias Agopian87baae12012-07-31 12:38:26 -07002300void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002301{
Mathias Agopian841cde52012-03-01 15:44:37 -08002302 ATRACE_CALL();
2303
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002304 // here we keep a copy of the drawing state (that is the state that's
2305 // going to be overwritten by handleTransactionLocked()) outside of
2306 // mStateLock so that the side-effects of the State assignment
2307 // don't happen with mStateLock held (which can cause deadlocks).
2308 State drawingState(mDrawingState);
2309
Mathias Agopianca4d3602011-05-19 15:38:14 -07002310 Mutex::Autolock _l(mStateLock);
2311 const nsecs_t now = systemTime();
2312 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002313
Mathias Agopianca4d3602011-05-19 15:38:14 -07002314 // Here we're guaranteed that some transaction flags are set
2315 // so we can call handleTransactionLocked() unconditionally.
2316 // We call getTransactionFlags(), which will also clear the flags,
2317 // with mStateLock held to guarantee that mCurrentState won't change
2318 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002319
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002320 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002321 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002322 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002323
Mathias Agopianca4d3602011-05-19 15:38:14 -07002324 mLastTransactionTime = systemTime() - now;
2325 mDebugInTransaction = 0;
2326 invalidateHwcGeometry();
2327 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002328}
2329
Lloyd Piqueba04e622017-12-14 17:11:26 -08002330void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2331 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002332 const std::optional<DisplayIdentificationInfo> info =
2333 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002334
Dominik Laskowski075d3172018-05-24 15:50:06 -07002335 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002336 continue;
2337 }
2338
Lloyd Piqueba04e622017-12-14 17:11:26 -08002339 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002340 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002341 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002342 mPhysicalDisplayTokens[info->id] = new BBinder();
2343 DisplayDeviceState state;
2344 state.displayId = info->id;
2345 state.isSecure = true; // All physical displays are currently considered secure.
2346 state.displayName = info->name;
2347 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2348 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002349 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002350 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002351 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002352
Dominik Laskowski075d3172018-05-24 15:50:06 -07002353 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2354 if (index >= 0) {
2355 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2356 mInterceptor->saveDisplayDeletion(state.sequenceId);
2357 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002358 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002359 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002360 }
2361
2362 processDisplayChangesLocked();
2363 }
2364
2365 mPendingHotplugEvents.clear();
2366}
2367
Lloyd Pique99d3da52018-01-22 17:48:03 -08002368sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002369 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
2370 const DisplayDeviceState& state, const sp<DisplaySurface>& dispSurface,
2371 const sp<IGraphicBufferProducer>& producer) {
2372 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002373 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002374 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002375 creationArgs.isSecure = state.isSecure;
2376 creationArgs.displaySurface = dispSurface;
2377 creationArgs.hasWideColorGamut = false;
2378 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002379
Dominik Laskowski075d3172018-05-24 15:50:06 -07002380 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2381 creationArgs.isPrimary = isInternalDisplay;
2382
2383 if (useColorManagement && displayId) {
2384 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002385 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002386 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002387 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002388 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002389
Dominik Laskowski7e045462018-05-30 13:02:02 -07002390 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002391 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002392 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002393 }
tangrobin6753a022018-08-10 10:58:54 +08002394 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002395
Dominik Laskowski075d3172018-05-24 15:50:06 -07002396 if (displayId) {
2397 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002398 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002399 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002400 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002401
Lloyd Pique90c115d2018-09-18 21:39:42 -07002402 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002403 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002404 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002405
Lloyd Pique99d3da52018-01-22 17:48:03 -08002406 // Make sure that composition can never be stalled by a virtual display
2407 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002408 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002409 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002410 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2411 }
2412
Dominik Laskowski075d3172018-05-24 15:50:06 -07002413 creationArgs.displayInstallOrientation =
2414 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002415
Lloyd Pique99d3da52018-01-22 17:48:03 -08002416 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002417 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002418
Lloyd Pique90c115d2018-09-18 21:39:42 -07002419 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002420
2421 if (maxFrameBufferAcquiredBuffers >= 3) {
2422 nativeWindowSurface->preallocateBuffers();
2423 }
2424
2425 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002426 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002427 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002428 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002429 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002430 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002431 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002432 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002433 if (!state.isVirtual()) {
2434 LOG_ALWAYS_FATAL_IF(!displayId);
2435 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002436 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002437
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002438 display->setLayerStack(state.layerStack);
2439 display->setProjection(state.orientation, state.viewport, state.frame);
2440 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002441
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002442 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002443}
2444
Lloyd Pique347200f2017-12-14 17:00:15 -08002445void SurfaceFlinger::processDisplayChangesLocked() {
2446 // here we take advantage of Vector's copy-on-write semantics to
2447 // improve performance by skipping the transaction entirely when
2448 // know that the lists are identical
2449 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2450 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2451 if (!curr.isIdenticalTo(draw)) {
2452 mVisibleRegionsDirty = true;
2453 const size_t cc = curr.size();
2454 size_t dc = draw.size();
2455
2456 // find the displays that were removed
2457 // (ie: in drawing state but not in current state)
2458 // also handle displays that changed
2459 // (ie: displays that are in both lists)
2460 for (size_t i = 0; i < dc;) {
2461 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2462 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002463 // Save display IDs before disconnecting.
2464 const auto internalDisplayId = getInternalDisplayId();
2465 const auto externalDisplayId = getExternalDisplayId();
2466
Lloyd Pique347200f2017-12-14 17:00:15 -08002467 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002468 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2469 display->disconnect(getHwComposer());
2470 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002471 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002472 if (mUseScheduler) {
2473 mScheduler->hotplugReceived(mAppConnectionHandle,
2474 EventThread::DisplayType::Primary, false);
2475 } else {
2476 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2477 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002478 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002479 if (mUseScheduler) {
2480 mScheduler->hotplugReceived(mAppConnectionHandle,
2481 EventThread::DisplayType::External, false);
2482 } else {
2483 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2484 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002485 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002486 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002487 } else {
2488 // this display is in both lists. see if something changed.
2489 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002490 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002491 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2492 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2493 if (state_binder != draw_binder) {
2494 // changing the surface is like destroying and
2495 // recreating the DisplayDevice, so we just remove it
2496 // from the drawing state, so that it get re-added
2497 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002498 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2499 display->disconnect(getHwComposer());
2500 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002501 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002502 mDrawingState.displays.removeItemsAt(i);
2503 dc--;
2504 // at this point we must loop to the next item
2505 continue;
2506 }
2507
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002508 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002509 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002510 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002511 }
2512 if ((state.orientation != draw[i].orientation) ||
2513 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002514 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002515 }
2516 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002517 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002518 }
2519 }
2520 }
2521 ++i;
2522 }
2523
2524 // find displays that were added
2525 // (ie: in current state but not in drawing state)
2526 for (size_t i = 0; i < cc; i++) {
2527 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2528 const DisplayDeviceState& state(curr[i]);
2529
2530 sp<DisplaySurface> dispSurface;
2531 sp<IGraphicBufferProducer> producer;
2532 sp<IGraphicBufferProducer> bqProducer;
2533 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002534 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002535
Dominik Laskowski075d3172018-05-24 15:50:06 -07002536 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002537 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002538 // Virtual displays without a surface are dormant:
2539 // they have external state (layer stack, projection,
2540 // etc.) but no internal state (i.e. a DisplayDevice).
2541 if (state.surface != nullptr) {
2542 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002543 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002544 int width = 0;
2545 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2546 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2547 int height = 0;
2548 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2549 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2550 int intFormat = 0;
2551 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2552 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002553 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002554
Dominik Laskowski075d3172018-05-24 15:50:06 -07002555 displayId =
2556 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002557 }
2558
2559 // TODO: Plumb requested format back up to consumer
2560
2561 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002562 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002563 bqProducer, bqConsumer,
2564 state.displayName);
2565
2566 dispSurface = vds;
2567 producer = vds;
2568 }
2569 } else {
2570 ALOGE_IF(state.surface != nullptr,
2571 "adding a supported display, but rendering "
2572 "surface is provided (%p), ignoring it",
2573 state.surface.get());
2574
Dominik Laskowski075d3172018-05-24 15:50:06 -07002575 displayId = state.displayId;
2576 LOG_ALWAYS_FATAL_IF(!displayId);
2577 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002578 producer = bqProducer;
2579 }
2580
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002581 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002582 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002583 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002584 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002585 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002586 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002587 LOG_ALWAYS_FATAL_IF(!displayId);
2588
2589 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002590 if (mUseScheduler) {
2591 mScheduler->hotplugReceived(mAppConnectionHandle,
2592 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002593 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002594 } else {
2595 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2596 true);
2597 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002598 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002599 if (mUseScheduler) {
2600 mScheduler->hotplugReceived(mAppConnectionHandle,
2601 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002602 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002603 } else {
2604 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2605 true);
2606 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002607 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002608 }
2609 }
2610 }
2611 }
2612 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002613
2614 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002615}
2616
Mathias Agopian87baae12012-07-31 12:38:26 -07002617void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002618{
Dan Stoza7dde5992015-05-22 09:51:44 -07002619 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002620 mCurrentState.traverseInZOrder([](Layer* layer) {
2621 layer->notifyAvailableFrames();
2622 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002623
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002624 /*
2625 * Traversal of the children
2626 * (perform the transaction for each of them if needed)
2627 */
2628
Robert Carr720e5062018-07-30 17:45:14 -07002629 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002630 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002631 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002632 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002633 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002634
2635 const uint32_t flags = layer->doTransaction(0);
2636 if (flags & Layer::eVisibleRegion)
2637 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002638
2639 if (flags & Layer::eInputInfoChanged) {
2640 inputChanged = true;
2641 }
Robert Carr2047fae2016-11-28 14:09:09 -08002642 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002643 }
2644
2645 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002646 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002647 */
2648
Mathias Agopiane57f2922012-08-09 16:29:12 -07002649 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002650 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002651 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002652 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002653
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002654 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002655 // The transform hint might have changed for some layers
2656 // (either because a display has changed, or because a layer
2657 // as changed).
2658 //
2659 // Walk through all the layers in currentLayers,
2660 // and update their transform hint.
2661 //
2662 // If a layer is visible only on a single display, then that
2663 // display is used to calculate the hint, otherwise we use the
2664 // default display.
2665 //
2666 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2667 // the hint is set before we acquire a buffer from the surface texture.
2668 //
2669 // NOTE: layer transactions have taken place already, so we use their
2670 // drawing state. However, SurfaceFlinger's own transaction has not
2671 // happened yet, so we must use the current state layer list
2672 // (soon to become the drawing state list).
2673 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002674 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002675 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002676 bool first = true;
2677 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002678 // NOTE: we rely on the fact that layers are sorted by
2679 // layerStack first (so we don't have to traverse the list
2680 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002681 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002682 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002683 currentlayerStack = layerStack;
2684 // figure out if this layerstack is mirrored
2685 // (more than one display) if so, pick the default display,
2686 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002687 hintDisplay = nullptr;
2688 for (const auto& [token, display] : mDisplays) {
2689 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2690 if (hintDisplay) {
2691 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002692 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002693 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002694 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002695 }
2696 }
2697 }
2698 }
Chet Haase91d25932013-04-11 15:24:55 -07002699
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002700 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002701 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2702 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002703
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002704 // could be null when this layer is using a layerStack
2705 // that is not visible on any display. Also can occur at
2706 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002707 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002708 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002709
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002710 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002711 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002712 if (hintDisplay) {
2713 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002714 }
Robert Carr2047fae2016-11-28 14:09:09 -08002715
2716 first = false;
2717 });
Mathias Agopian84300952012-11-21 16:02:13 -08002718 }
2719
2720
Mathias Agopian3559b072012-08-15 13:46:03 -07002721 /*
2722 * Perform our own transaction if needed
2723 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002724
2725 if (mLayersAdded) {
2726 mLayersAdded = false;
2727 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002728 mVisibleRegionsDirty = true;
2729 }
2730
2731 // some layers might have been removed, so
2732 // we need to update the regions they're exposing.
2733 if (mLayersRemoved) {
2734 mLayersRemoved = false;
2735 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002736 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002737 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002738 // this layer is not visible anymore
2739 // TODO: we could traverse the tree from front to back and
2740 // compute the actual visible region
2741 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002742 Region visibleReg;
2743 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002744 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002745 }
Robert Carr2047fae2016-11-28 14:09:09 -08002746 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002747 }
2748
2749 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002750
Vishnu Nairde19f852018-12-18 16:11:53 -08002751 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002752 updateInputWindows();
2753 }
2754
Riley Andrews03414a12014-07-01 14:22:59 -07002755 updateCursorAsync();
2756}
2757
Robert Carr720e5062018-07-30 17:45:14 -07002758void SurfaceFlinger::updateInputWindows() {
2759 ATRACE_CALL();
2760
Vishnu Nairde19f852018-12-18 16:11:53 -08002761 if (mInputFlinger == nullptr) {
2762 return;
2763 }
2764
Robert Carr720e5062018-07-30 17:45:14 -07002765 Vector<InputWindowInfo> inputHandles;
2766
2767 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2768 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002769 // When calculating the screen bounds we ignore the transparent region since it may
2770 // result in an unwanted offset.
2771 inputHandles.add(layer->fillInputInfo(
2772 layer->computeScreenBounds(false /* reduceTransparentRegion */)));
Robert Carr720e5062018-07-30 17:45:14 -07002773 }
2774 });
2775 mInputFlinger->setInputWindows(inputHandles);
2776}
2777
Riley Andrews03414a12014-07-01 14:22:59 -07002778void SurfaceFlinger::updateCursorAsync()
2779{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002780 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002781 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002782 continue;
2783 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002784
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002785 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2786 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002787 }
2788 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002789}
2790
chaviw61626f22018-11-15 16:26:27 -08002791void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2792 if (layer->hasReadyFrame()) {
2793 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2794 if (layer->shouldPresentNow(expectedPresentTime)) {
2795 bool ignored = false;
2796 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
2797 }
2798 }
2799 layer->releasePendingBuffer(systemTime());
2800}
2801
Mathias Agopian4fec8732012-06-29 14:12:52 -07002802void SurfaceFlinger::commitTransaction()
2803{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002804 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002805 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002806 for (const auto& l : mLayersPendingRemoval) {
2807 recordBufferingStats(l->getName().string(),
2808 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002809
2810 // We need to release the HWC layers when the Layer is removed
2811 // from the current state otherwise the HWC layer just continues
2812 // showing at its last configured state until we eventually
2813 // abandon the buffer queue.
2814 if (l->isRemovedFromCurrentState()) {
Robert Carr3aee9892018-11-07 12:53:41 -08002815 l->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* child) {
chaviw61626f22018-11-15 16:26:27 -08002816 child->destroyHwcLayersForAllDisplays();
2817 latchAndReleaseBuffer(child);
Robert Carr3aee9892018-11-07 12:53:41 -08002818 });
Robert Carr2e102c92018-10-23 12:11:15 -07002819 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002820 }
2821 mLayersPendingRemoval.clear();
2822 }
2823
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002824 // If this transaction is part of a window animation then the next frame
2825 // we composite should be considered an animation as well.
2826 mAnimCompositionPending = mAnimTransactionPending;
2827
Mathias Agopian4fec8732012-06-29 14:12:52 -07002828 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002829 // clear the "changed" flags in current state
2830 mCurrentState.colorMatrixChanged = false;
2831
Robert Carr1f0a16a2016-10-24 16:27:39 -07002832 mDrawingState.traverseInZOrder([](Layer* layer) {
2833 layer->commitChildList();
2834 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002835 mTransactionPending = false;
2836 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002837 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002838}
2839
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002840void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2841 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002842 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002843 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002844
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002845 Region aboveOpaqueLayers;
2846 Region aboveCoveredLayers;
2847 Region dirty;
2848
Mathias Agopian87baae12012-07-31 12:38:26 -07002849 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002850
Robert Carr2047fae2016-11-28 14:09:09 -08002851 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Jesse Hall01e29052013-02-19 16:13:35 -08002852 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002853 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002854 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002855 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002856
Mathias Agopianab028732010-03-16 16:41:46 -07002857 /*
2858 * opaqueRegion: area of a surface that is fully opaque.
2859 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002860 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002861
2862 /*
2863 * visibleRegion: area of a surface that is visible on screen
2864 * and not fully transparent. This is essentially the layer's
2865 * footprint minus the opaque regions above it.
2866 * Areas covered by a translucent surface are considered visible.
2867 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002868 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002869
2870 /*
2871 * coveredRegion: area of a surface that is covered by all
2872 * visible regions above it (which includes the translucent areas).
2873 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002875
Jesse Halla8026d22012-09-25 13:25:04 -07002876 /*
2877 * transparentRegion: area of a surface that is hinted to be completely
2878 * transparent. This is only used to tell when the layer has no visible
2879 * non-transparent regions and can be removed from the layer list. It
2880 * does not affect the visibleRegion of this layer or any layers
2881 * beneath it. The hint may not be correct if apps don't respect the
2882 * SurfaceView restrictions (which, sadly, some don't).
2883 */
2884 Region transparentRegion;
2885
Mathias Agopianab028732010-03-16 16:41:46 -07002886
2887 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002888 if (CC_LIKELY(layer->isVisible())) {
Ady Abraham83729882018-12-07 12:26:48 -08002889 const bool translucent = !layer->isDrawingOpaque();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002890 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07002891
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002892 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002893 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002894 if (!visibleRegion.isEmpty()) {
2895 // Remove the transparent area from the visible region
2896 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002897 if (tr.preserveRects()) {
2898 // transform the transparent region
Ady Abraham83729882018-12-07 12:26:48 -08002899 transparentRegion =
2900 tr.transform(layer->getDrawingActiveTransparentRegion());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002901 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002902 // transformation too complex, can't do the
2903 // transparent region optimization.
2904 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002905 }
Mathias Agopianab028732010-03-16 16:41:46 -07002906 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002907
Mathias Agopianab028732010-03-16 16:41:46 -07002908 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002909 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002910 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002911 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002912 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002913 // the opaque region is the layer's footprint
2914 opaqueRegion = visibleRegion;
2915 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002916 }
2917 }
2918
Robert Carre5f4f692018-01-12 13:12:28 -08002919 if (visibleRegion.isEmpty()) {
2920 layer->clearVisibilityRegions();
2921 return;
2922 }
2923
Mathias Agopianab028732010-03-16 16:41:46 -07002924 // Clip the covered region to the visible region
2925 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2926
2927 // Update aboveCoveredLayers for next (lower) layer
2928 aboveCoveredLayers.orSelf(visibleRegion);
2929
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002930 // subtract the opaque region covered by the layers above us
2931 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002932
2933 // compute this layer's dirty region
2934 if (layer->contentDirty) {
2935 // we need to invalidate the whole region
2936 dirty = visibleRegion;
2937 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002938 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002939 layer->contentDirty = false;
2940 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002941 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002942 * the exposed region consists of two components:
2943 * 1) what's VISIBLE now and was COVERED before
2944 * 2) what's EXPOSED now less what was EXPOSED before
2945 *
2946 * note that (1) is conservative, we start with the whole
2947 * visible region but only keep what used to be covered by
2948 * something -- which mean it may have been exposed.
2949 *
2950 * (2) handles areas that were not covered by anything but got
2951 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002952 */
Mathias Agopianab028732010-03-16 16:41:46 -07002953 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002954 const Region oldVisibleRegion = layer->visibleRegion;
2955 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002956 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2957 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002958 }
2959 dirty.subtractSelf(aboveOpaqueLayers);
2960
2961 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002962 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002963
Mathias Agopianab028732010-03-16 16:41:46 -07002964 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002965 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002966
Jesse Halla8026d22012-09-25 13:25:04 -07002967 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002968 layer->setVisibleRegion(visibleRegion);
2969 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002970 layer->setVisibleNonTransparentRegion(
2971 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002972 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002973
Mathias Agopian87baae12012-07-31 12:38:26 -07002974 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002975}
2976
Chia-I Wuab0c3192017-08-01 11:29:00 -07002977void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002978 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002979 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2980 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002981 }
2982 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002983}
2984
Dan Stoza6b9454d2014-11-07 16:00:59 -08002985bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002986{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002987 ALOGV("handlePageFlip");
2988
Brian Andersond6927fb2016-07-23 23:37:30 -07002989 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002990
Mathias Agopian4fec8732012-06-29 14:12:52 -07002991 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002992 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002993 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002994
2995 // Store the set of layers that need updates. This set must not change as
2996 // buffers are being latched, as this could result in a deadlock.
2997 // Example: Two producers share the same command stream and:
2998 // 1.) Layer 0 is latched
2999 // 2.) Layer 0 gets a new frame
3000 // 2.) Layer 1 gets a new frame
3001 // 3.) Layer 1 is latched.
3002 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3003 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003004 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003005 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003006 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003007 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3008 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003009 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003010 } else {
3011 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003012 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003013 } else {
3014 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003015 }
Robert Carr2047fae2016-11-28 14:09:09 -08003016 });
3017
Dan Stoza9e56aa02015-11-02 13:00:03 -08003018 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri86770e52018-09-24 22:40:58 +00003019 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
Dan Stozaee44edd2015-03-23 15:50:23 -07003020 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003021 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07003022 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06003023 newDataLatched = true;
3024 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003025 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003026
Alec Mouri86770e52018-09-24 22:40:58 +00003027 // Clear the renderengine fence here...
3028 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3029 // clear instead of sp::clear.
3030 getBE().flushFence = Fence::NO_FENCE;
3031
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003032 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003033
Vishnu Nairde19f852018-12-18 16:11:53 -08003034 if (visibleRegions) {
3035 // Update input window info if the layer receives its first buffer.
3036 updateInputWindows();
3037 }
3038
Dan Stoza6b9454d2014-11-07 16:00:59 -08003039 // If we will need to wake up at some time in the future to deal with a
3040 // queued frame that shouldn't be displayed during this vsync period, wake
3041 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003042 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003043 signalLayerUpdate();
3044 }
3045
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003046 // enter boot animation on first buffer latch
3047 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3048 ALOGI("Enter boot animation");
3049 mBootStage = BootStage::BOOTANIMATION;
3050 }
3051
Dan Stoza6b9454d2014-11-07 16:00:59 -08003052 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003053 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003054}
3055
Mathias Agopianad456f92011-01-13 17:53:01 -08003056void SurfaceFlinger::invalidateHwcGeometry()
3057{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003058 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003059}
3060
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003061void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& display,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003062 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003063 // We only need to actually compose the display if:
3064 // 1) It is being handled by hardware composer, which may need this to
3065 // keep its virtual display state machine in sync, or
3066 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski34157762018-10-31 13:07:19 -07003067 if (!display->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003068 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003069 return;
3070 }
3071
Dan Stoza9e56aa02015-11-02 13:00:03 -08003072 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003073 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003074
3075 // swap buffers (presentation)
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003076 display->queueBuffer(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003077}
3078
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003079bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003080 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003081
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003082 const Region bounds(display->bounds());
3083 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003084 const auto displayId = display->getId();
3085 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003086 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003087
Peiyong Lind3788632018-09-18 16:01:31 -07003088 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003089 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003090
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003091 // Framebuffer will live in this scope for GPU composition.
3092 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
3093
Dan Stoza9e56aa02015-11-02 13:00:03 -08003094 if (hasClientComposition) {
3095 ALOGV("hasClientComposition");
3096
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003097 sp<GraphicBuffer> buf = display->dequeueBuffer();
3098
3099 if (buf == nullptr) {
3100 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3101 "client composition for this frame",
3102 display->getDisplayName().c_str());
3103 return false;
3104 }
3105
3106 // Bind the framebuffer in this scope.
3107 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3108 buf->getNativeBuffer());
3109
3110 if (fbo->getStatus() != NO_ERROR) {
3111 ALOGW("Binding buffer for display [%s] failed with status: %d",
3112 display->getDisplayName().c_str(), fbo->getStatus());
3113 return false;
3114 }
3115
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003116 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003117 if (display->hasWideColorGamut()) {
3118 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003119 }
3120 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003121 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003122 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003123
Dominik Laskowski7e045462018-05-30 13:02:02 -07003124 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003125 const bool skipClientColorTransform =
3126 getBE().mHwc
3127 ->hasDisplayCapability(displayId,
3128 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003129
Peiyong Lind3788632018-09-18 16:01:31 -07003130 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003131 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3132 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003133 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003134 }
3135
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003136 display->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003137
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003138 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003139 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003140 // when using overlays, we assume a fully transparent framebuffer
3141 // NOTE: we could reduce how much we need to clear, for instance
3142 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003143 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003144 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003145 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003146 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003147 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003148 // we're left with the letterbox region
3149 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003150 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003151
3152 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003153 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003154
Mathias Agopianb9494d52012-04-18 02:28:45 -07003155 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003156 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003157 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003158 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003159 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003160 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003161
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003162 const Rect& bounds = display->getBounds();
3163 const Rect& scissor = display->getScissor();
3164 if (scissor != bounds) {
3165 // scissor doesn't match the screen's dimensions, so we
3166 // need to clear everything outside of it and enable
3167 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003168
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003169 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003170 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003171 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003172 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003173
Mathias Agopian85d751c2012-08-29 16:59:24 -07003174 /*
3175 * and then, render the layers targeted at the framebuffer
3176 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003177
Dan Stoza9e56aa02015-11-02 13:00:03 -08003178 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003179 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003180 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003181 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003182 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003183 displayTransform.transform(layer->visibleRegion)));
3184 ALOGV("Layer: %s", layer->getName().string());
3185 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003186 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003187 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003188 case HWC2::Composition::Cursor:
3189 case HWC2::Composition::Device:
3190 case HWC2::Composition::Sideband:
3191 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003192 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003193 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Ady Abraham83729882018-12-07 12:26:48 -08003194 layer->isDrawingOpaque() && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003195 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003196 // never clear the very first layer since we're
3197 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003198 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003199 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003200 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003201 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003202 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003203 if (layer->hasColorTransform()) {
3204 mat4 tmpMatrix;
3205 if (applyColorMatrix) {
3206 tmpMatrix = mDrawingState.colorMatrix;
3207 }
3208 tmpMatrix *= layer->getColorTransform();
Peiyong Lind3788632018-09-18 16:01:31 -07003209 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
Marissa Wall713b63f2018-10-17 15:42:43 -07003329bool SurfaceFlinger::flushTransactionQueues() {
3330 Mutex::Autolock _l(mStateLock);
3331 auto it = mTransactionQueues.begin();
3332 while (it != mTransactionQueues.end()) {
3333 auto& [applyToken, transactionQueue] = *it;
3334
3335 while (!transactionQueue.empty()) {
3336 const auto& [states, displays, flags] = transactionQueue.front();
3337 if (composerStateContainsUnsignaledFences(states)) {
3338 break;
3339 }
chaviw273171b2018-12-26 11:46:30 -08003340 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003341 transactionQueue.pop();
3342 }
3343
3344 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3345 }
3346 return mTransactionQueues.empty();
3347}
3348
chaviwca27f252018-02-06 16:46:39 -08003349bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3350 for (const ComposerState& state : states) {
3351 // Here we need to check that the interface we're given is indeed
3352 // one of our own. A malicious client could give us a nullptr
3353 // IInterface, or one of its own or even one of our own but a
3354 // different type. All these situations would cause us to crash.
3355 if (state.client == nullptr) {
3356 return true;
3357 }
3358
3359 sp<IBinder> binder = IInterface::asBinder(state.client);
3360 if (binder == nullptr) {
3361 return true;
3362 }
3363
3364 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3365 return true;
3366 }
3367 }
3368 return false;
3369}
3370
Marissa Wall713b63f2018-10-17 15:42:43 -07003371bool SurfaceFlinger::composerStateContainsUnsignaledFences(const Vector<ComposerState>& states) {
3372 for (const ComposerState& state : states) {
3373 const layer_state_t& s = state.state;
3374 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3375 continue;
3376 }
3377 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
3378 return true;
3379 }
3380 }
3381 return false;
3382}
3383
3384void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3385 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003386 const sp<IBinder>& applyToken,
3387 const InputWindowCommands& inputWindowCommands) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003388 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003389 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003390
chaviwca27f252018-02-06 16:46:39 -08003391 if (containsAnyInvalidClientState(states)) {
3392 return;
3393 }
3394
Marissa Wall713b63f2018-10-17 15:42:43 -07003395 // If its TransactionQueue already has a pending TransactionState or if it is pending
3396 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
3397 composerStateContainsUnsignaledFences(states)) {
3398 mTransactionQueues[applyToken].emplace(states, displays, flags);
3399 setTransactionFlags(eTransactionNeeded);
3400 return;
3401 }
3402
chaviw273171b2018-12-26 11:46:30 -08003403 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003404}
3405
3406void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003407 const Vector<DisplayState>& displays, uint32_t flags,
3408 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003409 uint32_t transactionFlags = 0;
3410
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003411 if (flags & eAnimation) {
3412 // For window updates that are part of an animation we must wait for
3413 // previous animation "frames" to be handled.
3414 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003415 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003416 if (CC_UNLIKELY(err != NO_ERROR)) {
3417 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003418 // caller after a few seconds.
3419 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3420 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003421 mAnimTransactionPending = false;
3422 break;
3423 }
3424 }
3425 }
3426
chaviwca27f252018-02-06 16:46:39 -08003427 for (const DisplayState& display : displays) {
3428 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003429 }
3430
Marissa Walle2ffb422018-10-12 11:33:52 -07003431 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003432 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003433 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003434 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003435 // If the state doesn't require a traversal and there are callbacks, send them now
3436 if (!(clientStateFlags & eTraversalNeeded)) {
3437 mTransactionCompletedThread.sendCallbacks();
3438 }
3439 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003440
3441 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3442 // as destroyed should only occur after setting all other states. This is to allow for a
3443 // child re-parent to happen before marking its original parent as destroyed (which would
3444 // then mark the child as destroyed).
3445 for (const ComposerState& state : states) {
3446 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003447 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003448
chaviw273171b2018-12-26 11:46:30 -08003449 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3450
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003451 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3452 // anyway. This can be used as a flush mechanism for previous async transactions.
3453 // Empty animation transaction can be used to simulate back-pressure, so also force a
3454 // transaction for empty animation transactions.
3455 if (transactionFlags == 0 &&
3456 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003457 transactionFlags = eTransactionNeeded;
3458 }
3459
Mathias Agopian386aa982011-11-07 21:58:03 -08003460 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003461 if (mInterceptor->isEnabled()) {
3462 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003463 }
Irvel468051e2016-06-13 16:44:44 -07003464
Mathias Agopian386aa982011-11-07 21:58:03 -08003465 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003466 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3467 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003468 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003469
3470 // if this is a synchronous transaction, wait for it to take effect
3471 // before returning.
3472 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003473 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003474 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003475 if (flags & eAnimation) {
3476 mAnimTransactionPending = true;
3477 }
3478 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003479 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3480 if (CC_UNLIKELY(err != NO_ERROR)) {
3481 // just in case something goes wrong in SF, return to the
3482 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003483 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3484 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003485 break;
3486 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003487 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003488 }
3489}
3490
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003491uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3492 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3493 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003494
Mathias Agopiane57f2922012-08-09 16:29:12 -07003495 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003496 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3497
3498 const uint32_t what = s.what;
3499 if (what & DisplayState::eSurfaceChanged) {
3500 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3501 state.surface = s.surface;
3502 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003503 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003504 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003505 if (what & DisplayState::eLayerStackChanged) {
3506 if (state.layerStack != s.layerStack) {
3507 state.layerStack = s.layerStack;
3508 flags |= eDisplayTransactionNeeded;
3509 }
3510 }
3511 if (what & DisplayState::eDisplayProjectionChanged) {
3512 if (state.orientation != s.orientation) {
3513 state.orientation = s.orientation;
3514 flags |= eDisplayTransactionNeeded;
3515 }
3516 if (state.frame != s.frame) {
3517 state.frame = s.frame;
3518 flags |= eDisplayTransactionNeeded;
3519 }
3520 if (state.viewport != s.viewport) {
3521 state.viewport = s.viewport;
3522 flags |= eDisplayTransactionNeeded;
3523 }
3524 }
3525 if (what & DisplayState::eDisplaySizeChanged) {
3526 if (state.width != s.width) {
3527 state.width = s.width;
3528 flags |= eDisplayTransactionNeeded;
3529 }
3530 if (state.height != s.height) {
3531 state.height = s.height;
3532 flags |= eDisplayTransactionNeeded;
3533 }
3534 }
3535
Mathias Agopiane57f2922012-08-09 16:29:12 -07003536 return flags;
3537}
3538
Robert Carrd4ae7f32018-06-07 16:10:57 -07003539bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3540 IPCThreadState* ipc = IPCThreadState::self();
3541 const int pid = ipc->getCallingPid();
3542 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003543 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003544 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003545 return false;
3546 }
3547 return true;
3548}
3549
chaviwca27f252018-02-06 16:46:39 -08003550uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3551 const layer_state_t& s = composerState.state;
3552 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3553
Mathias Agopian13127d82013-03-05 17:47:11 -08003554 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003555 if (layer == nullptr) {
3556 return 0;
3557 }
3558
chaviw8b3871a2017-11-01 17:41:01 -07003559 uint32_t flags = 0;
3560
Garfield Tan8a3083e2018-12-03 13:21:07 -08003561 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003562 bool geometryAppliesWithResize =
3563 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003564
3565 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3566 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003567 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003568 layer->pushPendingState();
3569 }
3570
chaviw8b3871a2017-11-01 17:41:01 -07003571 if (what & layer_state_t::ePositionChanged) {
3572 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3573 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003574 }
chaviw8b3871a2017-11-01 17:41:01 -07003575 }
3576 if (what & layer_state_t::eLayerChanged) {
3577 // NOTE: index needs to be calculated before we update the state
3578 const auto& p = layer->getParent();
3579 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003580 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003581 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003582 mCurrentState.layersSortedByZ.removeAt(idx);
3583 mCurrentState.layersSortedByZ.add(layer);
3584 // we need traversal (state changed)
3585 // AND transaction (list changed)
3586 flags |= eTransactionNeeded|eTraversalNeeded;
3587 }
chaviw8b3871a2017-11-01 17:41:01 -07003588 } else {
3589 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003590 flags |= eTransactionNeeded|eTraversalNeeded;
3591 }
3592 }
chaviw8b3871a2017-11-01 17:41:01 -07003593 }
3594 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003595 // NOTE: index needs to be calculated before we update the state
3596 const auto& p = layer->getParent();
3597 if (p == nullptr) {
3598 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3599 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3600 mCurrentState.layersSortedByZ.removeAt(idx);
3601 mCurrentState.layersSortedByZ.add(layer);
3602 // we need traversal (state changed)
3603 // AND transaction (list changed)
3604 flags |= eTransactionNeeded|eTraversalNeeded;
3605 }
3606 } else {
3607 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3608 flags |= eTransactionNeeded|eTraversalNeeded;
3609 }
chaviw8b3871a2017-11-01 17:41:01 -07003610 }
3611 }
3612 if (what & layer_state_t::eSizeChanged) {
3613 if (layer->setSize(s.w, s.h)) {
3614 flags |= eTraversalNeeded;
3615 }
3616 }
3617 if (what & layer_state_t::eAlphaChanged) {
3618 if (layer->setAlpha(s.alpha))
3619 flags |= eTraversalNeeded;
3620 }
3621 if (what & layer_state_t::eColorChanged) {
3622 if (layer->setColor(s.color))
3623 flags |= eTraversalNeeded;
3624 }
Peiyong Lind3788632018-09-18 16:01:31 -07003625 if (what & layer_state_t::eColorTransformChanged) {
3626 if (layer->setColorTransform(s.colorTransform)) {
3627 flags |= eTraversalNeeded;
3628 }
3629 }
chaviw8b3871a2017-11-01 17:41:01 -07003630 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003631 // TODO: b/109894387
3632 //
3633 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3634 // rotation. To see the problem observe that if we have a square parent, and a child
3635 // of the same size, then we rotate the child 45 degrees around it's center, the child
3636 // must now be cropped to a non rectangular 8 sided region.
3637 //
3638 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3639 // private API, and the WindowManager only uses rotation in one case, which is on a top
3640 // level layer in which cropping is not an issue.
3641 //
3642 // However given that abuse of rotation matrices could lead to surfaces extending outside
3643 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3644 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3645 // transformations.
3646 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003647 flags |= eTraversalNeeded;
3648 }
3649 if (what & layer_state_t::eTransparentRegionChanged) {
3650 if (layer->setTransparentRegionHint(s.transparentRegion))
3651 flags |= eTraversalNeeded;
3652 }
3653 if (what & layer_state_t::eFlagsChanged) {
3654 if (layer->setFlags(s.flags, s.mask))
3655 flags |= eTraversalNeeded;
3656 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003657 if (what & layer_state_t::eCropChanged_legacy) {
3658 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003659 flags |= eTraversalNeeded;
3660 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003661 if (what & layer_state_t::eCornerRadiusChanged) {
3662 if (layer->setCornerRadius(s.cornerRadius))
3663 flags |= eTraversalNeeded;
3664 }
chaviw8b3871a2017-11-01 17:41:01 -07003665 if (what & layer_state_t::eLayerStackChanged) {
3666 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3667 // We only allow setting layer stacks for top level layers,
3668 // everything else inherits layer stack from its parent.
3669 if (layer->hasParent()) {
3670 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3671 layer->getName().string());
3672 } else if (idx < 0) {
3673 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3674 "that also does not appear in the top level layer list. Something"
3675 " has gone wrong.", layer->getName().string());
3676 } else if (layer->setLayerStack(s.layerStack)) {
3677 mCurrentState.layersSortedByZ.removeAt(idx);
3678 mCurrentState.layersSortedByZ.add(layer);
3679 // we need traversal (state changed)
3680 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003681 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003682 }
3683 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003684 if (what & layer_state_t::eDeferTransaction_legacy) {
3685 if (s.barrierHandle_legacy != nullptr) {
3686 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3687 } else if (s.barrierGbp_legacy != nullptr) {
3688 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003689 if (authenticateSurfaceTextureLocked(gbp)) {
3690 const auto& otherLayer =
3691 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003692 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003693 } else {
3694 ALOGE("Attempt to defer transaction to to an"
3695 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003696 }
3697 }
chaviw8b3871a2017-11-01 17:41:01 -07003698 // We don't trigger a traversal here because if no other state is
3699 // changed, we don't want this to cause any more work
3700 }
3701 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003702 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003703 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003704 if (!hadParent) {
3705 mCurrentState.layersSortedByZ.remove(layer);
3706 }
chaviw8b3871a2017-11-01 17:41:01 -07003707 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003708 }
chaviw8b3871a2017-11-01 17:41:01 -07003709 }
3710 if (what & layer_state_t::eReparentChildren) {
3711 if (layer->reparentChildren(s.reparentHandle)) {
3712 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003713 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003714 }
chaviw8b3871a2017-11-01 17:41:01 -07003715 if (what & layer_state_t::eDetachChildren) {
3716 layer->detachChildren();
3717 }
3718 if (what & layer_state_t::eOverrideScalingModeChanged) {
3719 layer->setOverrideScalingMode(s.overrideScalingMode);
3720 // We don't trigger a traversal here because if no other state is
3721 // changed, we don't want this to cause any more work
3722 }
Marissa Wall61c58622018-07-18 10:12:20 -07003723 if (what & layer_state_t::eTransformChanged) {
3724 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3725 }
3726 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3727 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3728 flags |= eTraversalNeeded;
3729 }
3730 if (what & layer_state_t::eCropChanged) {
3731 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3732 }
Marissa Wall861616d2018-10-22 12:52:23 -07003733 if (what & layer_state_t::eFrameChanged) {
3734 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3735 }
Marissa Wall61c58622018-07-18 10:12:20 -07003736 if (what & layer_state_t::eBufferChanged) {
3737 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3738 }
3739 if (what & layer_state_t::eAcquireFenceChanged) {
3740 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3741 }
3742 if (what & layer_state_t::eDataspaceChanged) {
3743 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3744 }
3745 if (what & layer_state_t::eHdrMetadataChanged) {
3746 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3747 }
3748 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3749 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3750 }
3751 if (what & layer_state_t::eApiChanged) {
3752 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3753 }
3754 if (what & layer_state_t::eSidebandStreamChanged) {
3755 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3756 }
Robert Carr720e5062018-07-30 17:45:14 -07003757 if (what & layer_state_t::eInputInfoChanged) {
3758 layer->setInputInfo(s.inputInfo);
3759 flags |= eTraversalNeeded;
3760 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003761 std::vector<sp<CallbackHandle>> callbackHandles;
3762 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3763 mTransactionCompletedThread.run();
3764 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3765 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3766 }
3767 }
3768 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3769 // Do not put anything that updates layer state or modifies flags after
3770 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003771 return flags;
3772}
3773
chaviwca27f252018-02-06 16:46:39 -08003774void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3775 const layer_state_t& state = composerState.state;
3776 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3777
3778 sp<Layer> layer(client->getLayerUser(state.surface));
3779 if (layer == nullptr) {
3780 return;
3781 }
3782
chaviwca27f252018-02-06 16:46:39 -08003783 if (state.what & layer_state_t::eDestroySurface) {
3784 removeLayerLocked(mStateLock, layer);
3785 }
3786}
3787
chaviw273171b2018-12-26 11:46:30 -08003788uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3789 uint32_t flags = 0;
3790 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3791 flags |= eTraversalNeeded;
3792 }
3793
3794 mInputWindowCommands.merge(inputWindowCommands);
3795 return flags;
3796}
3797
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003798status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003799 const String8& name,
3800 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003801 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003802 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003803 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003804{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003805 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003806 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003807 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003808 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003809 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003810
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003811 status_t result = NO_ERROR;
3812
3813 sp<Layer> layer;
3814
Cody Northropbc755282017-03-31 12:00:08 -06003815 String8 uniqueName = getUniqueLayerName(name);
3816
Mathias Agopian3165cc22012-08-08 19:42:09 -07003817 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003818 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003819 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3820 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003821
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003822 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003823 case ISurfaceComposerClient::eFXSurfaceBufferState:
3824 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3825 break;
chaviw13fdc492017-06-27 12:40:18 -07003826 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003827 // check if buffer size is set for color layer.
3828 if (w > 0 || h > 0) {
3829 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3830 int(w), int(h));
3831 return BAD_VALUE;
3832 }
3833
chaviw13fdc492017-06-27 12:40:18 -07003834 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003835 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003836 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003837 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003838 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003839 // check if buffer size is set for container layer.
3840 if (w > 0 || h > 0) {
3841 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3842 int(w), int(h));
3843 return BAD_VALUE;
3844 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07003845 result = createContainerLayer(client,
3846 uniqueName, w, h, flags,
3847 handle, &layer);
3848 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003849 default:
3850 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003851 break;
3852 }
3853
Dan Stoza7d89d062015-04-30 13:29:25 -07003854 if (result != NO_ERROR) {
3855 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003856 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003857
Chia-I Wuab0c3192017-08-01 11:29:00 -07003858 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3859 // TODO b/64227542
3860 if (windowType == 441731) {
3861 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3862 layer->setPrimaryDisplayOnly();
3863 }
3864
Albert Chaulk479c60c2017-01-27 14:21:34 -05003865 layer->setInfo(windowType, ownerUid);
3866
Robert Carr1f0a16a2016-10-24 16:27:39 -07003867 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003868 if (result != NO_ERROR) {
3869 return result;
3870 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003871 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003872
3873 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003874 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003875}
3876
Cody Northropbc755282017-03-31 12:00:08 -06003877String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3878{
3879 bool matchFound = true;
3880 uint32_t dupeCounter = 0;
3881
3882 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3883 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3884
Dan Stoza436ccf32018-06-21 12:10:12 -07003885 // Grab the state lock since we're accessing mCurrentState
3886 Mutex::Autolock lock(mStateLock);
3887
Cody Northropbc755282017-03-31 12:00:08 -06003888 // Loop over layers until we're sure there is no matching name
3889 while (matchFound) {
3890 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003891 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003892 if (layer->getName() == uniqueName) {
3893 matchFound = true;
3894 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3895 }
3896 });
3897 }
3898
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003899 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3900 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003901
3902 return uniqueName;
3903}
3904
Marissa Wallfd668622018-05-10 10:21:13 -07003905status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3906 uint32_t w, uint32_t h, uint32_t flags,
3907 PixelFormat& format, sp<IBinder>* handle,
3908 sp<IGraphicBufferProducer>* gbp,
3909 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003910 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003911 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003912 case PIXEL_FORMAT_TRANSPARENT:
3913 case PIXEL_FORMAT_TRANSLUCENT:
3914 format = PIXEL_FORMAT_RGBA_8888;
3915 break;
3916 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003917 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003918 break;
3919 }
3920
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003921 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003922 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003923 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003924 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003925 *handle = layer->getHandle();
3926 *gbp = layer->getProducer();
3927 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003928 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003929
Marissa Wallfd668622018-05-10 10:21:13 -07003930 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003931 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003932}
3933
Marissa Wall61c58622018-07-18 10:12:20 -07003934status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3935 uint32_t w, uint32_t h, uint32_t flags,
3936 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003937 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003938 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003939 *handle = layer->getHandle();
3940 *outLayer = layer;
3941
3942 return NO_ERROR;
3943}
3944
chaviw13fdc492017-06-27 12:40:18 -07003945status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003946 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003947 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003948{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003949 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003950 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003951 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003952}
3953
Robert Carr6b3f6c52018-08-13 13:05:17 -07003954status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3955 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3956 sp<IBinder>* handle, sp<Layer>* outLayer)
3957{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003958 *outLayer =
3959 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003960 *handle = (*outLayer)->getHandle();
3961 return NO_ERROR;
3962}
3963
3964
Mathias Agopianac9fa422013-02-11 16:40:36 -08003965status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003966{
Robert Carr9524cb32017-02-13 11:32:32 -08003967 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003968 status_t err = NO_ERROR;
3969 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003970 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003971 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003972 err = removeLayer(l);
3973 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3974 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003975 }
3976 return err;
3977}
3978
Robert Carr2e102c92018-10-23 12:11:15 -07003979void SurfaceFlinger::markLayerPendingRemovalLocked(const Mutex&, const sp<Layer>& layer) {
3980 mLayersPendingRemoval.add(layer);
3981 mLayersRemoved = true;
3982 setTransactionFlags(eTransactionNeeded);
3983}
3984
Robert Carr695d5282018-12-18 15:27:58 -08003985void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003986{
Robert Carr2e102c92018-10-23 12:11:15 -07003987 Mutex::Autolock lock(mStateLock);
3988 markLayerPendingRemovalLocked(mStateLock, layer);
Robert Carr695d5282018-12-18 15:27:58 -08003989 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003990}
3991
Mathias Agopianb60314a2012-04-10 22:09:54 -07003992// ---------------------------------------------------------------------------
3993
Andy McFadden13a082e2012-08-24 10:16:42 -07003994void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003995 const auto displayToken = getInternalDisplayToken();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003996 if (!displayToken) return;
3997
Jesse Hall01e29052013-02-19 16:13:35 -08003998 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003999 Vector<ComposerState> state;
4000 Vector<DisplayState> displays;
4001 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004002 d.what = DisplayState::eDisplayProjectionChanged |
4003 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004004 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08004005 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004006 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004007 d.frame.makeInvalid();
4008 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004009 d.width = 0;
4010 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004011 displays.add(d);
chaviw273171b2018-12-26 11:46:30 -08004012 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004013
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004014 const auto display = getDisplayDevice(displayToken);
4015 if (!display) return;
4016
Dominik Laskowskie9774092018-12-11 10:04:24 -08004017 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004018
Dominik Laskowski075d3172018-05-24 15:50:06 -07004019 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08004020 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07004021 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004022
Brian Andersond0010582017-03-07 13:20:31 -08004023 // Use phase of 0 since phase is not known.
4024 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07004025 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
4026 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004027}
4028
4029void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004030 // Async since we may be called from the main thread.
4031 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004032}
4033
Dominik Laskowskie9774092018-12-11 10:04:24 -08004034void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004035 if (display->isVirtual()) {
4036 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004037 return;
4038 }
4039
Dominik Laskowski075d3172018-05-24 15:50:06 -07004040 const auto displayId = display->getId();
4041 LOG_ALWAYS_FATAL_IF(!displayId);
4042
Dominik Laskowski34157762018-10-31 13:07:19 -07004043 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004044
4045 int currentMode = display->getPowerMode();
4046 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004047 return;
4048 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004049
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004050 display->setPowerMode(mode);
4051
Lloyd Pique4dccc412018-01-22 17:21:36 -08004052 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004053 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004054 }
4055
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004056 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004057 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004058 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004059 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004060 if (mUseScheduler) {
4061 mScheduler->onScreenAcquired(mAppConnectionHandle);
4062 } else {
4063 mEventThread->onScreenAcquired();
4064 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004065 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004066 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004067
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004068 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004069 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004070 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004071
4072 struct sched_param param = {0};
4073 param.sched_priority = 1;
4074 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4075 ALOGW("Couldn't set SCHED_FIFO on display on");
4076 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004077 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004078 // Turn off the display
4079 struct sched_param param = {0};
4080 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4081 ALOGW("Couldn't set SCHED_OTHER on display off");
4082 }
4083
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004084 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004085 if (mUseScheduler) {
4086 mScheduler->disableHardwareVsync(true);
4087 } else {
4088 disableHardwareVsync(true); // also cancels any in-progress resync
4089 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004090 if (mUseScheduler) {
4091 mScheduler->onScreenReleased(mAppConnectionHandle);
4092 } else {
4093 mEventThread->onScreenReleased();
4094 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004095 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004096
Dominik Laskowski075d3172018-05-24 15:50:06 -07004097 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004098 mVisibleRegionsDirty = true;
4099 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004100 } else if (mode == HWC_POWER_MODE_DOZE ||
4101 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004102 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004103 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004104 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004105 if (mUseScheduler) {
4106 mScheduler->onScreenAcquired(mAppConnectionHandle);
4107 } else {
4108 mEventThread->onScreenAcquired();
4109 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004110 resyncToHardwareVsync(true);
4111 }
4112 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4113 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004114 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004115 if (mUseScheduler) {
4116 mScheduler->disableHardwareVsync(true);
4117 } else {
4118 disableHardwareVsync(true); // also cancels any in-progress resync
4119 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004120 if (mUseScheduler) {
4121 mScheduler->onScreenReleased(mAppConnectionHandle);
4122 } else {
4123 mEventThread->onScreenReleased();
4124 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004125 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004126 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004127 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004128 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004129 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004130 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004131
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004132 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004133 mTimeStats->setPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004134 }
4135
Dominik Laskowski34157762018-10-31 13:07:19 -07004136 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004137}
4138
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004139void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004140 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004141 const auto display = getDisplayDevice(displayToken);
4142 if (!display) {
4143 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4144 displayToken.get());
4145 } else if (display->isVirtual()) {
4146 ALOGW("Attempt to set power mode %d for virtual display", mode);
4147 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004148 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004149 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004150 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004151}
4152
4153// ---------------------------------------------------------------------------
4154
Lloyd Pique755e3192018-01-31 16:46:15 -08004155status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4156 NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004157 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004158
Mathias Agopianbd115332013-04-18 16:41:04 -07004159 IPCThreadState* ipc = IPCThreadState::self();
4160 const int pid = ipc->getCallingPid();
4161 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004162
Mathias Agopianbd115332013-04-18 16:41:04 -07004163 if ((uid != AID_SHELL) &&
4164 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004165 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4166 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004167 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004168 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004169 // (this would indicate SF is stuck, but we want to be able to
4170 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004171 status_t err = mStateLock.timedLock(s2ns(1));
4172 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004173 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004174 StringAppendF(&result,
4175 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4176 "(no locks held)\n",
4177 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004178 }
4179
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004180 bool dumpAll = true;
4181 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004182 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004183
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004184 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004185 if ((index < numArgs) &&
4186 (args[index] == String16("--list"))) {
4187 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004188 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004189 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004190 }
4191
4192 if ((index < numArgs) &&
4193 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004194 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004195 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004196 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004197 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004198
4199 if ((index < numArgs) &&
4200 (args[index] == String16("--latency-clear"))) {
4201 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004202 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004203 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004204 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004205
4206 if ((index < numArgs) &&
4207 (args[index] == String16("--dispsync"))) {
4208 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004209 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004210 dumpAll = false;
4211 }
Dan Stozab90cf072015-03-05 11:05:59 -08004212
4213 if ((index < numArgs) &&
4214 (args[index] == String16("--static-screen"))) {
4215 index++;
4216 dumpStaticScreenStats(result);
4217 dumpAll = false;
4218 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004219
4220 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004221 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004222 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004223 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004224 dumpAll = false;
4225 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004226
4227 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4228 index++;
4229 dumpWideColorInfo(result);
4230 dumpAll = false;
4231 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004232
4233 if ((index < numArgs) &&
4234 (args[index] == String16("--enable-layer-stats"))) {
4235 index++;
4236 mLayerStats.enable();
4237 dumpAll = false;
4238 }
4239
4240 if ((index < numArgs) &&
4241 (args[index] == String16("--disable-layer-stats"))) {
4242 index++;
4243 mLayerStats.disable();
4244 dumpAll = false;
4245 }
4246
4247 if ((index < numArgs) &&
4248 (args[index] == String16("--clear-layer-stats"))) {
4249 index++;
4250 mLayerStats.clear();
4251 dumpAll = false;
4252 }
4253
4254 if ((index < numArgs) &&
4255 (args[index] == String16("--dump-layer-stats"))) {
4256 index++;
4257 mLayerStats.dump(result);
4258 dumpAll = false;
4259 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004260
4261 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004262 (args[index] == String16("--frame-composition"))) {
4263 index++;
4264 dumpFrameCompositionInfo(result);
4265 dumpAll = false;
4266 }
4267
4268 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004269 (args[index] == String16("--display-identification"))) {
4270 index++;
4271 dumpDisplayIdentificationData(result);
4272 dumpAll = false;
4273 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004274
4275 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4276 index++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004277 mTimeStats->parseArgs(asProto, args, index, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004278 dumpAll = false;
4279 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004280 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004281
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004282 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004283 if (asProto) {
4284 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4285 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4286 } else {
4287 dumpAllLocked(args, index, result);
4288 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004289 }
4290
Mathias Agopian9795c422009-08-26 16:36:26 -07004291 if (locked) {
4292 mStateLock.unlock();
4293 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004294 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004295 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004296 return NO_ERROR;
4297}
4298
Yiwei Zhang5434a782018-12-05 18:06:32 -08004299void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */, size_t& /* index */,
4300 std::string& result) const {
4301 mCurrentState.traverseInZOrder(
4302 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004303}
4304
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004305void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004306 std::string& result) const {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004307 String8 name;
4308 if (index < args.size()) {
4309 name = String8(args[index]);
4310 index++;
4311 }
4312
Dominik Laskowski075d3172018-05-24 15:50:06 -07004313 if (const auto displayId = getInternalDisplayId();
4314 displayId && getHwComposer().isConnected(*displayId)) {
4315 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004316 const nsecs_t period = activeConfig->getVsyncPeriod();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004317 StringAppendF(&result, "%" PRId64 "\n", period);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004318 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004319
4320 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004321 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004322 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004323 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004324 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004325 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004326 }
Robert Carr2047fae2016-11-28 14:09:09 -08004327 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004328 }
4329}
4330
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004331void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004332 std::string& /* result */) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004333 String8 name;
4334 if (index < args.size()) {
4335 name = String8(args[index]);
4336 index++;
4337 }
4338
Robert Carr2047fae2016-11-28 14:09:09 -08004339 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004340 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004341 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004342 }
Robert Carr2047fae2016-11-28 14:09:09 -08004343 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004344
Svetoslavd85084b2014-03-20 10:28:31 -07004345 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004346}
4347
Jamie Gennis6547ff42013-07-16 20:12:42 -07004348// This should only be called from the main thread. Otherwise it would need
4349// the lock and should use mCurrentState rather than mDrawingState.
4350void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004351 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004352 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004353 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004354
4355 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4356}
4357
Yiwei Zhang5434a782018-12-05 18:06:32 -08004358void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004359 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004360
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004361 if (isLayerTripleBufferingDisabled())
4362 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004363
Yiwei Zhang5434a782018-12-05 18:06:32 -08004364 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4365 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4366 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4367 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4368 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4369 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004370 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004371}
4372
Yiwei Zhang5434a782018-12-05 18:06:32 -08004373void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4374 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004375 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4376 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004377 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004378 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004379 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004380 }
David Sodman4a36e932017-11-07 14:29:47 -08004381 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004382 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004383 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004384 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4385 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004386}
4387
Dan Stozae77c7662016-05-13 11:37:28 -07004388void SurfaceFlinger::recordBufferingStats(const char* layerName,
4389 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004390 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4391 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004392 for (const auto& segment : history) {
4393 if (!segment.usedThirdBuffer) {
4394 stats.twoBufferTime += segment.totalTime;
4395 }
4396 if (segment.occupancyAverage < 1.0f) {
4397 stats.doubleBufferedTime += segment.totalTime;
4398 } else if (segment.occupancyAverage < 2.0f) {
4399 stats.tripleBufferedTime += segment.totalTime;
4400 }
4401 ++stats.numSegments;
4402 stats.totalTime += segment.totalTime;
4403 }
4404}
4405
Yiwei Zhang5434a782018-12-05 18:06:32 -08004406void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4407 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004408
4409 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4410 const size_t count = currentLayers.size();
4411 for (size_t i=0 ; i<count ; i++) {
4412 currentLayers[i]->dumpFrameEvents(result);
4413 }
4414}
4415
Yiwei Zhang5434a782018-12-05 18:06:32 -08004416void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004417 result.append("Buffering stats:\n");
4418 result.append(" [Layer name] <Active time> <Two buffer> "
4419 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004420 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004421 typedef std::tuple<std::string, float, float, float> BufferTuple;
4422 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004423 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004424 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004425 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004426 if (stats.numSegments == 0) {
4427 continue;
4428 }
4429 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4430 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4431 stats.totalTime;
4432 float doubleBufferRatio = static_cast<float>(
4433 stats.doubleBufferedTime) / stats.totalTime;
4434 float tripleBufferRatio = static_cast<float>(
4435 stats.tripleBufferedTime) / stats.totalTime;
4436 sorted.insert({activeTime, {name, twoBufferRatio,
4437 doubleBufferRatio, tripleBufferRatio}});
4438 }
4439 for (const auto& sortedPair : sorted) {
4440 float activeTime = sortedPair.first;
4441 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004442 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4443 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004444 }
4445 result.append("\n");
4446}
4447
Yiwei Zhang5434a782018-12-05 18:06:32 -08004448void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
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) {
4452 continue;
4453 }
4454 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004455 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004456 continue;
4457 }
4458
Yiwei Zhang5434a782018-12-05 18:06:32 -08004459 StringAppendF(&result,
4460 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4461 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004462 uint8_t port;
4463 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004464 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004465 result.append("no identification data\n");
4466 continue;
4467 }
4468
4469 if (!isEdid(data)) {
4470 result.append("unknown identification data: ");
4471 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004472 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004473 }
4474 result.append("\n");
4475 continue;
4476 }
4477
4478 const auto edid = parseEdid(data);
4479 if (!edid) {
4480 result.append("invalid EDID: ");
4481 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004482 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004483 }
4484 result.append("\n");
4485 continue;
4486 }
4487
Yiwei Zhang5434a782018-12-05 18:06:32 -08004488 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004489 result.append(edid->displayName.data(), edid->displayName.length());
4490 result.append("\"\n");
4491 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004492}
4493
Yiwei Zhang5434a782018-12-05 18:06:32 -08004494void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4495 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4496 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4497 StringAppendF(&result, "DisplayColorSetting: %s\n",
4498 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004499
4500 // TODO: print out if wide-color mode is active or not
4501
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004502 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004503 const auto displayId = display->getId();
4504 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004505 continue;
4506 }
4507
Yiwei Zhang5434a782018-12-05 18:06:32 -08004508 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004509 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004510 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004511 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004512 }
4513
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004514 ColorMode currentMode = display->getActiveColorMode();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004515 StringAppendF(&result, " Current color mode: %s (%d)\n",
4516 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004517 }
4518 result.append("\n");
4519}
4520
Yiwei Zhang5434a782018-12-05 18:06:32 -08004521void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004522 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004523 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4524 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004525 continue;
4526 }
4527
Dominik Laskowski05275f12018-11-01 15:03:24 -07004528 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004529 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4530 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004531 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004532 compositionInfo.dump(result, nullptr);
4533 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004534 }
4535 }
David Sodman7e4ae112018-02-09 15:02:28 -08004536}
4537
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004538LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004539 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004540 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4541 const State& state = useDrawing ? mDrawingState : mCurrentState;
4542 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004543 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004544 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004545 });
4546
4547 return layersProto;
4548}
4549
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004550LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004551 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004552
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004553 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004554 resolution->set_w(display.getWidth());
4555 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004556
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004557 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4558 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4559 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004560
Dominik Laskowski075d3172018-05-24 15:50:06 -07004561 const auto displayId = display.getId();
4562 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004563 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004564 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004565 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004566 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004567 }
4568 });
4569
4570 return layersProto;
4571}
4572
Mathias Agopian74d211a2013-04-22 16:55:35 +02004573void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004574 std::string& result) const {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004575 bool colorize = false;
4576 if (index < args.size()
4577 && (args[index] == String16("--color"))) {
4578 colorize = true;
4579 index++;
4580 }
4581
4582 Colorizer colorizer(colorize);
4583
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004584 // figure out if we're stuck somewhere
4585 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004586 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004587 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4588
4589 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004590 * Dump library configuration.
4591 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004592
4593 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004594 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004595 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004596 appendSfConfigString(result);
4597 appendUiConfigString(result);
4598 appendGuiConfigString(result);
4599 result.append("\n");
4600
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004601 result.append("\nDisplay identification data:\n");
4602 dumpDisplayIdentificationData(result);
4603
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004604 result.append("\nWide-Color information:\n");
4605 dumpWideColorInfo(result);
4606
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004607 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004608 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004609 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004610 result.append(SyncFeatures::getInstance().toString());
4611 result.append("\n");
4612
Andy McFadden41d67d72014-04-25 16:58:34 -07004613 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004614 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004615 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004616
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004617 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4618 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004619 if (const auto displayId = getInternalDisplayId();
4620 displayId && getHwComposer().isConnected(*displayId)) {
4621 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004622 StringAppendF(&result,
4623 "Display %s: app phase %" PRId64 " ns, "
4624 "sf phase %" PRId64 " ns, "
4625 "early app phase %" PRId64 " ns, "
4626 "early sf phase %" PRId64 " ns, "
4627 "early app gl phase %" PRId64 " ns, "
4628 "early sf gl phase %" PRId64 " ns, "
4629 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4630 to_string(*displayId).c_str(), vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
4631 appEarlyOffset, sfEarlyOffset, appEarlyGlOffset, sfEarlyGlOffset,
4632 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004633 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004634 result.append("\n");
4635
Dan Stozab90cf072015-03-05 11:05:59 -08004636 // Dump static screen stats
4637 result.append("\n");
4638 dumpStaticScreenStats(result);
4639 result.append("\n");
4640
Yiwei Zhang5434a782018-12-05 18:06:32 -08004641 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004642
Dan Stozae77c7662016-05-13 11:37:28 -07004643 dumpBufferingStats(result);
4644
Andy McFadden4803b742012-09-24 19:07:20 -07004645 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004646 * Dump the visible layer list
4647 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004648 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004649 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4650 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4651 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004652 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004653
Chia-I Wu2f884132018-09-13 15:17:58 -07004654 {
4655 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4656 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004657 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004658 result.append("\n");
4659 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004660
David Sodman7e4ae112018-02-09 15:02:28 -08004661 result.append("\nFrame-Composition information:\n");
4662 dumpFrameCompositionInfo(result);
4663 result.append("\n");
4664
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004665 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004666 * Dump Display state
4667 */
4668
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004669 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004670 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004671 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004672 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004673 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004674 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004675 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004676
4677 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004678 * Dump SurfaceFlinger global state
4679 */
4680
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004681 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004682 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004683 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004684
David Sodmanbc815282017-11-05 18:57:52 -08004685 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004686
Dominik Laskowski075d3172018-05-24 15:50:06 -07004687 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004688 display->undefinedRegion.dump(result, "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004689 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4690 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004691 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004692 StringAppendF(&result,
4693 " transaction-flags : %08x\n"
4694 " gpu_to_cpu_unsupported : %d\n",
4695 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004696
Dominik Laskowski075d3172018-05-24 15:50:06 -07004697 if (const auto displayId = getInternalDisplayId();
4698 displayId && getHwComposer().isConnected(*displayId)) {
4699 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004700 StringAppendF(&result,
4701 " refresh-rate : %f fps\n"
4702 " x-dpi : %f\n"
4703 " y-dpi : %f\n",
4704 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4705 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004706 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004707
Yiwei Zhang5434a782018-12-05 18:06:32 -08004708 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004709
Yiwei Zhang5434a782018-12-05 18:06:32 -08004710 StringAppendF(&result, " use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004711 /*
4712 * VSYNC state
4713 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004714 if (mUseScheduler) {
4715 mScheduler->dump(mAppConnectionHandle, result);
4716 } else {
4717 mEventThread->dump(result);
4718 }
Dan Stozae22aec72016-08-01 13:20:59 -07004719 result.append("\n");
4720
4721 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004722 * Tracing state
4723 */
4724 mTracing.dump(result);
4725 result.append("\n");
4726
4727 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004728 * HWC layer minidump
4729 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004730 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004731 const auto displayId = display->getId();
4732 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004733 continue;
4734 }
4735
Yiwei Zhang5434a782018-12-05 18:06:32 -08004736 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004737 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004738 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004739 result.append("\n");
4740 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004741
4742 /*
4743 * Dump HWComposer state
4744 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004745 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004746 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004747 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004748 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004749 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004750 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004751
4752 /*
4753 * Dump gralloc state
4754 */
4755 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4756 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004757
4758 /*
4759 * Dump VrFlinger state if in use.
4760 */
4761 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4762 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004763 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004764 result.append("\n");
4765 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004766}
4767
Dominik Laskowski075d3172018-05-24 15:50:06 -07004768const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004769 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004770 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004771 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004772 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004773 }
4774 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004775
Dominik Laskowski34157762018-10-31 13:07:19 -07004776 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004777 static const Vector<sp<Layer>> empty;
4778 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004779}
4780
Keun young Park63f165f2012-08-31 10:53:36 -07004781bool SurfaceFlinger::startDdmConnection()
4782{
4783 void* libddmconnection_dso =
4784 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4785 if (!libddmconnection_dso) {
4786 return false;
4787 }
4788 void (*DdmConnection_start)(const char* name);
4789 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004790 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004791 if (!DdmConnection_start) {
4792 dlclose(libddmconnection_dso);
4793 return false;
4794 }
4795 (*DdmConnection_start)(getServiceName());
4796 return true;
4797}
4798
Chia-I Wu28f320b2018-05-03 11:02:56 -07004799void SurfaceFlinger::updateColorMatrixLocked() {
4800 mat4 colorMatrix;
4801 if (mGlobalSaturationFactor != 1.0f) {
4802 // Rec.709 luma coefficients
4803 float3 luminance{0.213f, 0.715f, 0.072f};
4804 luminance *= 1.0f - mGlobalSaturationFactor;
4805 mat4 saturationMatrix = mat4(
4806 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4807 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4808 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4809 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4810 );
4811 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4812 } else {
4813 colorMatrix = mClientColorMatrix * mDaltonizer();
4814 }
4815
4816 if (mCurrentState.colorMatrix != colorMatrix) {
4817 mCurrentState.colorMatrix = colorMatrix;
4818 mCurrentState.colorMatrixChanged = true;
4819 setTransactionFlags(eTransactionNeeded);
4820 }
4821}
4822
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004823status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004824#pragma clang diagnostic push
4825#pragma clang diagnostic error "-Wswitch-enum"
4826 switch (static_cast<ISurfaceComposerTag>(code)) {
4827 // These methods should at minimum make sure that the client requested
4828 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004829 case BOOT_FINISHED:
4830 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004831 case CREATE_CONNECTION:
4832 case CREATE_DISPLAY:
4833 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004834 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004835 case GET_ACTIVE_COLOR_MODE:
4836 case GET_ANIMATION_FRAME_STATS:
4837 case GET_HDR_CAPABILITIES:
4838 case SET_ACTIVE_CONFIG:
4839 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004840 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004841 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004842 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004843 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4844 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004845 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4846 IPCThreadState* ipc = IPCThreadState::self();
4847 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4848 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004849 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004850 }
Robert Carr1db73f62016-12-21 12:58:51 -08004851 return OK;
4852 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004853 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004854 IPCThreadState* ipc = IPCThreadState::self();
4855 const int pid = ipc->getCallingPid();
4856 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004857 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4858 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004859 return PERMISSION_DENIED;
4860 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004861 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004862 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004863 // Used by apps to hook Choreographer to SurfaceFlinger.
4864 case CREATE_DISPLAY_EVENT_CONNECTION:
4865 // The following calls are currently used by clients that do not
4866 // request necessary permissions. However, they do not expose any secret
4867 // information, so it is OK to pass them.
4868 case AUTHENTICATE_SURFACE:
4869 case GET_ACTIVE_CONFIG:
4870 case GET_BUILT_IN_DISPLAY:
4871 case GET_DISPLAY_COLOR_MODES:
4872 case GET_DISPLAY_CONFIGS:
4873 case GET_DISPLAY_STATS:
4874 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4875 // Calling setTransactionState is safe, because you need to have been
4876 // granted a reference to Client* and Handle* to do anything with it.
4877 case SET_TRANSACTION_STATE:
4878 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004879 case CREATE_SCOPED_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004880 case GET_COLOR_MANAGEMENT:
Peiyong Lin0256f722018-08-31 15:45:10 -07004881 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004882 return OK;
4883 }
4884 case CAPTURE_LAYERS:
4885 case CAPTURE_SCREEN: {
4886 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004887 IPCThreadState* ipc = IPCThreadState::self();
4888 const int pid = ipc->getCallingPid();
4889 const int uid = ipc->getCallingUid();
4890 if ((uid != AID_GRAPHICS) &&
4891 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4892 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4893 return PERMISSION_DENIED;
4894 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004895 return OK;
4896 }
4897 // The following codes are deprecated and should never be allowed to access SF.
4898 case CONNECT_DISPLAY_UNUSED:
4899 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4900 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4901 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004902 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004903 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004904
4905 // These codes are used for the IBinder protocol to either interrogate the recipient
4906 // side of the transaction for its canonical interface descriptor or to dump its state.
4907 // We let them pass by default.
4908 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4909 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4910 code == IBinder::SYSPROPS_TRANSACTION) {
4911 return OK;
4912 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004913 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004914 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004915 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004916 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4917 return OK;
4918 }
4919 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4920 return PERMISSION_DENIED;
4921#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004922}
4923
Ana Krulec13be8ad2018-08-21 02:43:56 +00004924status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4925 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004926 status_t credentialCheck = CheckTransactCodeCredentials(code);
4927 if (credentialCheck != OK) {
4928 return credentialCheck;
4929 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004930
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004931 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4932 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004933 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004934 IPCThreadState* ipc = IPCThreadState::self();
4935 const int uid = ipc->getCallingUid();
4936 if (CC_UNLIKELY(uid != AID_SYSTEM
4937 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004938 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004939 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004940 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004941 return PERMISSION_DENIED;
4942 }
4943 int n;
4944 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004945 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004946 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004947 return NO_ERROR;
4948 case 1002: // SHOW_UPDATES
4949 n = data.readInt32();
4950 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004951 invalidateHwcGeometry();
4952 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004953 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004954 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004955 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004956 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004957 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004958 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004959 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004960 setTransactionFlags(
4961 eTransactionNeeded|
4962 eDisplayTransactionNeeded|
4963 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004964 return NO_ERROR;
4965 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004966 case 1006:{ // send empty update
4967 signalRefresh();
4968 return NO_ERROR;
4969 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004970 case 1008: // toggle use of hw composer
4971 n = data.readInt32();
4972 mDebugDisableHWC = n ? 1 : 0;
4973 invalidateHwcGeometry();
4974 repaintEverything();
4975 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004976 case 1009: // toggle use of transform hint
4977 n = data.readInt32();
4978 mDebugDisableTransformHint = n ? 1 : 0;
4979 invalidateHwcGeometry();
4980 repaintEverything();
4981 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004982 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004983 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004984 reply->writeInt32(0);
4985 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004986 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004987 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004988 return NO_ERROR;
4989 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004990 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004991 if (!display) {
4992 return NAME_NOT_FOUND;
4993 }
4994
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004995 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004996 return NO_ERROR;
4997 }
4998 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004999 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005000 // daltonize
5001 n = data.readInt32();
5002 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005003 case 1:
5004 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5005 break;
5006 case 2:
5007 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5008 break;
5009 case 3:
5010 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5011 break;
5012 default:
5013 mDaltonizer.setType(ColorBlindnessType::None);
5014 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005015 }
5016 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005017 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005018 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005019 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005020 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005021
5022 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005023 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005024 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005025 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005026 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005027 // apply a color matrix
5028 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005029 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005030 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005031 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005032 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005033 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005034 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005035 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005036 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005037 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005038 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005039
5040 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5041 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005042 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005043 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5044 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5045 }
5046
Chia-I Wu28f320b2018-05-03 11:02:56 -07005047 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005048 return NO_ERROR;
5049 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005050 // This is an experimental interface
5051 // Needs to be shifted to proper binder interface when we productize
5052 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005053 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005054 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005055 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005056 return NO_ERROR;
5057 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005058 case 1017: {
5059 n = data.readInt32();
5060 mForceFullDamage = static_cast<bool>(n);
5061 return NO_ERROR;
5062 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005063 case 1018: { // Modify Choreographer's phase offset
5064 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005065 if (mUseScheduler) {
5066 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5067 } else {
5068 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5069 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005070 return NO_ERROR;
5071 }
5072 case 1019: { // Modify SurfaceFlinger's phase offset
5073 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005074 if (mUseScheduler) {
5075 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5076 } else {
5077 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5078 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005079 return NO_ERROR;
5080 }
Irvel468051e2016-06-13 16:44:44 -07005081 case 1020: { // Layer updates interceptor
5082 n = data.readInt32();
5083 if (n) {
5084 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005085 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005086 }
5087 else{
5088 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005089 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005090 }
5091 return NO_ERROR;
5092 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005093 case 1021: { // Disable HWC virtual displays
5094 n = data.readInt32();
5095 mUseHwcVirtualDisplays = !n;
5096 return NO_ERROR;
5097 }
Romain Guy0147a172017-06-01 13:53:56 -07005098 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005099 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005100 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005101
Chia-I Wu28f320b2018-05-03 11:02:56 -07005102 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005103 return NO_ERROR;
5104 }
Romain Guy54f154a2017-10-24 21:40:32 +01005105 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005106 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005107 invalidateHwcGeometry();
5108 repaintEverything();
5109 return NO_ERROR;
5110 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005111 // Deprecate, use 1030 to check whether the device is color managed.
5112 case 1024: {
5113 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005114 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005115 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005116 n = data.readInt32();
5117 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005118 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005119 mTracing.enable();
5120 doTracing("tracing.enable");
5121 reply->writeInt32(NO_ERROR);
5122 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005123 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005124 status_t err = mTracing.disable();
5125 reply->writeInt32(err);
5126 }
5127 return NO_ERROR;
5128 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005129 case 1026: { // Get layer tracing status
5130 reply->writeBool(mTracing.isEnabled());
5131 return NO_ERROR;
5132 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005133 // Is a DisplayColorSetting supported?
5134 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005135 const auto display = getDefaultDisplayDevice();
5136 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005137 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005138 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005139
5140 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5141 switch (setting) {
5142 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005143 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005144 break;
5145 case DisplayColorSetting::UNMANAGED:
5146 reply->writeBool(true);
5147 break;
5148 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005149 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005150 break;
5151 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005152 reply->writeBool(
5153 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005154 break;
5155 }
5156 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005157 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005158 // Is VrFlinger active?
5159 case 1028: {
5160 Mutex::Autolock _l(mStateLock);
5161 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5162 return NO_ERROR;
5163 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005164 // Is device color managed?
5165 case 1030: {
5166 reply->writeBool(useColorManagement);
5167 return NO_ERROR;
5168 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005169 // Override default composition data space
5170 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5171 // && adb shell stop zygote && adb shell start zygote
5172 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5173 // adb shell stop zygote && adb shell start zygote
5174 case 1031: {
5175 Mutex::Autolock _l(mStateLock);
5176 n = data.readInt32();
5177 if (n) {
5178 n = data.readInt32();
5179 if (n) {
5180 Dataspace dataspace = static_cast<Dataspace>(n);
5181 if (!validateCompositionDataspace(dataspace)) {
5182 return BAD_VALUE;
5183 }
5184 mDefaultCompositionDataspace = dataspace;
5185 }
5186 n = data.readInt32();
5187 if (n) {
5188 Dataspace dataspace = static_cast<Dataspace>(n);
5189 if (!validateCompositionDataspace(dataspace)) {
5190 return BAD_VALUE;
5191 }
5192 mWideColorGamutCompositionDataspace = dataspace;
5193 }
5194 } else {
5195 // restore composition data space.
5196 mDefaultCompositionDataspace = defaultCompositionDataspace;
5197 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5198 }
5199 return NO_ERROR;
5200 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005201 }
5202 }
5203 return err;
5204}
5205
Steven Thomas6d8110b2017-08-31 18:24:21 -07005206void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005207 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005208 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005209}
5210
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005211// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5212class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005213public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005214 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5215 ~WindowDisconnector() {
5216 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005217 }
5218
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005219private:
5220 ANativeWindow* mWindow;
5221 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005222};
5223
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005224status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005225 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5226 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005227 uint32_t reqWidth, uint32_t reqHeight,
5228 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005229 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005230 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005231
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005232 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005233
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005234 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5235
Chia-I Wu20261cb2018-08-23 12:55:44 -07005236 sp<DisplayDevice> display;
5237 {
5238 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005239
Chia-I Wu20261cb2018-08-23 12:55:44 -07005240 display = getDisplayDeviceLocked(displayToken);
5241 if (!display) return BAD_VALUE;
5242
Chia-I Wucb023152018-08-28 12:57:23 -07005243 // set the requested width/height to the logical display viewport size
5244 // by default
5245 if (reqWidth == 0 || reqHeight == 0) {
5246 reqWidth = uint32_t(display->getViewport().width());
5247 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005248 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005249 }
5250
Peiyong Lin0e003c92018-09-17 11:09:51 -07005251 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5252 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005253
5254 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005255 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005256 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5257 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005258}
5259
5260status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005261 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5262 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005263 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005264 ATRACE_CALL();
5265
5266 class LayerRenderArea : public RenderArea {
5267 public:
Robert Carr578038f2018-03-09 12:25:24 -08005268 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005269 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5270 bool childrenOnly)
5271 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005272 mLayer(layer),
5273 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005274 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005275 mFlinger(flinger),
5276 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005277 const ui::Transform& getTransform() const override { return mTransform; }
Ady Abraham83729882018-12-07 12:26:48 -08005278 Rect getBounds() const override { return mLayer->getBufferSize(StateSet::Drawing); }
Marissa Wall61c58622018-07-18 10:12:20 -07005279 int getHeight() const override {
Ady Abraham83729882018-12-07 12:26:48 -08005280 return mLayer->getBufferSize(StateSet::Drawing).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005281 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005282 int getWidth() const override {
Ady Abraham83729882018-12-07 12:26:48 -08005283 return mLayer->getBufferSize(StateSet::Drawing).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005284 }
chaviwa76b2712017-09-20 12:02:26 -07005285 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005286 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005287 Rect getSourceCrop() const override {
5288 if (mCrop.isEmpty()) {
5289 return getBounds();
5290 } else {
5291 return mCrop;
5292 }
5293 }
Robert Carr578038f2018-03-09 12:25:24 -08005294 class ReparentForDrawing {
5295 public:
5296 const sp<Layer>& oldParent;
5297 const sp<Layer>& newParent;
5298
5299 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5300 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005301 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005302 }
Robert Carr15eae092018-03-23 13:43:53 -07005303 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005304 };
5305
5306 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005307 const Rect sourceCrop = getSourceCrop();
5308 // no need to check rotation because there is none
5309 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5310 sourceCrop.height() != getReqHeight();
5311
Robert Carr578038f2018-03-09 12:25:24 -08005312 if (!mChildrenOnly) {
5313 mTransform = mLayer->getTransform().inverse();
5314 drawLayers();
5315 } else {
5316 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005317 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005318 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5319 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005320
5321 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5322 drawLayers();
5323 }
5324 }
chaviwa76b2712017-09-20 12:02:26 -07005325
chaviwa76b2712017-09-20 12:02:26 -07005326 private:
chaviw7206d492017-11-10 16:16:12 -08005327 const sp<Layer> mLayer;
5328 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005329
5330 // In the "childrenOnly" case we reparent the children to a screenshot
5331 // layer which has no properties set and which does not draw.
5332 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005333 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005334 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005335
5336 SurfaceFlinger* mFlinger;
5337 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005338 };
5339
5340 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5341 auto parent = layerHandle->owner.promote();
5342
Robert Carr2e102c92018-10-23 12:11:15 -07005343 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005344 ALOGE("captureLayers called with a removed parent");
5345 return NAME_NOT_FOUND;
5346 }
5347
Robert Carr578038f2018-03-09 12:25:24 -08005348 const int uid = IPCThreadState::self()->getCallingUid();
5349 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Ady Abraham83729882018-12-07 12:26:48 -08005350 if (!forSystem && parent->getCurrentFlags() & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005351 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5352 return PERMISSION_DENIED;
5353 }
5354
chaviw7206d492017-11-10 16:16:12 -08005355 Rect crop(sourceCrop);
5356 if (sourceCrop.width() <= 0) {
5357 crop.left = 0;
Ady Abraham83729882018-12-07 12:26:48 -08005358 crop.right = parent->getBufferSize(StateSet::Current).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005359 }
5360
5361 if (sourceCrop.height() <= 0) {
5362 crop.top = 0;
Ady Abraham83729882018-12-07 12:26:48 -08005363 crop.bottom = parent->getBufferSize(StateSet::Current).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005364 }
5365
5366 int32_t reqWidth = crop.width() * frameScale;
5367 int32_t reqHeight = crop.height() * frameScale;
5368
Chia-I Wu20261cb2018-08-23 12:55:44 -07005369 // really small crop or frameScale
5370 if (reqWidth <= 0) {
5371 reqWidth = 1;
5372 }
5373 if (reqHeight <= 0) {
5374 reqHeight = 1;
5375 }
5376
Peiyong Lin0e003c92018-09-17 11:09:51 -07005377 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005378
Robert Carr578038f2018-03-09 12:25:24 -08005379 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005380 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5381 if (!layer->isVisible()) {
5382 return;
Robert Carr578038f2018-03-09 12:25:24 -08005383 } else if (childrenOnly && layer == parent.get()) {
5384 return;
chaviwa76b2712017-09-20 12:02:26 -07005385 }
5386 visitor(layer);
5387 });
5388 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005389 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005390}
5391
5392status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5393 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005394 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005395 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005396 bool useIdentityTransform) {
5397 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005398
Peiyong Lin0e003c92018-09-17 11:09:51 -07005399 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005400 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5401 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005402 *outBuffer =
5403 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5404 static_cast<android_pixel_format>(reqPixelFormat), 1,
5405 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005406
5407 // This mutex protects syncFd and captureResult for communication of the return values from the
5408 // main thread back to this Binder thread
5409 std::mutex captureMutex;
5410 std::condition_variable captureCondition;
5411 std::unique_lock<std::mutex> captureLock(captureMutex);
5412 int syncFd = -1;
5413 std::optional<status_t> captureResult;
5414
Robert Carr03480e22018-01-04 16:02:06 -08005415 const int uid = IPCThreadState::self()->getCallingUid();
5416 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5417
Dominik Laskowski8c001672018-05-30 16:52:06 -07005418 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005419 // If there is a refresh pending, bug out early and tell the binder thread to try again
5420 // after the refresh.
5421 if (mRefreshPending) {
5422 ATRACE_NAME("Skipping screenshot for now");
5423 std::unique_lock<std::mutex> captureLock(captureMutex);
5424 captureResult = std::make_optional<status_t>(EAGAIN);
5425 captureCondition.notify_one();
5426 return;
5427 }
5428
5429 status_t result = NO_ERROR;
5430 int fd = -1;
5431 {
5432 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005433 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005434 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5435 useIdentityTransform, forSystem, &fd);
5436 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005437 }
5438
5439 {
5440 std::unique_lock<std::mutex> captureLock(captureMutex);
5441 syncFd = fd;
5442 captureResult = std::make_optional<status_t>(result);
5443 captureCondition.notify_one();
5444 }
5445 });
5446
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005447 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005448 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005449 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005450 while (*captureResult == EAGAIN) {
5451 captureResult.reset();
5452 result = postMessageAsync(message);
5453 if (result != NO_ERROR) {
5454 return result;
5455 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005456 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005457 }
5458 result = *captureResult;
5459 }
5460
5461 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005462 sync_wait(syncFd, -1);
5463 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005464 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005465
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005466 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005467}
5468
chaviwa76b2712017-09-20 12:02:26 -07005469void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005470 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005471 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005472 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005473
Lloyd Pique144e1162017-12-20 16:44:52 -08005474 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005475
chaviwa76b2712017-09-20 12:02:26 -07005476 const auto reqWidth = renderArea.getReqWidth();
5477 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005478 const auto sourceCrop = renderArea.getSourceCrop();
5479 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005480
Peiyong Lin0e003c92018-09-17 11:09:51 -07005481 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005482 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005483
Mathias Agopian180f10d2013-04-10 22:55:41 -07005484 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005485 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005486
5487 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005488 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005489 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005490
chaviw50da5042018-04-09 13:49:37 -07005491 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005492 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005493 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005494
chaviwa76b2712017-09-20 12:02:26 -07005495 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005496 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005497 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005498 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005499 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005500}
5501
chaviwa76b2712017-09-20 12:02:26 -07005502status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5503 TraverseLayersFunction traverseLayers,
5504 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005505 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005506 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005507 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005508 ATRACE_CALL();
5509
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005510 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005511
5512 traverseLayers([&](Layer* layer) {
5513 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5514 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005515
Robert Carr03480e22018-01-04 16:02:06 -08005516 // We allow the system server to take screenshots of secure layers for
5517 // use in situations like the Screen-rotation animation and place
5518 // the impetus on WindowManager to not persist them.
5519 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005520 ALOGW("FB is protected: PERMISSION_DENIED");
5521 return PERMISSION_DENIED;
5522 }
Peiyong Linfb530cf2018-12-15 05:07:38 +00005523 auto& engine(getRenderEngine());
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005524
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005525 // this binds the given EGLImage as a framebuffer for the
5526 // duration of this scope.
Peiyong Linfb530cf2018-12-15 05:07:38 +00005527 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005528 if (bufferBond.getStatus() != NO_ERROR) {
5529 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005530 return INVALID_OPERATION;
5531 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005532
Dan Stozaabcda352017-06-01 14:37:39 -07005533 // this will in fact render into our dequeued buffer
5534 // via an FBO, which means we didn't have to create
5535 // an EGLSurface and therefore we're not
5536 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005537 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005538
Peiyong Linfb530cf2018-12-15 05:07:38 +00005539 base::unique_fd syncFd = engine.flush();
Alec Mouri492bc572018-09-11 21:40:04 +00005540 if (syncFd < 0) {
Peiyong Linfb530cf2018-12-15 05:07:38 +00005541 engine.finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005542 }
Alec Mouri492bc572018-09-11 21:40:04 +00005543 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005544
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005545 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005546}
5547
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005548// ---------------------------------------------------------------------------
5549
Dan Stoza412903f2017-04-27 13:42:17 -07005550void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5551 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005552}
5553
Dan Stoza412903f2017-04-27 13:42:17 -07005554void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5555 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005556}
5557
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005558void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005559 const LayerVector::Visitor& visitor) {
5560 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005561 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005562 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005563 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005564 continue;
5565 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005566 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005567 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005568 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005569 return;
5570 }
chaviwa76b2712017-09-20 12:02:26 -07005571 if (!layer->isVisible()) {
5572 return;
5573 }
5574 visitor(layer);
5575 });
5576 }
5577}
5578
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005579}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005580
Lloyd Pique074e8122018-07-26 12:57:23 -07005581
Mathias Agopian3f844832013-08-07 21:24:32 -07005582#if defined(__gl_h_)
5583#error "don't include gl/gl.h in this file"
5584#endif
5585
5586#if defined(__gl2_h_)
5587#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005588#endif