blob: 467b7da27a76c297aa7d25b94a58a39fb6b2cc12 [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
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700461sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
462 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700463{
464 class DisplayToken : public BBinder {
465 sp<SurfaceFlinger> flinger;
466 virtual ~DisplayToken() {
467 // no more references, this display must be terminated
468 Mutex::Autolock _l(flinger->mStateLock);
469 flinger->mCurrentState.displays.removeItem(this);
470 flinger->setTransactionFlags(eDisplayTransactionNeeded);
471 }
472 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700473 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700474 : flinger(flinger) {
475 }
476 };
477
478 sp<BBinder> token = new DisplayToken(this);
479
480 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700481 // Display ID is assigned when virtual display is allocated by HWC.
482 DisplayDeviceState state;
483 state.isSecure = secure;
484 state.displayName = displayName;
485 mCurrentState.displays.add(token, state);
486 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700487 return token;
488}
489
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700490void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700491 Mutex::Autolock _l(mStateLock);
492
Dominik Laskowski075d3172018-05-24 15:50:06 -0700493 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
494 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700495 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700496 return;
497 }
498
Dominik Laskowski075d3172018-05-24 15:50:06 -0700499 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
500 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700501 ALOGE("destroyDisplay called for non-virtual display");
502 return;
503 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700504 mInterceptor->saveDisplayDeletion(state.sequenceId);
505 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700506 setTransactionFlags(eDisplayTransactionNeeded);
507}
508
Mathias Agopiane57f2922012-08-09 16:29:12 -0700509sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700510 std::optional<DisplayId> displayId;
511
512 if (id == HWC_DISPLAY_PRIMARY) {
513 displayId = getInternalDisplayId();
514 } else if (id == HWC_DISPLAY_EXTERNAL) {
515 displayId = getExternalDisplayId();
516 }
517
518 if (!displayId) {
519 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800520 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700521 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700522
523 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700524}
525
Ady Abraham37965d42018-11-01 13:43:32 -0700526status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
527 if (!outGetColorManagement) {
528 return BAD_VALUE;
529 }
530 *outGetColorManagement = useColorManagement;
531 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700532}
533
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800534void SurfaceFlinger::bootFinished()
535{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700536 if (mStartPropertySetThread->join() != NO_ERROR) {
537 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800538 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800539 const nsecs_t now = systemTime();
540 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000541 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700542
543 // wait patiently for the window manager death
544 const String16 name("window");
545 sp<IBinder> window(defaultServiceManager()->getService(name));
546 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700547 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700548 }
Robert Carr720e5062018-07-30 17:45:14 -0700549 sp<IBinder> input(defaultServiceManager()->getService(
550 String16("inputflinger")));
551 if (input == nullptr) {
552 ALOGE("Failed to link to input service");
553 } else {
554 mInputFlinger = interface_cast<IInputFlinger>(input);
555 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700556
Steven Thomas050b2c82017-03-06 11:45:16 -0800557 if (mVrFlinger) {
558 mVrFlinger->OnBootFinished();
559 }
560
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700561 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700562 // formerly we would just kill the process, but we now ask it to exit so it
563 // can choose where to stop the animation.
564 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700565
566 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
567 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
568 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700569
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800570 postMessageAsync(new LambdaMessage([this] {
571 readPersistentProperties();
572 mBootStage = BootStage::FINISHED;
573 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800574}
575
Dan Stoza436ccf32018-06-21 12:10:12 -0700576uint32_t SurfaceFlinger::getNewTexture() {
577 {
578 std::lock_guard lock(mTexturePoolMutex);
579 if (!mTexturePool.empty()) {
580 uint32_t name = mTexturePool.back();
581 mTexturePool.pop_back();
582 ATRACE_INT("TexturePoolSize", mTexturePool.size());
583 return name;
584 }
585
586 // The pool was too small, so increase it for the future
587 ++mTexturePoolSize;
588 }
589
590 // The pool was empty, so we need to get a new texture name directly using a
591 // blocking call to the main thread
592 uint32_t name = 0;
593 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
594 return name;
595}
596
Mathias Agopian3f844832013-08-07 21:24:32 -0700597void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700598 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700599}
600
Wei Wangf9b05ee2017-07-19 20:59:39 -0700601// Do not call property_set on main thread which will be blocked by init
602// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700603void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700604 ALOGI( "SurfaceFlinger's main thread ready to run. "
605 "Initializing graphics H/W...");
606
Thierry Strudel2924d012017-08-14 15:19:37 -0700607 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900608
Steven Thomasb02664d2017-07-26 18:48:28 -0700609 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800610
Steven Thomasb02664d2017-07-26 18:48:28 -0700611 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700612 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700613 mScheduler = getFactory().createScheduler([this](bool enabled) {
614 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
615 });
616
Ana Krulec98b5b242018-08-10 15:03:23 -0700617 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700618 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700619 [this] { resyncWithRateLimit(); },
620 impl::EventThread::InterceptVSyncsCallback());
621 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700622 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700623 [this] { resyncWithRateLimit(); },
624 [this](nsecs_t timestamp) {
625 mInterceptor->saveVSyncEvent(timestamp);
626 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800627
Ana Krulec98b5b242018-08-10 15:03:23 -0700628 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700629 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
630 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700631 } else {
632 mEventThreadSource =
633 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
634 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
635 mEventThread =
636 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
637 [this] { resyncWithRateLimit(); },
638 impl::EventThread::InterceptVSyncsCallback(),
639 "appEventThread");
640 mSfEventThreadSource =
641 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
642 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
643
644 mSFEventThread =
645 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
646 [this] { resyncWithRateLimit(); },
647 [this](nsecs_t timestamp) {
648 mInterceptor->saveVSyncEvent(timestamp);
649 },
650 "sfEventThread");
651 mEventQueue->setEventThread(mSFEventThread.get());
652 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
653 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800654
Steven Thomasb02664d2017-07-26 18:48:28 -0700655 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700656 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700657 renderEngineFeature |= (useColorManagement ?
658 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700659 renderEngineFeature |= (useContextPriority ?
660 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700661
662 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
663 getBE().mRenderEngine =
Peiyong Linc6780972018-10-28 15:24:08 -0700664 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
665 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800666 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700667
668 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
669 "Starting with vr flinger active is not currently supported.");
Lloyd Pique90c115d2018-09-18 21:39:42 -0700670 getBE().mHwc = getFactory().createHWComposer(getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -0700671 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800672 // Process any initial hotplug and resulting display changes.
673 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700674 const auto display = getDefaultDisplayDeviceLocked();
675 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700676 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700677 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800678
Steven Thomas050b2c82017-03-06 11:45:16 -0800679 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700680 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700681 // This callback is called from the vr flinger dispatch thread. We
682 // need to call signalTransaction(), which requires holding
683 // mStateLock when we're not on the main thread. Acquiring
684 // mStateLock from the vr flinger dispatch thread might trigger a
685 // deadlock in surface flinger (see b/66916578), so post a message
686 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700687 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700688 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
689 mVrFlingerRequestsDisplay = requestDisplay;
690 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700691 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800692 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700693 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
694 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700695 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700696 .value_or(0),
697 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800698 if (!mVrFlinger) {
699 ALOGE("Failed to start vrflinger");
700 }
701 }
702
Lloyd Pique90c115d2018-09-18 21:39:42 -0700703 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700704 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700705
Mathias Agopian92a979a2012-08-02 18:32:23 -0700706 // initialize our drawing state
707 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700708
Andy McFadden13a082e2012-08-24 10:16:42 -0700709 // set initial conditions (e.g. unblank default device)
710 initializeDisplays();
711
David Sodmanbc815282017-11-05 18:57:52 -0800712 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700713
Wei Wangf9b05ee2017-07-19 20:59:39 -0700714 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700715
716 const bool presentFenceReliable =
717 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
718 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700719
720 if (mStartPropertySetThread->Start() != NO_ERROR) {
721 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800722 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800723
Dan Stoza9e56aa02015-11-02 13:00:03 -0800724 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700725}
726
Romain Guy11d63f42017-07-20 12:47:14 -0700727void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700728 Mutex::Autolock _l(mStateLock);
729
Romain Guy11d63f42017-07-20 12:47:14 -0700730 char value[PROPERTY_VALUE_MAX];
731
732 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800733 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700734 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800735 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100736
737 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700738 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700739}
740
Mathias Agopiana67e4182012-06-19 17:26:12 -0700741void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800742 // Start boot animation service by setting a property mailbox
743 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700744 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800745 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700746 if (mStartPropertySetThread->join() != NO_ERROR) {
747 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800748 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700749}
750
Mathias Agopian875d8e12013-06-07 15:35:48 -0700751size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800752 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700753}
754
Mathias Agopian875d8e12013-06-07 15:35:48 -0700755size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800756 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700757}
758
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800759// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800760
Jamie Gennis582270d2011-08-17 18:19:00 -0700761bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800762 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800763 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800764 return authenticateSurfaceTextureLocked(bufferProducer);
765}
766
767bool SurfaceFlinger::authenticateSurfaceTextureLocked(
768 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800769 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800770 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800771}
772
Brian Anderson6b376712017-04-04 10:51:39 -0700773status_t SurfaceFlinger::getSupportedFrameTimestamps(
774 std::vector<FrameEvent>* outSupported) const {
775 *outSupported = {
776 FrameEvent::REQUESTED_PRESENT,
777 FrameEvent::ACQUIRE,
778 FrameEvent::LATCH,
779 FrameEvent::FIRST_REFRESH_START,
780 FrameEvent::LAST_REFRESH_START,
781 FrameEvent::GPU_COMPOSITION_DONE,
782 FrameEvent::DEQUEUE_READY,
783 FrameEvent::RELEASE,
784 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700785 ConditionalLock _l(mStateLock,
786 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700787 if (!getHwComposer().hasCapability(
788 HWC2::Capability::PresentFenceIsNotReliable)) {
789 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
790 }
791 return NO_ERROR;
792}
793
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700794status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
795 Vector<DisplayInfo>* configs) {
796 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700797 return BAD_VALUE;
798 }
799
Dominik Laskowski075d3172018-05-24 15:50:06 -0700800 const auto displayId = getPhysicalDisplayId(displayToken);
801 if (!displayId) {
802 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700803 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700804
Mathias Agopian8b736f12012-08-13 17:54:26 -0700805 // TODO: Not sure if display density should handled by SF any longer
806 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700807 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700808 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700809 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800810 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700811 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700812 }
813 return density;
814 }
815 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700816 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700817 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700818 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700819 return getDensityFromProperty("ro.sf.lcd_density"); }
820 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700821
Dan Stoza7f7da322014-05-02 15:26:25 -0700822 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700823
Steven Thomas6d8110b2017-08-31 18:24:21 -0700824 ConditionalLock _l(mStateLock,
825 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700826 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700827 DisplayInfo info = DisplayInfo();
828
Dan Stoza9e56aa02015-11-02 13:00:03 -0800829 float xdpi = hwConfig->getDpiX();
830 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700831
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700832 info.w = hwConfig->getWidth();
833 info.h = hwConfig->getHeight();
834 // Default display viewport to display width and height
835 info.viewportW = info.w;
836 info.viewportH = info.h;
837
Dominik Laskowski075d3172018-05-24 15:50:06 -0700838 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700839 // The density of the device is provided by a build property
840 float density = Density::getBuildDensity() / 160.0f;
841 if (density == 0) {
842 // the build doesn't provide a density -- this is wrong!
843 // use xdpi instead
844 ALOGE("ro.sf.lcd_density must be defined as a build property");
845 density = xdpi / 160.0f;
846 }
847 if (Density::getEmuDensity()) {
848 // if "qemu.sf.lcd_density" is specified, it overrides everything
849 xdpi = ydpi = density = Density::getEmuDensity();
850 density /= 160.0f;
851 }
852 info.density = density;
853
854 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700855 const auto display = getDefaultDisplayDeviceLocked();
856 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700857
858 // This is for screenrecord
859 const Rect viewport = display->getViewport();
860 if (viewport.isValid()) {
861 info.viewportW = uint32_t(viewport.getWidth());
862 info.viewportH = uint32_t(viewport.getHeight());
863 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700864 } else {
865 // TODO: where should this value come from?
866 static const int TV_DENSITY = 213;
867 info.density = TV_DENSITY / 160.0f;
868 info.orientation = 0;
869 }
870
Dan Stoza7f7da322014-05-02 15:26:25 -0700871 info.xdpi = xdpi;
872 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800873 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900874 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800875
Andy McFadden91b2ca82014-06-13 14:04:23 -0700876 // This is how far in advance a buffer must be queued for
877 // presentation at a given time. If you want a buffer to appear
878 // on the screen at time N, you must submit the buffer before
879 // (N - presentationDeadline).
880 //
881 // Normally it's one full refresh period (to give SF a chance to
882 // latch the buffer), but this can be reduced by configuring a
883 // DispSync offset. Any additional delays introduced by the hardware
884 // composer or panel must be accounted for here.
885 //
886 // We add an additional 1ms to allow for processing time and
887 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800888 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800889 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700890
891 // All non-virtual displays are currently considered secure.
892 info.secure = true;
893
Dominik Laskowski075d3172018-05-24 15:50:06 -0700894 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700895 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800896 std::swap(info.w, info.h);
897 }
898
Michael Wright28f24d02016-07-12 13:30:53 -0700899 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700900 }
901
Dan Stoza7f7da322014-05-02 15:26:25 -0700902 return NO_ERROR;
903}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700904
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700905status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
906 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700907 return BAD_VALUE;
908 }
909
Ana Krulece588e312018-09-18 12:32:24 -0700910 if (mUseScheduler) {
911 mScheduler->getDisplayStatInfo(stats);
912 } else {
913 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
914 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
915 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700916 return NO_ERROR;
917}
918
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700919int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
920 const auto display = getDisplayDevice(displayToken);
921 if (!display) {
922 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800923 return BAD_VALUE;
924 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700925
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700926 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700927}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700928
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700929void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700930 if (display->isVirtual()) {
931 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
932 return;
933 }
934
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700935 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700936 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700937 return;
938 }
939
Dominik Laskowski075d3172018-05-24 15:50:06 -0700940 const auto displayId = display->getId();
941 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700942
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700943 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700944 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700945}
946
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700947status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700948 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700949 Vector<DisplayInfo> configs;
950 getDisplayConfigs(displayToken, &configs);
951 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
952 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
953 configs.size());
954 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700955 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700956 const auto display = getDisplayDevice(displayToken);
957 if (!display) {
958 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
959 displayToken.get());
960 } else if (display->isVirtual()) {
961 ALOGW("Attempt to set active config %d for virtual display", mode);
962 } else {
963 setActiveConfigInternal(display, mode);
964 }
965 }));
966
Mathias Agopian888c8222012-08-04 21:10:38 -0700967 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700968}
Dominik Laskowski075d3172018-05-24 15:50:06 -0700969
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700970status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
971 Vector<ColorMode>* outColorModes) {
972 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700973 return BAD_VALUE;
974 }
975
Dominik Laskowski075d3172018-05-24 15:50:06 -0700976 const auto displayId = getPhysicalDisplayId(displayToken);
977 if (!displayId) {
978 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -0700979 }
980
Peiyong Lina52f0292018-03-14 17:26:31 -0700981 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700982 {
983 ConditionalLock _l(mStateLock,
984 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700985 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -0700986 }
Michael Wright28f24d02016-07-12 13:30:53 -0700987 outColorModes->clear();
988 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
989
990 return NO_ERROR;
991}
992
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700993ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
994 if (const auto display = getDisplayDevice(displayToken)) {
995 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700996 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700997 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700998}
999
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001000void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1001 Dataspace dataSpace, RenderIntent renderIntent) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001002 if (display->isVirtual()) {
1003 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
1004 return;
1005 }
1006
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001007 ColorMode currentMode = display->getActiveColorMode();
1008 Dataspace currentDataSpace = display->getCompositionDataSpace();
1009 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001010
Peiyong Lin38e9a562018-04-10 16:24:20 -07001011 if (mode == currentMode && dataSpace == currentDataSpace &&
1012 renderIntent == currentRenderIntent) {
1013 return;
1014 }
1015
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001016 display->setActiveColorMode(mode);
1017 display->setCompositionDataSpace(dataSpace);
1018 display->setActiveRenderIntent(renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001019
Dominik Laskowski075d3172018-05-24 15:50:06 -07001020 const auto displayId = display->getId();
1021 LOG_ALWAYS_FATAL_IF(!displayId);
1022 getHwComposer().setActiveColorMode(*displayId, mode, renderIntent);
1023
Dominik Laskowski34157762018-10-31 13:07:19 -07001024 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), display=%s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001025 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
Dominik Laskowski34157762018-10-31 13:07:19 -07001026 renderIntent, to_string(*displayId).c_str());
Michael Wright28f24d02016-07-12 13:30:53 -07001027}
1028
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001029status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001030 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001031 Vector<ColorMode> modes;
1032 getDisplayColorModes(displayToken, &modes);
1033 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1034 if (mode < ColorMode::NATIVE || !exists) {
1035 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1036 decodeColorMode(mode).c_str(), mode, displayToken.get());
1037 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001038 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001039 const auto display = getDisplayDevice(displayToken);
1040 if (!display) {
1041 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1042 decodeColorMode(mode).c_str(), mode, displayToken.get());
1043 } else if (display->isVirtual()) {
1044 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1045 decodeColorMode(mode).c_str(), mode);
1046 } else {
1047 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1048 RenderIntent::COLORIMETRIC);
1049 }
1050 }));
1051
Michael Wright28f24d02016-07-12 13:30:53 -07001052 return NO_ERROR;
1053}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001054
Svetoslavd85084b2014-03-20 10:28:31 -07001055status_t SurfaceFlinger::clearAnimationFrameStats() {
1056 Mutex::Autolock _l(mStateLock);
1057 mAnimFrameTracker.clearStats();
1058 return NO_ERROR;
1059}
1060
1061status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1062 Mutex::Autolock _l(mStateLock);
1063 mAnimFrameTracker.getStats(outStats);
1064 return NO_ERROR;
1065}
1066
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001067status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1068 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001069 Mutex::Autolock _l(mStateLock);
1070
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001071 const auto display = getDisplayDeviceLocked(displayToken);
1072 if (!display) {
1073 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001074 return BAD_VALUE;
1075 }
1076
Peiyong Linfb069302018-04-25 14:34:31 -07001077 // At this point the DisplayDeivce should already be set up,
1078 // meaning the luminance information is already queried from
1079 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001080 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001081 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1082 capabilities.getDesiredMaxLuminance(),
1083 capabilities.getDesiredMaxAverageLuminance(),
1084 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001085
1086 return NO_ERROR;
1087}
1088
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001089status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1090 ui::PixelFormat* outFormat,
1091 ui::Dataspace* outDataspace,
1092 uint8_t* outComponentMask) const {
1093 if (!outFormat || !outDataspace || !outComponentMask) {
1094 return BAD_VALUE;
1095 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001096 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001097 if (!display || !display->getId()) {
1098 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1099 return BAD_VALUE;
1100 }
1101 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1102 outDataspace, outComponentMask);
1103}
1104
Kevin DuBois74e53772018-11-19 10:52:38 -08001105status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1106 bool enable, uint8_t componentMask,
1107 uint64_t maxFrames) const {
1108 const auto display = getDisplayDevice(displayToken);
1109 if (!display || !display->getId()) {
1110 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1111 return BAD_VALUE;
1112 }
1113
1114 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1115 componentMask, maxFrames);
1116}
1117
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001118status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1119 uint64_t maxFrames, uint64_t timestamp,
1120 DisplayedFrameStats* outStats) const {
1121 const auto display = getDisplayDevice(displayToken);
1122 if (!display || !display->getId()) {
1123 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1124 return BAD_VALUE;
1125 }
1126
1127 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1128 outStats);
1129}
1130
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001131status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001132 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001133 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001134
Chia-I Wu90f669f2017-10-05 14:24:41 -07001135 if (mInjectVSyncs == enable) {
1136 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001137 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001138
Ana Krulec98b5b242018-08-10 15:03:23 -07001139 // TODO(akrulec): Part of the Injector should be refactored, so that it
1140 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001141 if (enable) {
1142 ALOGV("VSync Injections enabled");
1143 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001144 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001145 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001146 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001147 impl::EventThread::InterceptVSyncsCallback(),
1148 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001149 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001150 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001151 } else {
1152 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001153 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001154 }
1155
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001156 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001157 }));
1158
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001159 return NO_ERROR;
1160}
1161
1162status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001163 Mutex::Autolock _l(mStateLock);
1164
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001165 if (!mInjectVSyncs) {
1166 ALOGE("VSync Injections not enabled");
1167 return BAD_VALUE;
1168 }
1169 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1170 ALOGV("Injecting VSync inside SurfaceFlinger");
1171 mVSyncInjector->onInjectSyncEvent(when);
1172 }
1173 return NO_ERROR;
1174}
1175
Lloyd Pique755e3192018-01-31 16:46:15 -08001176status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1177 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001178 // Try to acquire a lock for 1s, fail gracefully
1179 const status_t err = mStateLock.timedLock(s2ns(1));
1180 const bool locked = (err == NO_ERROR);
1181 if (!locked) {
1182 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1183 return TIMED_OUT;
1184 }
1185
1186 outLayers->clear();
1187 mCurrentState.traverseInZOrder([&](Layer* layer) {
1188 outLayers->push_back(layer->getLayerDebugInfo());
1189 });
1190
1191 mStateLock.unlock();
1192 return NO_ERROR;
1193}
1194
Peiyong Linc6780972018-10-28 15:24:08 -07001195status_t SurfaceFlinger::getCompositionPreference(
1196 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1197 Dataspace* outWideColorGamutDataspace,
1198 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001199 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001200 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001201 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001202 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001203 return NO_ERROR;
1204}
1205
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001206// ----------------------------------------------------------------------------
1207
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001208sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1209 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001210 if (mUseScheduler) {
1211 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1212 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1213 } else {
1214 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1215 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001216 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001217 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1218 return mSFEventThread->createEventConnection();
1219 } else {
1220 return mEventThread->createEventConnection();
1221 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001222 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001223}
1224
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001225// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001226
1227void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001228 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001229}
1230
1231void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001232 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001233}
1234
1235void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001236 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001237}
1238
1239void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001240 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001241 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001242}
1243
1244status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001245 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001246 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001247}
1248
1249status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001250 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001251 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001252 if (res == NO_ERROR) {
1253 msg->wait();
1254 }
1255 return res;
1256}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001257
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001258void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001259 do {
1260 waitForEvent();
1261 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001262}
1263
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001264void SurfaceFlinger::enableHardwareVsync() {
1265 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001266 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001267 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001268 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001269 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001270 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001271}
1272
Jesse Hall948fe0c2013-10-14 12:56:09 -07001273void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001274 Mutex::Autolock _l(mHWVsyncLock);
1275
Jesse Hall948fe0c2013-10-14 12:56:09 -07001276 if (makeAvailable) {
1277 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001278 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1279 if (mUseScheduler) {
1280 mScheduler->makeHWSyncAvailable(true);
1281 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001282 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001283 // Hardware vsync is not currently available, so abort the resync
1284 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001285 return;
1286 }
1287
Dominik Laskowski075d3172018-05-24 15:50:06 -07001288 const auto displayId = getInternalDisplayId();
1289 if (!displayId || !getHwComposer().isConnected(*displayId)) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001290 return;
1291 }
1292
Dominik Laskowski075d3172018-05-24 15:50:06 -07001293 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001294 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001295
Ana Krulece588e312018-09-18 12:32:24 -07001296 if (mUseScheduler) {
1297 mScheduler->setVsyncPeriod(period);
1298 } else {
1299 mPrimaryDispSync->reset();
1300 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001301
Ana Krulece588e312018-09-18 12:32:24 -07001302 if (!mPrimaryHWVsyncEnabled) {
1303 mPrimaryDispSync->beginResync();
1304 mEventControlThread->setVsyncEnabled(true);
1305 mPrimaryHWVsyncEnabled = true;
1306 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001307 }
1308}
1309
Jesse Hall948fe0c2013-10-14 12:56:09 -07001310void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001311 Mutex::Autolock _l(mHWVsyncLock);
1312 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001313 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001314 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001315 mPrimaryHWVsyncEnabled = false;
1316 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001317 if (makeUnavailable) {
1318 mHWVsyncAvailable = false;
1319 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001320}
1321
Tim Murray4a4e4a22016-04-19 16:29:23 +00001322void SurfaceFlinger::resyncWithRateLimit() {
1323 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001324
1325 // No explicit locking is needed here since EventThread holds a lock while calling this method
1326 static nsecs_t sLastResyncAttempted = 0;
1327 const nsecs_t now = systemTime();
1328 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001329 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001330 }
Dan Stoza57164302017-05-08 14:03:54 -07001331 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001332}
1333
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001334void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1335 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001336 ATRACE_NAME("SF onVsync");
1337
Steven Thomas3cfac282017-02-06 12:29:30 -08001338 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001339 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001340 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001341 return;
1342 }
1343
Dominik Laskowski075d3172018-05-24 15:50:06 -07001344 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001345 return;
1346 }
1347
Dominik Laskowski075d3172018-05-24 15:50:06 -07001348 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001349 // For now, we don't do anything with external display vsyncs.
1350 return;
1351 }
1352
Ana Krulece588e312018-09-18 12:32:24 -07001353 if (mUseScheduler) {
1354 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001355 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001356 bool needsHwVsync = false;
1357 { // Scope for the lock
1358 Mutex::Autolock _l(mHWVsyncLock);
1359 if (mPrimaryHWVsyncEnabled) {
1360 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1361 }
1362 }
1363
1364 if (needsHwVsync) {
1365 enableHardwareVsync();
1366 } else {
1367 disableHardwareVsync(false);
1368 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001369 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001370}
1371
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001372void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001373 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1374 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001375}
1376
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001377void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001378 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001379 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001380 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001381
Lloyd Piqueba04e622017-12-14 17:11:26 -08001382 // Ignore events that do not have the right sequenceId.
1383 if (sequenceId != getBE().mComposerSequenceId) {
1384 return;
1385 }
1386
Steven Thomasb02664d2017-07-26 18:48:28 -07001387 // Only lock if we're not on the main thread. This function is normally
1388 // called on a hwbinder thread, but for the primary display it's called on
1389 // the main thread with the state lock already held, so don't attempt to
1390 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001391 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001392
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001393 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001394
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001395 if (std::this_thread::get_id() == mMainThreadId) {
1396 // Process all pending hot plug events immediately if we are on the main thread.
1397 processDisplayHotplugEventsLocked();
1398 }
1399
Lloyd Piqueba04e622017-12-14 17:11:26 -08001400 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001401}
1402
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001403void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001404 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001405 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001406 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001407 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001408 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001409}
1410
Dominik Laskowski075d3172018-05-24 15:50:06 -07001411void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001412 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001413 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001414 if (const auto displayId = getInternalDisplayId()) {
1415 getHwComposer().setVsyncEnabled(*displayId,
1416 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1417 }
Mathias Agopian86303202012-07-24 22:46:10 -07001418}
1419
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001420// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001421void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001422 if (mUseScheduler) {
1423 mScheduler->disableHardwareVsync(true);
1424 } else {
1425 disableHardwareVsync(true);
1426 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001427 // Clear the drawing state so that the logic inside of
1428 // handleTransactionLocked will fire. It will determine the delta between
1429 // mCurrentState and mDrawingState and re-apply all changes when we make the
1430 // transition.
1431 mDrawingState.displays.clear();
1432 mDisplays.clear();
1433}
1434
Steven Thomas050b2c82017-03-06 11:45:16 -08001435void SurfaceFlinger::updateVrFlinger() {
1436 if (!mVrFlinger)
1437 return;
1438 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001439 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001440 return;
1441 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001442
David Sodman105b7dc2017-11-04 20:28:14 -07001443 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001444 ALOGE("Vr flinger is only supported for remote hardware composer"
1445 " service connections. Ignoring request to transition to vr"
1446 " flinger.");
1447 mVrFlingerRequestsDisplay = false;
1448 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001449 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001450
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001451 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001452
Steven Thomas0123ac62018-07-12 11:32:34 -07001453 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001454 LOG_ALWAYS_FATAL_IF(!display);
1455 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001456 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1457 // called below. Clear the reference now so we don't accidentally use it
1458 // later.
1459 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001460
Steven Thomasb02664d2017-07-26 18:48:28 -07001461 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001462 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001463 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001464
Steven Thomasb02664d2017-07-26 18:48:28 -07001465 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001466 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Pique90c115d2018-09-18 21:39:42 -07001467 getBE().mHwc = getFactory().createHWComposer(
1468 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -07001469 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001470
David Sodman105b7dc2017-11-04 20:28:14 -07001471 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1472 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001473
1474 if (vrFlingerRequestsDisplay) {
1475 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001476 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001477
1478 mVisibleRegionsDirty = true;
1479 invalidateHwcGeometry();
1480
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001481 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001482 display = getDefaultDisplayDeviceLocked();
1483 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001484 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001485
Steven Thomasb02664d2017-07-26 18:48:28 -07001486 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski075d3172018-05-24 15:50:06 -07001487 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001488 const nsecs_t period = activeConfig->getVsyncPeriod();
1489 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001490
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001491 // The present fences returned from vr_hwc are not an accurate
1492 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001493 if (mUseScheduler) {
1494 mScheduler->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() || !hasSyncFramework);
1495 } else {
1496 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1497 !hasSyncFramework);
1498 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001499
Steven Thomasb02664d2017-07-26 18:48:28 -07001500 // Use phase of 0 since phase is not known.
1501 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001502 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1503 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001504
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001505 resyncToHardwareVsync(false);
1506
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001507 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001508 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001509}
1510
Mathias Agopian4fec8732012-06-29 14:12:52 -07001511void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001512 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001513 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001514 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001515 if (mUseScheduler) {
1516 // This call is made each time SF wakes up and creates a new frame.
1517 mScheduler->incrementFrameCounter();
1518 }
Dan Stoza50182882016-07-08 12:02:20 -07001519 bool frameMissed = !mHadClientComposition &&
1520 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001521 (mPreviousPresentFence->getSignalTime() ==
1522 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001523 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001524 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001525 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001526 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001527 if (mPropagateBackpressure) {
1528 signalLayerUpdate();
1529 break;
1530 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001531 }
Dan Stoza50182882016-07-08 12:02:20 -07001532
Steven Thomas050b2c82017-03-06 11:45:16 -08001533 // Now that we're going to make it to the handleMessageTransaction()
1534 // call below it's safe to call updateVrFlinger(), which will
1535 // potentially trigger a display handoff.
1536 updateVrFlinger();
1537
Dan Stoza6b9454d2014-11-07 16:00:59 -08001538 bool refreshNeeded = handleMessageTransaction();
1539 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001540 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001541 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001542 // Signal a refresh if a transaction modified the window state,
1543 // a new buffer was latched, or if HWC has requested a full
1544 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001545 signalRefresh();
1546 }
1547 break;
1548 }
1549 case MessageQueue::REFRESH: {
1550 handleMessageRefresh();
1551 break;
1552 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001553 }
1554}
1555
Dan Stoza6b9454d2014-11-07 16:00:59 -08001556bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001557 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001558
1559 // Apply any ready transactions in the queues if there are still transactions that have not been
1560 // applied, wake up during the next vsync period and check again
1561 bool transactionNeeded = false;
1562 if (!flushTransactionQueues()) {
1563 transactionNeeded = true;
1564 }
1565
Mathias Agopian4fec8732012-06-29 14:12:52 -07001566 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001567 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001568 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001569
1570 if (transactionNeeded) {
1571 setTransactionFlags(eTransactionNeeded);
1572 }
1573
1574 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001575}
1576
Mathias Agopian4fec8732012-06-29 14:12:52 -07001577void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001578 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001579
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001580 mRefreshPending = false;
1581
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001582 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001583 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001584 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001585 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001586 for (const auto& [token, display] : mDisplays) {
1587 beginFrame(display);
1588 prepareFrame(display);
1589 doDebugFlashRegions(display, repaintEverything);
1590 doComposition(display, repaintEverything);
1591 }
1592
Adrian Roos1e1a1282017-11-01 19:05:31 +01001593 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001594 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001595
1596 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001597 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001598
Dan Stozabfbffeb2016-07-21 14:49:33 -07001599 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001600 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001601 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001602 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001603 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001604
Alec Mouri86770e52018-09-24 22:40:58 +00001605 // Setup RenderEngine sync fences if native sync is supported.
1606 if (getBE().mRenderEngine->useNativeFenceSync()) {
1607 if (mHadClientComposition) {
1608 base::unique_fd flushFence(getRenderEngine().flush());
1609 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1610 getBE().flushFence = new Fence(std::move(flushFence));
1611 } else {
1612 // Cleanup for hygiene.
1613 getBE().flushFence = Fence::NO_FENCE;
1614 }
1615 }
1616
Jorim Jaggi90535212018-05-23 23:44:06 +02001617 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001618
David Sodman7e4ae112018-02-09 15:02:28 -08001619 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001620 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001621 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001622 compositionInfo.hwc.hwcLayer = nullptr;
1623 }
David Sodmanba340492018-08-05 21:51:33 -07001624 }
David Sodman7e4ae112018-02-09 15:02:28 -08001625
1626 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001627}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001628
David Sodmanfa9b2af2017-12-24 13:28:59 -08001629
1630bool SurfaceFlinger::handleMessageInvalidate() {
1631 ATRACE_CALL();
1632 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001633}
1634
David Sodman79bba0e2018-08-05 18:07:49 -07001635void SurfaceFlinger::calculateWorkingSet() {
1636 ATRACE_CALL();
1637 ALOGV(__FUNCTION__);
1638
David Sodman79bba0e2018-08-05 18:07:49 -07001639 // build the h/w work list
1640 if (CC_UNLIKELY(mGeometryInvalid)) {
1641 mGeometryInvalid = false;
1642 for (const auto& [token, display] : mDisplays) {
1643 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001644 if (!displayId) {
1645 continue;
1646 }
David Sodman79bba0e2018-08-05 18:07:49 -07001647
Dominik Laskowski075d3172018-05-24 15:50:06 -07001648 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
1649 for (size_t i = 0; i < currentLayers.size(); i++) {
1650 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001651
Dominik Laskowski075d3172018-05-24 15:50:06 -07001652 if (!layer->hasHwcLayer(*displayId)) {
1653 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1654 layer->forceClientComposition(*displayId);
1655 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001656 }
1657 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001658
1659 layer->setGeometry(display, i);
1660 if (mDebugDisableHWC || mDebugRegion) {
1661 layer->forceClientComposition(*displayId);
1662 }
David Sodman79bba0e2018-08-05 18:07:49 -07001663 }
1664 }
1665 }
1666
1667 // Set the per-frame data
1668 for (const auto& [token, display] : mDisplays) {
1669 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001670 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001671 continue;
1672 }
1673
1674 if (mDrawingState.colorMatrixChanged) {
1675 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001676 status_t result =
1677 getHwComposer().setColorTransform(*displayId, mDrawingState.colorMatrix);
Dominik Laskowski34157762018-10-31 13:07:19 -07001678 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %s: %d",
1679 to_string(*displayId).c_str(), result);
David Sodman79bba0e2018-08-05 18:07:49 -07001680 }
1681 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1682 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001683 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001684 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1685 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1686 !display->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001687 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001688 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1689 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1690 !display->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001691 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001692 }
1693
Peiyong Lind3788632018-09-18 16:01:31 -07001694 // TODO(b/111562338) remove when composer 2.3 is shipped.
1695 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001696 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001697 }
1698
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001699 if (layer->getRoundedCornerState().radius > 0.0f) {
1700 layer->forceClientComposition(*displayId);
1701 }
1702
Dominik Laskowski075d3172018-05-24 15:50:06 -07001703 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001704 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001705 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001706 continue;
1707 }
1708
Dominik Laskowski075d3172018-05-24 15:50:06 -07001709 layer->setPerFrameData(*displayId, display->getTransform(), display->getViewport(),
1710 display->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001711 }
1712
Peiyong Lin13effd12018-07-24 17:01:47 -07001713 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001714 ColorMode colorMode;
1715 Dataspace dataSpace;
1716 RenderIntent renderIntent;
1717 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1718 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1719 }
1720 }
1721
1722 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001723
1724 for (const auto& [token, display] : mDisplays) {
1725 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001726 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001727 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001728
1729 if (displayId) {
1730 if (!layer->setHwcLayer(*displayId)) {
1731 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1732 }
1733 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001734 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001735
Dominik Laskowski05275f12018-11-01 15:03:24 -07001736 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001737 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1738 }
1739 }
David Sodman79bba0e2018-08-05 18:07:49 -07001740}
1741
David Sodmanfa9b2af2017-12-24 13:28:59 -08001742void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001743{
1744 // is debugging enabled
1745 if (CC_LIKELY(!mDebugRegion))
1746 return;
1747
David Sodmanfa9b2af2017-12-24 13:28:59 -08001748 if (display->isPoweredOn()) {
1749 // transform the dirty region into this screen's coordinate space
1750 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1751 if (!dirtyRegion.isEmpty()) {
1752 // redraw the whole screen
1753 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001754
David Sodmanfa9b2af2017-12-24 13:28:59 -08001755 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001756 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001757 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001758
Alec Mouri0a9c7b82018-11-16 13:05:25 -08001759 display->queueBuffer(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001760 }
1761 }
1762
David Sodmanfa9b2af2017-12-24 13:28:59 -08001763 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001764
1765 if (mDebugRegion > 1) {
1766 usleep(mDebugRegion * 1000);
1767 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001768
Dominik Laskowski05275f12018-11-01 15:03:24 -07001769 prepareFrame(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001770}
1771
Adrian Roos1e1a1282017-11-01 19:05:31 +01001772void SurfaceFlinger::doTracing(const char* where) {
1773 ATRACE_CALL();
1774 ATRACE_NAME(where);
1775 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001776 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001777 }
1778}
1779
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001780void SurfaceFlinger::logLayerStats() {
1781 ATRACE_CALL();
1782 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001783 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001784 if (display->isPrimary()) {
1785 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001786 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001787 }
1788 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001789
1790 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001791 }
1792}
1793
David Sodman2b406362017-12-15 13:33:47 -08001794void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001795{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001796 ATRACE_CALL();
1797 ALOGV("preComposition");
1798
David Sodman2b406362017-12-15 13:33:47 -08001799 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1800
Mathias Agopiancd60f992012-08-16 16:28:27 -07001801 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001802 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001803 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001804 needExtraInvalidate = true;
1805 }
Robert Carr2047fae2016-11-28 14:09:09 -08001806 });
1807
Mathias Agopiancd60f992012-08-16 16:28:27 -07001808 if (needExtraInvalidate) {
1809 signalLayerUpdate();
1810 }
1811}
1812
Ana Krulece588e312018-09-18 12:32:24 -07001813void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1814 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001815 // Update queue of past composite+present times and determine the
1816 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001817 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001818 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001819 while (!getBE().mCompositePresentTimes.empty()) {
1820 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001821 // Cached values should have been updated before calling this method,
1822 // which helps avoid duplicate syscalls.
1823 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1824 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1825 break;
1826 }
1827 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001828 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001829 }
1830
1831 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001832 while (getBE().mCompositePresentTimes.size() > 16) {
1833 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001834 }
1835
Ana Krulece588e312018-09-18 12:32:24 -07001836 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001837}
1838
Ana Krulece588e312018-09-18 12:32:24 -07001839void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1840 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001841 // Integer division and modulo round toward 0 not -inf, so we need to
1842 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001843 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1844 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1845 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001846
Brian Andersond0010582017-03-07 13:20:31 -08001847 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1848 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001849 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001850 }
1851
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001852 // Snap the latency to a value that removes scheduling jitter from the
1853 // composition and present times, which often have >1ms of jitter.
1854 // Reducing jitter is important if an app attempts to extrapolate
1855 // something (such as user input) to an accurate diasplay time.
1856 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1857 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001858 nsecs_t bias = stats.vsyncPeriod / 2;
1859 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1860 nsecs_t snappedCompositeToPresentLatency =
1861 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001862
David Sodman99974d22017-11-28 12:04:33 -08001863 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001864 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1865 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001866 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001867}
1868
David Sodman2b406362017-12-15 13:33:47 -08001869void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001870{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001871 ATRACE_CALL();
1872 ALOGV("postComposition");
1873
Brian Anderson3546a3f2016-07-14 11:51:14 -07001874 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001875 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001876 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001877 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001878 }
1879
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001880 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001881 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001882
David Sodman73beded2017-11-15 11:56:06 -08001883 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001884 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001885 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001886 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001887 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001888 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001889 } else {
1890 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1891 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001892
David Sodman73beded2017-11-15 11:56:06 -08001893 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001894 mPreviousPresentFence =
Dominik Laskowski075d3172018-05-24 15:50:06 -07001895 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001896 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001897 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001898
Ana Krulece588e312018-09-18 12:32:24 -07001899 DisplayStatInfo stats;
1900 if (mUseScheduler) {
1901 mScheduler->getDisplayStatInfo(&stats);
1902 } else {
1903 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1904 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
1905 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001906
David Sodman2b406362017-12-15 13:33:47 -08001907 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001908 // when we started doing work for this frame, but that should be okay
1909 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07001910 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001911 CompositorTiming compositorTiming;
1912 {
David Sodman99974d22017-11-28 12:04:33 -08001913 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1914 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001915 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001916
Robert Carr2047fae2016-11-28 14:09:09 -08001917 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001918 bool frameLatched = layer->onPostComposition(display->getId(), glCompositionDoneFenceTime,
1919 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001920 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001921 recordBufferingStats(layer->getName().string(),
1922 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001923 }
Robert Carr2047fae2016-11-28 14:09:09 -08001924 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001925
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001926 if (presentFenceTime->isValid()) {
Ana Krulece588e312018-09-18 12:32:24 -07001927 if (mUseScheduler) {
1928 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001929 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001930 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
1931 enableHardwareVsync();
1932 } else {
1933 disableHardwareVsync(false);
1934 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001935 }
1936 }
1937
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001938 if (!hasSyncFramework) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001939 if (display && getHwComposer().isConnected(*display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07001940 if (mUseScheduler) {
1941 mScheduler->enableHardwareVsync();
1942 } else {
1943 enableHardwareVsync();
1944 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001945 }
1946 }
1947
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001948 if (mAnimCompositionPending) {
1949 mAnimCompositionPending = false;
1950
Brian Anderson4e606e32017-03-16 15:34:57 -07001951 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001952 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001953 std::move(presentFenceTime));
Dominik Laskowski075d3172018-05-24 15:50:06 -07001954 } else if (display && getHwComposer().isConnected(*display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001955 // The HWC doesn't support present fences, so use the refresh
1956 // timestamp instead.
Dominik Laskowski075d3172018-05-24 15:50:06 -07001957 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001958 mAnimFrameTracker.setActualPresentTime(presentTime);
1959 }
1960 mAnimFrameTracker.advanceFrame();
1961 }
Dan Stozab90cf072015-03-05 11:05:59 -08001962
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001963 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001964 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001965 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001966 }
1967
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001968 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001969
Dominik Laskowski075d3172018-05-24 15:50:06 -07001970 if (display && getHwComposer().isConnected(*display->getId()) && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08001971 return;
1972 }
1973
1974 nsecs_t currentTime = systemTime();
1975 if (mHasPoweredOff) {
1976 mHasPoweredOff = false;
1977 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001978 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001979 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001980 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1981 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001982 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001983 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001984 }
David Sodman4a36e932017-11-07 14:29:47 -08001985 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001986 }
David Sodman4a36e932017-11-07 14:29:47 -08001987 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001988
1989 {
1990 std::lock_guard lock(mTexturePoolMutex);
1991 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1992 if (refillCount > 0) {
1993 const size_t offset = mTexturePool.size();
1994 mTexturePool.resize(mTexturePoolSize);
1995 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1996 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1997 }
1998 }
Marissa Walle2ffb422018-10-12 11:33:52 -07001999
Marissa Wallfda30bb2018-10-12 11:34:28 -07002000 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002001 mTransactionCompletedThread.sendCallbacks();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002002}
2003
2004void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002005 ATRACE_CALL();
2006 ALOGV("rebuildLayerStacks");
2007
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002008 // We need to clear these out now as these may be holding on to a
2009 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2010 // also holds a reference. When the set of visible layers is recomputed,
2011 // some layers may be destroyed if the only thing keeping them alive was
2012 // that list of visible layers associated with each display. The layer
2013 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2014 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2015 for (const auto& [token, display] : mDisplays) {
2016 getBE().mCompositionInfo[token].clear();
2017 }
2018
Mathias Agopiancd60f992012-08-16 16:28:27 -07002019 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002020 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002021 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002022 mVisibleRegionsDirty = false;
2023 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002024
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002025 for (const auto& pair : mDisplays) {
2026 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07002027 Region opaqueRegion;
2028 Region dirtyRegion;
2029 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002030 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07002031 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002032 const Rect bounds = display->getBounds();
2033 if (display->isPoweredOn()) {
2034 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002035
Jeff Sharkey76488112017-02-27 14:15:18 -07002036 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002037 bool hwcLayerDestroyed = false;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002038 const auto displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002039 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002040 Region drawRegion(tr.transform(
2041 layer->visibleNonTransparentRegion));
2042 drawRegion.andSelf(bounds);
2043 if (!drawRegion.isEmpty()) {
2044 layersSortedByZ.add(layer);
2045 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002046 // Clear out the HWC layer if this layer was
2047 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002048 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002049 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002050 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002051 // WM changes display->layerStack upon sleep/awake.
2052 // Here we make sure we delete the HWC layers even if
2053 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002054 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002055 }
2056
2057 // If a layer is not going to get a release fence because
2058 // it is invisible, but it is also going to release its
2059 // old buffer, add it to the list of layers needing
2060 // fences.
2061 if (hwcLayerDestroyed) {
2062 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2063 mLayersWithQueuedFrames.cend(), layer);
2064 if (found != mLayersWithQueuedFrames.cend()) {
2065 layersNeedingFences.add(layer);
2066 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002067 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002068 });
2069 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002070 display->setVisibleLayersSortedByZ(layersSortedByZ);
2071 display->setLayersNeedingFences(layersNeedingFences);
2072 display->undefinedRegion.set(bounds);
2073 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2074 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002075 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002076 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002077}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002078
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002079// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002080// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002081// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002082// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002083// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002084// The returned HDR data space is one of
2085// - Dataspace::UNKNOWN
2086// - Dataspace::BT2020_HLG
2087// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002088Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2089 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002090 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002091 *outHdrDataSpace = Dataspace::UNKNOWN;
2092
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002093 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002094 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002095 case Dataspace::V0_SCRGB:
2096 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002097 case Dataspace::BT2020:
2098 case Dataspace::BT2020_ITU:
2099 case Dataspace::BT2020_LINEAR:
2100 case Dataspace::DISPLAY_BT2020:
2101 bestDataSpace = Dataspace::DISPLAY_BT2020;
2102 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002103 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002104 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002105 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002106 case Dataspace::BT2020_PQ:
2107 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002108 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002109 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002110 case Dataspace::BT2020_HLG:
2111 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002112 // When there's mixed PQ content and HLG content, we set the HDR
2113 // data space to be BT2020_PQ and convert HLG to PQ.
2114 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2115 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002116 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002117 break;
2118 default:
2119 break;
2120 }
Romain Guy54f154a2017-10-24 21:40:32 +01002121 }
2122
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002123 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002124}
2125
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002126// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002127void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2128 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002129 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2130 *outMode = ColorMode::NATIVE;
2131 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002132 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002133 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002134 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002135
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002136 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002137 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002138
Peiyong Lindfde5112018-06-05 10:58:41 -07002139 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002140 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002141 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002142 if (isHdr) {
2143 bestDataSpace = hdrDataSpace;
2144 }
2145
Chia-I Wu0d711262018-05-21 15:19:35 -07002146 RenderIntent intent;
2147 switch (mDisplayColorSetting) {
2148 case DisplayColorSetting::MANAGED:
2149 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002150 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002151 break;
2152 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002153 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002154 break;
2155 default: // vendor display color setting
2156 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2157 break;
2158 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002159
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002160 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002161}
2162
David Sodmanfa9b2af2017-12-24 13:28:59 -08002163void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002164{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002165 bool dirty = !display->getDirtyRegion(false).isEmpty();
2166 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2167 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002168
David Sodmanfa9b2af2017-12-24 13:28:59 -08002169 // If nothing has changed (!dirty), don't recompose.
2170 // If something changed, but we don't currently have any visible layers,
2171 // and didn't when we last did a composition, then skip it this time.
2172 // The second rule does two things:
2173 // - When all layers are removed from a display, we'll emit one black
2174 // frame, then nothing more until we get new layers.
2175 // - When a display is created with a private layer stack, we won't
2176 // emit any black frames until a layer is added to the layer stack.
2177 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002178
Dominik Laskowski075d3172018-05-24 15:50:06 -07002179 const char flagPrefix[] = {'-', '+'};
2180 static_cast<void>(flagPrefix);
2181 ALOGV_IF(display->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2182 __FUNCTION__, mustRecompose ? "doing" : "skipping", display->getDebugName().c_str(),
2183 flagPrefix[dirty], flagPrefix[empty], flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002184
David Sodmanfa9b2af2017-12-24 13:28:59 -08002185 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002186
David Sodmanfa9b2af2017-12-24 13:28:59 -08002187 if (mustRecompose) {
2188 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002189 }
2190}
2191
David Sodmanfa9b2af2017-12-24 13:28:59 -08002192void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002193{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002194 if (!display->isPoweredOn()) {
2195 return;
David Sodman2b406362017-12-15 13:33:47 -08002196 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002197
Dominik Laskowski05275f12018-11-01 15:03:24 -07002198 status_t result = display->prepareFrame(getHwComposer(),
2199 getBE().mCompositionInfo[display->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002200 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
2201 display->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002202}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002203
David Sodmanfa9b2af2017-12-24 13:28:59 -08002204void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002205 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002206 ALOGV("doComposition");
2207
David Sodmanfa9b2af2017-12-24 13:28:59 -08002208 if (display->isPoweredOn()) {
2209 // transform the dirty region into this screen's coordinate space
2210 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002211
David Sodmanfa9b2af2017-12-24 13:28:59 -08002212 // repaint the framebuffer (if needed)
2213 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002214
David Sodmanfa9b2af2017-12-24 13:28:59 -08002215 display->dirtyRegion.clear();
2216 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002217 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002218 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002219}
2220
David Sodmanfa9b2af2017-12-24 13:28:59 -08002221void SurfaceFlinger::postFrame()
2222{
2223 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002224 const auto display = getDefaultDisplayDeviceLocked();
2225 if (display && getHwComposer().isConnected(*display->getId())) {
2226 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002227 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2228 logFrameStats();
2229 }
2230 }
2231}
2232
2233void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002234{
Mathias Agopian841cde52012-03-01 15:44:37 -08002235 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002236 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002237
David Sodmanfa9b2af2017-12-24 13:28:59 -08002238 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002239
David Sodmanfa9b2af2017-12-24 13:28:59 -08002240 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002241 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002242 if (displayId) {
2243 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002244 }
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002245 display->onPresentDisplayCompleted();
David Sodman15094112018-10-11 09:39:37 -07002246 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002247 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002248
Chia-I Wu7b549592017-11-15 09:14:57 -08002249 // The layer buffer from the previous frame (if any) is released
2250 // by HWC only when the release fence from this frame (if any) is
2251 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002252 if (displayId && layer->hasHwcLayer(*displayId)) {
2253 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2254 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002255 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002256
2257 // If the layer was client composited in the previous frame, we
2258 // need to merge with the previous client target acquire fence.
2259 // Since we do not track that, always merge with the current
2260 // client target acquire fence when it is available, even though
2261 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002262 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002263 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002264 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002265 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002266
David Sodman15094112018-10-11 09:39:37 -07002267 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002268 }
Chia-I Wu83806892017-11-16 10:50:20 -08002269
2270 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002271 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002272 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002273 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002274 sp<Fence> presentFence =
2275 displayId ? getBE().mHwc->getPresentFence(*displayId) : Fence::NO_FENCE;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002276 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002277 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002278 }
2279 }
2280
Dominik Laskowski075d3172018-05-24 15:50:06 -07002281 if (displayId) {
2282 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002283 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002284 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002285}
2286
Mathias Agopian87baae12012-07-31 12:38:26 -07002287void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002288{
Mathias Agopian841cde52012-03-01 15:44:37 -08002289 ATRACE_CALL();
2290
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002291 // here we keep a copy of the drawing state (that is the state that's
2292 // going to be overwritten by handleTransactionLocked()) outside of
2293 // mStateLock so that the side-effects of the State assignment
2294 // don't happen with mStateLock held (which can cause deadlocks).
2295 State drawingState(mDrawingState);
2296
Mathias Agopianca4d3602011-05-19 15:38:14 -07002297 Mutex::Autolock _l(mStateLock);
2298 const nsecs_t now = systemTime();
2299 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002300
Mathias Agopianca4d3602011-05-19 15:38:14 -07002301 // Here we're guaranteed that some transaction flags are set
2302 // so we can call handleTransactionLocked() unconditionally.
2303 // We call getTransactionFlags(), which will also clear the flags,
2304 // with mStateLock held to guarantee that mCurrentState won't change
2305 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002306
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002307 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002308 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002309 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002310
Mathias Agopianca4d3602011-05-19 15:38:14 -07002311 mLastTransactionTime = systemTime() - now;
2312 mDebugInTransaction = 0;
2313 invalidateHwcGeometry();
2314 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002315}
2316
Lloyd Piqueba04e622017-12-14 17:11:26 -08002317void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2318 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002319 const std::optional<DisplayIdentificationInfo> info =
2320 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002321
Dominik Laskowski075d3172018-05-24 15:50:06 -07002322 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002323 continue;
2324 }
2325
Lloyd Piqueba04e622017-12-14 17:11:26 -08002326 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002327 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002328 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002329 mPhysicalDisplayTokens[info->id] = new BBinder();
2330 DisplayDeviceState state;
2331 state.displayId = info->id;
2332 state.isSecure = true; // All physical displays are currently considered secure.
2333 state.displayName = info->name;
2334 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2335 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002336 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002337 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002338 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002339
Dominik Laskowski075d3172018-05-24 15:50:06 -07002340 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2341 if (index >= 0) {
2342 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2343 mInterceptor->saveDisplayDeletion(state.sequenceId);
2344 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002345 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002346 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002347 }
2348
2349 processDisplayChangesLocked();
2350 }
2351
2352 mPendingHotplugEvents.clear();
2353}
2354
Lloyd Pique99d3da52018-01-22 17:48:03 -08002355sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002356 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
2357 const DisplayDeviceState& state, const sp<DisplaySurface>& dispSurface,
2358 const sp<IGraphicBufferProducer>& producer) {
2359 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002360 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002361 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002362 creationArgs.isSecure = state.isSecure;
2363 creationArgs.displaySurface = dispSurface;
2364 creationArgs.hasWideColorGamut = false;
2365 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002366
Dominik Laskowski075d3172018-05-24 15:50:06 -07002367 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2368 creationArgs.isPrimary = isInternalDisplay;
2369
2370 if (useColorManagement && displayId) {
2371 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002372 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002373 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002374 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002375 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002376
Dominik Laskowski7e045462018-05-30 13:02:02 -07002377 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002378 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002379 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002380 }
tangrobin6753a022018-08-10 10:58:54 +08002381 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002382
Dominik Laskowski075d3172018-05-24 15:50:06 -07002383 if (displayId) {
2384 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002385 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002386 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002387 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002388
Lloyd Pique90c115d2018-09-18 21:39:42 -07002389 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002390 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002391 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002392
Lloyd Pique99d3da52018-01-22 17:48:03 -08002393 // Make sure that composition can never be stalled by a virtual display
2394 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002395 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002396 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002397 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2398 }
2399
Dominik Laskowski075d3172018-05-24 15:50:06 -07002400 creationArgs.displayInstallOrientation =
2401 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002402
Lloyd Pique99d3da52018-01-22 17:48:03 -08002403 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002404 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002405
Lloyd Pique90c115d2018-09-18 21:39:42 -07002406 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002407
2408 if (maxFrameBufferAcquiredBuffers >= 3) {
2409 nativeWindowSurface->preallocateBuffers();
2410 }
2411
2412 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002413 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002414 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002415 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002416 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002417 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002418 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002419 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002420 if (!state.isVirtual()) {
2421 LOG_ALWAYS_FATAL_IF(!displayId);
2422 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002423 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002424
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002425 display->setLayerStack(state.layerStack);
2426 display->setProjection(state.orientation, state.viewport, state.frame);
2427 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002428
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002429 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002430}
2431
Lloyd Pique347200f2017-12-14 17:00:15 -08002432void SurfaceFlinger::processDisplayChangesLocked() {
2433 // here we take advantage of Vector's copy-on-write semantics to
2434 // improve performance by skipping the transaction entirely when
2435 // know that the lists are identical
2436 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2437 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2438 if (!curr.isIdenticalTo(draw)) {
2439 mVisibleRegionsDirty = true;
2440 const size_t cc = curr.size();
2441 size_t dc = draw.size();
2442
2443 // find the displays that were removed
2444 // (ie: in drawing state but not in current state)
2445 // also handle displays that changed
2446 // (ie: displays that are in both lists)
2447 for (size_t i = 0; i < dc;) {
2448 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2449 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002450 // Save display IDs before disconnecting.
2451 const auto internalDisplayId = getInternalDisplayId();
2452 const auto externalDisplayId = getExternalDisplayId();
2453
Lloyd Pique347200f2017-12-14 17:00:15 -08002454 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002455 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2456 display->disconnect(getHwComposer());
2457 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002458 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002459 if (mUseScheduler) {
2460 mScheduler->hotplugReceived(mAppConnectionHandle,
2461 EventThread::DisplayType::Primary, false);
2462 } else {
2463 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2464 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002465 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002466 if (mUseScheduler) {
2467 mScheduler->hotplugReceived(mAppConnectionHandle,
2468 EventThread::DisplayType::External, false);
2469 } else {
2470 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2471 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002472 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002473 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002474 } else {
2475 // this display is in both lists. see if something changed.
2476 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002477 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002478 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2479 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2480 if (state_binder != draw_binder) {
2481 // changing the surface is like destroying and
2482 // recreating the DisplayDevice, so we just remove it
2483 // from the drawing state, so that it get re-added
2484 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002485 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2486 display->disconnect(getHwComposer());
2487 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002488 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002489 mDrawingState.displays.removeItemsAt(i);
2490 dc--;
2491 // at this point we must loop to the next item
2492 continue;
2493 }
2494
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002495 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002496 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002497 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002498 }
2499 if ((state.orientation != draw[i].orientation) ||
2500 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002501 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002502 }
2503 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002504 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002505 }
2506 }
2507 }
2508 ++i;
2509 }
2510
2511 // find displays that were added
2512 // (ie: in current state but not in drawing state)
2513 for (size_t i = 0; i < cc; i++) {
2514 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2515 const DisplayDeviceState& state(curr[i]);
2516
2517 sp<DisplaySurface> dispSurface;
2518 sp<IGraphicBufferProducer> producer;
2519 sp<IGraphicBufferProducer> bqProducer;
2520 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002521 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002522
Dominik Laskowski075d3172018-05-24 15:50:06 -07002523 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002524 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002525 // Virtual displays without a surface are dormant:
2526 // they have external state (layer stack, projection,
2527 // etc.) but no internal state (i.e. a DisplayDevice).
2528 if (state.surface != nullptr) {
2529 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002530 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002531 int width = 0;
2532 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2533 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2534 int height = 0;
2535 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2536 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2537 int intFormat = 0;
2538 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2539 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002540 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002541
Dominik Laskowski075d3172018-05-24 15:50:06 -07002542 displayId =
2543 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002544 }
2545
2546 // TODO: Plumb requested format back up to consumer
2547
2548 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002549 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002550 bqProducer, bqConsumer,
2551 state.displayName);
2552
2553 dispSurface = vds;
2554 producer = vds;
2555 }
2556 } else {
2557 ALOGE_IF(state.surface != nullptr,
2558 "adding a supported display, but rendering "
2559 "surface is provided (%p), ignoring it",
2560 state.surface.get());
2561
Dominik Laskowski075d3172018-05-24 15:50:06 -07002562 displayId = state.displayId;
2563 LOG_ALWAYS_FATAL_IF(!displayId);
2564 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002565 producer = bqProducer;
2566 }
2567
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002568 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002569 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002570 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002571 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002572 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002573 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002574 LOG_ALWAYS_FATAL_IF(!displayId);
2575
2576 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002577 if (mUseScheduler) {
2578 mScheduler->hotplugReceived(mAppConnectionHandle,
2579 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002580 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002581 } else {
2582 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2583 true);
2584 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002585 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002586 if (mUseScheduler) {
2587 mScheduler->hotplugReceived(mAppConnectionHandle,
2588 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002589 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002590 } else {
2591 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2592 true);
2593 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002594 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002595 }
2596 }
2597 }
2598 }
2599 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002600
2601 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002602}
2603
Mathias Agopian87baae12012-07-31 12:38:26 -07002604void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002605{
Dan Stoza7dde5992015-05-22 09:51:44 -07002606 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002607 mCurrentState.traverseInZOrder([](Layer* layer) {
2608 layer->notifyAvailableFrames();
2609 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002610
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002611 /*
2612 * Traversal of the children
2613 * (perform the transaction for each of them if needed)
2614 */
2615
Robert Carr720e5062018-07-30 17:45:14 -07002616 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002617 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002618 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002619 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002620 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002621
2622 const uint32_t flags = layer->doTransaction(0);
2623 if (flags & Layer::eVisibleRegion)
2624 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002625
2626 if (flags & Layer::eInputInfoChanged) {
2627 inputChanged = true;
2628 }
Robert Carr2047fae2016-11-28 14:09:09 -08002629 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002630 }
2631
2632 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002633 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002634 */
2635
Mathias Agopiane57f2922012-08-09 16:29:12 -07002636 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002637 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002638 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002639 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002640
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002641 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002642 // The transform hint might have changed for some layers
2643 // (either because a display has changed, or because a layer
2644 // as changed).
2645 //
2646 // Walk through all the layers in currentLayers,
2647 // and update their transform hint.
2648 //
2649 // If a layer is visible only on a single display, then that
2650 // display is used to calculate the hint, otherwise we use the
2651 // default display.
2652 //
2653 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2654 // the hint is set before we acquire a buffer from the surface texture.
2655 //
2656 // NOTE: layer transactions have taken place already, so we use their
2657 // drawing state. However, SurfaceFlinger's own transaction has not
2658 // happened yet, so we must use the current state layer list
2659 // (soon to become the drawing state list).
2660 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002661 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002662 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002663 bool first = true;
2664 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002665 // NOTE: we rely on the fact that layers are sorted by
2666 // layerStack first (so we don't have to traverse the list
2667 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002668 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002669 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002670 currentlayerStack = layerStack;
2671 // figure out if this layerstack is mirrored
2672 // (more than one display) if so, pick the default display,
2673 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002674 hintDisplay = nullptr;
2675 for (const auto& [token, display] : mDisplays) {
2676 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2677 if (hintDisplay) {
2678 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002679 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002680 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002681 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002682 }
2683 }
2684 }
2685 }
Chet Haase91d25932013-04-11 15:24:55 -07002686
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002687 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002688 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2689 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002690
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002691 // could be null when this layer is using a layerStack
2692 // that is not visible on any display. Also can occur at
2693 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002694 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002695 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002696
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002697 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002698 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002699 if (hintDisplay) {
2700 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002701 }
Robert Carr2047fae2016-11-28 14:09:09 -08002702
2703 first = false;
2704 });
Mathias Agopian84300952012-11-21 16:02:13 -08002705 }
2706
2707
Mathias Agopian3559b072012-08-15 13:46:03 -07002708 /*
2709 * Perform our own transaction if needed
2710 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002711
2712 if (mLayersAdded) {
2713 mLayersAdded = false;
2714 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002715 mVisibleRegionsDirty = true;
2716 }
2717
2718 // some layers might have been removed, so
2719 // we need to update the regions they're exposing.
2720 if (mLayersRemoved) {
2721 mLayersRemoved = false;
2722 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002723 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002724 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002725 // this layer is not visible anymore
2726 // TODO: we could traverse the tree from front to back and
2727 // compute the actual visible region
2728 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002729 Region visibleReg;
2730 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002731 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002732 }
Robert Carr2047fae2016-11-28 14:09:09 -08002733 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002734 }
2735
2736 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002737
Vishnu Nairde19f852018-12-18 16:11:53 -08002738 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002739 updateInputWindows();
2740 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002741 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002742
Riley Andrews03414a12014-07-01 14:22:59 -07002743 updateCursorAsync();
2744}
2745
Robert Carr720e5062018-07-30 17:45:14 -07002746void SurfaceFlinger::updateInputWindows() {
2747 ATRACE_CALL();
2748
Vishnu Nairde19f852018-12-18 16:11:53 -08002749 if (mInputFlinger == nullptr) {
2750 return;
2751 }
2752
Robert Carr720e5062018-07-30 17:45:14 -07002753 Vector<InputWindowInfo> inputHandles;
2754
2755 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2756 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002757 // When calculating the screen bounds we ignore the transparent region since it may
2758 // result in an unwanted offset.
2759 inputHandles.add(layer->fillInputInfo(
2760 layer->computeScreenBounds(false /* reduceTransparentRegion */)));
Robert Carr720e5062018-07-30 17:45:14 -07002761 }
2762 });
2763 mInputFlinger->setInputWindows(inputHandles);
2764}
2765
chaviwfbe5d9c2018-12-26 12:23:37 -08002766void SurfaceFlinger::executeInputWindowCommands() {
2767 if (!mInputFlinger) {
2768 return;
2769 }
2770
2771 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2772 if (transferTouchFocusCommand.fromToken != nullptr &&
2773 transferTouchFocusCommand.toToken != nullptr &&
2774 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2775 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2776 transferTouchFocusCommand.toToken);
2777 }
2778 }
2779
2780 mInputWindowCommands.clear();
2781}
2782
Riley Andrews03414a12014-07-01 14:22:59 -07002783void SurfaceFlinger::updateCursorAsync()
2784{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002785 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002786 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002787 continue;
2788 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002789
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002790 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2791 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002792 }
2793 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002794}
2795
chaviw61626f22018-11-15 16:26:27 -08002796void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2797 if (layer->hasReadyFrame()) {
2798 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2799 if (layer->shouldPresentNow(expectedPresentTime)) {
2800 bool ignored = false;
2801 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
2802 }
2803 }
2804 layer->releasePendingBuffer(systemTime());
2805}
2806
Mathias Agopian4fec8732012-06-29 14:12:52 -07002807void SurfaceFlinger::commitTransaction()
2808{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002809 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002810 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002811 for (const auto& l : mLayersPendingRemoval) {
2812 recordBufferingStats(l->getName().string(),
2813 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002814
2815 // We need to release the HWC layers when the Layer is removed
2816 // from the current state otherwise the HWC layer just continues
2817 // showing at its last configured state until we eventually
2818 // abandon the buffer queue.
2819 if (l->isRemovedFromCurrentState()) {
Robert Carr3aee9892018-11-07 12:53:41 -08002820 l->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* child) {
chaviw61626f22018-11-15 16:26:27 -08002821 child->destroyHwcLayersForAllDisplays();
2822 latchAndReleaseBuffer(child);
Robert Carr3aee9892018-11-07 12:53:41 -08002823 });
Robert Carr2e102c92018-10-23 12:11:15 -07002824 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002825 }
2826 mLayersPendingRemoval.clear();
2827 }
2828
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002829 // If this transaction is part of a window animation then the next frame
2830 // we composite should be considered an animation as well.
2831 mAnimCompositionPending = mAnimTransactionPending;
2832
Mathias Agopian4fec8732012-06-29 14:12:52 -07002833 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002834 // clear the "changed" flags in current state
2835 mCurrentState.colorMatrixChanged = false;
2836
Robert Carr1f0a16a2016-10-24 16:27:39 -07002837 mDrawingState.traverseInZOrder([](Layer* layer) {
2838 layer->commitChildList();
2839 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002840 mTransactionPending = false;
2841 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002842 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002843}
2844
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002845void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2846 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002847 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002848 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002849
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002850 Region aboveOpaqueLayers;
2851 Region aboveCoveredLayers;
2852 Region dirty;
2853
Mathias Agopian87baae12012-07-31 12:38:26 -07002854 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002855
Robert Carr2047fae2016-11-28 14:09:09 -08002856 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Jesse Hall01e29052013-02-19 16:13:35 -08002857 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002858 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002859 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002860 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002861
Mathias Agopianab028732010-03-16 16:41:46 -07002862 /*
2863 * opaqueRegion: area of a surface that is fully opaque.
2864 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002865 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002866
2867 /*
2868 * visibleRegion: area of a surface that is visible on screen
2869 * and not fully transparent. This is essentially the layer's
2870 * footprint minus the opaque regions above it.
2871 * Areas covered by a translucent surface are considered visible.
2872 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002873 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002874
2875 /*
2876 * coveredRegion: area of a surface that is covered by all
2877 * visible regions above it (which includes the translucent areas).
2878 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002879 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002880
Jesse Halla8026d22012-09-25 13:25:04 -07002881 /*
2882 * transparentRegion: area of a surface that is hinted to be completely
2883 * transparent. This is only used to tell when the layer has no visible
2884 * non-transparent regions and can be removed from the layer list. It
2885 * does not affect the visibleRegion of this layer or any layers
2886 * beneath it. The hint may not be correct if apps don't respect the
2887 * SurfaceView restrictions (which, sadly, some don't).
2888 */
2889 Region transparentRegion;
2890
Mathias Agopianab028732010-03-16 16:41:46 -07002891
2892 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002893 if (CC_LIKELY(layer->isVisible())) {
Ady Abraham83729882018-12-07 12:26:48 -08002894 const bool translucent = !layer->isDrawingOpaque();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002895 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07002896
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002897 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002898 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002899 if (!visibleRegion.isEmpty()) {
2900 // Remove the transparent area from the visible region
2901 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002902 if (tr.preserveRects()) {
2903 // transform the transparent region
Ady Abraham83729882018-12-07 12:26:48 -08002904 transparentRegion =
2905 tr.transform(layer->getDrawingActiveTransparentRegion());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002906 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002907 // transformation too complex, can't do the
2908 // transparent region optimization.
2909 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002910 }
Mathias Agopianab028732010-03-16 16:41:46 -07002911 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002912
Mathias Agopianab028732010-03-16 16:41:46 -07002913 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002914 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002915 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002916 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002917 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002918 // the opaque region is the layer's footprint
2919 opaqueRegion = visibleRegion;
2920 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002921 }
2922 }
2923
Robert Carre5f4f692018-01-12 13:12:28 -08002924 if (visibleRegion.isEmpty()) {
2925 layer->clearVisibilityRegions();
2926 return;
2927 }
2928
Mathias Agopianab028732010-03-16 16:41:46 -07002929 // Clip the covered region to the visible region
2930 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2931
2932 // Update aboveCoveredLayers for next (lower) layer
2933 aboveCoveredLayers.orSelf(visibleRegion);
2934
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002935 // subtract the opaque region covered by the layers above us
2936 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002937
2938 // compute this layer's dirty region
2939 if (layer->contentDirty) {
2940 // we need to invalidate the whole region
2941 dirty = visibleRegion;
2942 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002943 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002944 layer->contentDirty = false;
2945 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002946 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002947 * the exposed region consists of two components:
2948 * 1) what's VISIBLE now and was COVERED before
2949 * 2) what's EXPOSED now less what was EXPOSED before
2950 *
2951 * note that (1) is conservative, we start with the whole
2952 * visible region but only keep what used to be covered by
2953 * something -- which mean it may have been exposed.
2954 *
2955 * (2) handles areas that were not covered by anything but got
2956 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002957 */
Mathias Agopianab028732010-03-16 16:41:46 -07002958 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002959 const Region oldVisibleRegion = layer->visibleRegion;
2960 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002961 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2962 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002963 }
2964 dirty.subtractSelf(aboveOpaqueLayers);
2965
2966 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002967 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002968
Mathias Agopianab028732010-03-16 16:41:46 -07002969 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002970 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002971
Jesse Halla8026d22012-09-25 13:25:04 -07002972 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002973 layer->setVisibleRegion(visibleRegion);
2974 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002975 layer->setVisibleNonTransparentRegion(
2976 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002977 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002978
Mathias Agopian87baae12012-07-31 12:38:26 -07002979 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002980}
2981
Chia-I Wuab0c3192017-08-01 11:29:00 -07002982void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002983 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002984 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2985 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002986 }
2987 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002988}
2989
Dan Stoza6b9454d2014-11-07 16:00:59 -08002990bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002991{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002992 ALOGV("handlePageFlip");
2993
Brian Andersond6927fb2016-07-23 23:37:30 -07002994 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002995
Mathias Agopian4fec8732012-06-29 14:12:52 -07002996 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002997 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002998 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002999
3000 // Store the set of layers that need updates. This set must not change as
3001 // buffers are being latched, as this could result in a deadlock.
3002 // Example: Two producers share the same command stream and:
3003 // 1.) Layer 0 is latched
3004 // 2.) Layer 0 gets a new frame
3005 // 2.) Layer 1 gets a new frame
3006 // 3.) Layer 1 is latched.
3007 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3008 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003009 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003010 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003011 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003012 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3013 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003014 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003015 } else {
3016 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003017 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003018 } else {
3019 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003020 }
Robert Carr2047fae2016-11-28 14:09:09 -08003021 });
3022
Dan Stoza9e56aa02015-11-02 13:00:03 -08003023 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri86770e52018-09-24 22:40:58 +00003024 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
Dan Stozaee44edd2015-03-23 15:50:23 -07003025 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003026 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07003027 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06003028 newDataLatched = true;
3029 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003030 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003031
Alec Mouri86770e52018-09-24 22:40:58 +00003032 // Clear the renderengine fence here...
3033 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3034 // clear instead of sp::clear.
3035 getBE().flushFence = Fence::NO_FENCE;
3036
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003037 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003038
Vishnu Nairde19f852018-12-18 16:11:53 -08003039 if (visibleRegions) {
3040 // Update input window info if the layer receives its first buffer.
3041 updateInputWindows();
3042 }
3043
Dan Stoza6b9454d2014-11-07 16:00:59 -08003044 // If we will need to wake up at some time in the future to deal with a
3045 // queued frame that shouldn't be displayed during this vsync period, wake
3046 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003047 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003048 signalLayerUpdate();
3049 }
3050
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003051 // enter boot animation on first buffer latch
3052 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3053 ALOGI("Enter boot animation");
3054 mBootStage = BootStage::BOOTANIMATION;
3055 }
3056
Dan Stoza6b9454d2014-11-07 16:00:59 -08003057 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003058 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003059}
3060
Mathias Agopianad456f92011-01-13 17:53:01 -08003061void SurfaceFlinger::invalidateHwcGeometry()
3062{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003063 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003064}
3065
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003066void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& display,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003067 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003068 // We only need to actually compose the display if:
3069 // 1) It is being handled by hardware composer, which may need this to
3070 // keep its virtual display state machine in sync, or
3071 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski34157762018-10-31 13:07:19 -07003072 if (!display->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003073 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003074 return;
3075 }
3076
Dan Stoza9e56aa02015-11-02 13:00:03 -08003077 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003078 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003079
3080 // swap buffers (presentation)
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003081 display->queueBuffer(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003082}
3083
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003084bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003085 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003086
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003087 const Region bounds(display->bounds());
3088 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003089 const auto displayId = display->getId();
3090 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003091 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003092
Peiyong Lind3788632018-09-18 16:01:31 -07003093 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003094 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003095
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003096 // Framebuffer will live in this scope for GPU composition.
3097 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
3098
Dan Stoza9e56aa02015-11-02 13:00:03 -08003099 if (hasClientComposition) {
3100 ALOGV("hasClientComposition");
3101
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003102 sp<GraphicBuffer> buf = display->dequeueBuffer();
3103
3104 if (buf == nullptr) {
3105 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3106 "client composition for this frame",
3107 display->getDisplayName().c_str());
3108 return false;
3109 }
3110
3111 // Bind the framebuffer in this scope.
3112 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3113 buf->getNativeBuffer());
3114
3115 if (fbo->getStatus() != NO_ERROR) {
3116 ALOGW("Binding buffer for display [%s] failed with status: %d",
3117 display->getDisplayName().c_str(), fbo->getStatus());
3118 return false;
3119 }
3120
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003121 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003122 if (display->hasWideColorGamut()) {
3123 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003124 }
3125 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003126 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003127 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003128
Dominik Laskowski7e045462018-05-30 13:02:02 -07003129 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003130 const bool skipClientColorTransform =
3131 getBE().mHwc
3132 ->hasDisplayCapability(displayId,
3133 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003134
Peiyong Lind3788632018-09-18 16:01:31 -07003135 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003136 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3137 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003138 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003139 }
3140
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003141 display->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003142
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003143 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003144 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003145 // when using overlays, we assume a fully transparent framebuffer
3146 // NOTE: we could reduce how much we need to clear, for instance
3147 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003148 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003149 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003150 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003151 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003152 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003153 // we're left with the letterbox region
3154 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003155 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003156
3157 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003158 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003159
Mathias Agopianb9494d52012-04-18 02:28:45 -07003160 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003161 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003162 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003163 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003164 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003165 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003166
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003167 const Rect& bounds = display->getBounds();
3168 const Rect& scissor = display->getScissor();
3169 if (scissor != bounds) {
3170 // scissor doesn't match the screen's dimensions, so we
3171 // need to clear everything outside of it and enable
3172 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003173
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003174 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003175 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003176 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003177 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003178
Mathias Agopian85d751c2012-08-29 16:59:24 -07003179 /*
3180 * and then, render the layers targeted at the framebuffer
3181 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003182
Dan Stoza9e56aa02015-11-02 13:00:03 -08003183 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003184 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003185 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003186 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003187 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003188 displayTransform.transform(layer->visibleRegion)));
3189 ALOGV("Layer: %s", layer->getName().string());
3190 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003191 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003192 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003193 case HWC2::Composition::Cursor:
3194 case HWC2::Composition::Device:
3195 case HWC2::Composition::Sideband:
3196 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003197 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003198 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Ady Abraham83729882018-12-07 12:26:48 -08003199 layer->isDrawingOpaque() && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003200 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003201 // never clear the very first layer since we're
3202 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003203 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003204 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003205 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003206 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003207 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003208 if (layer->hasColorTransform()) {
3209 mat4 tmpMatrix;
3210 if (applyColorMatrix) {
3211 tmpMatrix = mDrawingState.colorMatrix;
3212 }
3213 tmpMatrix *= layer->getColorTransform();
Peiyong Lind3788632018-09-18 16:01:31 -07003214 getRenderEngine().setColorTransform(tmpMatrix);
3215 } else {
3216 getRenderEngine().setColorTransform(colorMatrix);
3217 }
David Sodmanc1498e62018-09-12 14:36:26 -07003218 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003219 break;
3220 }
3221 default:
3222 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003223 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003224 } else {
3225 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003226 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003227 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003228 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003229
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003230 // Perform some cleanup steps if we used client composition.
3231 if (hasClientComposition) {
3232 getRenderEngine().setColorTransform(mat4());
3233 getBE().mRenderEngine->disableScissor();
3234 display->finishBuffer();
3235 // Clear out error flags here so that we don't wait until next
3236 // composition to log.
3237 getRenderEngine().checkErrors();
3238 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003239 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003240}
3241
Chia-I Wu28e3a252018-09-07 12:05:02 -07003242void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003243 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003244 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003245}
3246
Dan Stoza7d89d062015-04-30 13:29:25 -07003247status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003248 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003249 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003250 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003251 const sp<Layer>& parent,
3252 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003253{
Dan Stoza7d89d062015-04-30 13:29:25 -07003254 // add this layer to the current state list
3255 {
3256 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003257 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003258 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3259 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003260 return NO_MEMORY;
3261 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003262 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003263 mCurrentState.layersSortedByZ.add(lbc);
Robert Carrb89ea9d2018-12-10 13:01:14 -08003264 } else if (parent == nullptr || parent->isRemovedFromCurrentState()) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003265 ALOGE("addClientLayer called with a removed parent");
chaviw61626f22018-11-15 16:26:27 -08003266 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003267 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003268 parent->addChild(lbc);
3269 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003270
Yiwei Zhang243b3782018-05-15 17:40:04 -07003271 if (gbc != nullptr) {
3272 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3273 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3274 mMaxGraphicBufferProducerListSize,
3275 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3276 mGraphicBufferProducerList.size(),
3277 mMaxGraphicBufferProducerListSize, mNumLayers);
3278 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003279 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003280 }
3281
Mathias Agopian96f08192010-06-02 23:28:45 -07003282 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003283 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003284
Dan Stoza7d89d062015-04-30 13:29:25 -07003285 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003286}
3287
Robert Carr8d2711b2018-11-14 16:36:18 -08003288status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003289 Mutex::Autolock _l(mStateLock);
Robert Carr8d2711b2018-11-14 16:36:18 -08003290 return removeLayerLocked(mStateLock, layer);
chaviwca27f252018-02-06 16:46:39 -08003291}
Robert Carr7f9b8992017-03-10 11:08:39 -08003292
Robert Carr8d2711b2018-11-14 16:36:18 -08003293status_t SurfaceFlinger::removeLayerLocked(const Mutex& lock, const sp<Layer>& layer) {
chaviw5aedec92018-10-22 10:40:38 -07003294 if (layer->isLayerDetached()) {
3295 return NO_ERROR;
3296 }
3297
Robert Carr1f0a16a2016-10-24 16:27:39 -07003298 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003299 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003300 if (p != nullptr) {
Chia-I Wufae51c42017-06-15 12:53:59 -07003301 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003302 } else {
3303 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003304 }
3305
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003306 layer->onRemovedFromCurrentState();
Robert Carr2e102c92018-10-23 12:11:15 -07003307
3308 markLayerPendingRemovalLocked(lock, layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003309 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003310}
3311
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003312uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003313 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003314}
3315
Mathias Agopian3f844832013-08-07 21:24:32 -07003316uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003317 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003318}
3319
Mathias Agopian3f844832013-08-07 21:24:32 -07003320uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003321 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003322}
3323
3324uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003325 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003326 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003327 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003328 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003329 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003330 }
3331 return old;
3332}
3333
Marissa Wall713b63f2018-10-17 15:42:43 -07003334bool SurfaceFlinger::flushTransactionQueues() {
3335 Mutex::Autolock _l(mStateLock);
3336 auto it = mTransactionQueues.begin();
3337 while (it != mTransactionQueues.end()) {
3338 auto& [applyToken, transactionQueue] = *it;
3339
3340 while (!transactionQueue.empty()) {
3341 const auto& [states, displays, flags] = transactionQueue.front();
3342 if (composerStateContainsUnsignaledFences(states)) {
3343 break;
3344 }
chaviw273171b2018-12-26 11:46:30 -08003345 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003346 transactionQueue.pop();
3347 }
3348
3349 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3350 }
3351 return mTransactionQueues.empty();
3352}
3353
chaviwca27f252018-02-06 16:46:39 -08003354bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3355 for (const ComposerState& state : states) {
3356 // Here we need to check that the interface we're given is indeed
3357 // one of our own. A malicious client could give us a nullptr
3358 // IInterface, or one of its own or even one of our own but a
3359 // different type. All these situations would cause us to crash.
3360 if (state.client == nullptr) {
3361 return true;
3362 }
3363
3364 sp<IBinder> binder = IInterface::asBinder(state.client);
3365 if (binder == nullptr) {
3366 return true;
3367 }
3368
3369 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3370 return true;
3371 }
3372 }
3373 return false;
3374}
3375
Marissa Wall713b63f2018-10-17 15:42:43 -07003376bool SurfaceFlinger::composerStateContainsUnsignaledFences(const Vector<ComposerState>& states) {
3377 for (const ComposerState& state : states) {
3378 const layer_state_t& s = state.state;
3379 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3380 continue;
3381 }
3382 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
3383 return true;
3384 }
3385 }
3386 return false;
3387}
3388
3389void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3390 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003391 const sp<IBinder>& applyToken,
3392 const InputWindowCommands& inputWindowCommands) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003393 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003394 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003395
chaviwca27f252018-02-06 16:46:39 -08003396 if (containsAnyInvalidClientState(states)) {
3397 return;
3398 }
3399
Marissa Wall713b63f2018-10-17 15:42:43 -07003400 // If its TransactionQueue already has a pending TransactionState or if it is pending
3401 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
3402 composerStateContainsUnsignaledFences(states)) {
3403 mTransactionQueues[applyToken].emplace(states, displays, flags);
3404 setTransactionFlags(eTransactionNeeded);
3405 return;
3406 }
3407
chaviw273171b2018-12-26 11:46:30 -08003408 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003409}
3410
3411void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003412 const Vector<DisplayState>& displays, uint32_t flags,
3413 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003414 uint32_t transactionFlags = 0;
3415
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003416 if (flags & eAnimation) {
3417 // For window updates that are part of an animation we must wait for
3418 // previous animation "frames" to be handled.
3419 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003420 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003421 if (CC_UNLIKELY(err != NO_ERROR)) {
3422 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003423 // caller after a few seconds.
3424 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3425 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003426 mAnimTransactionPending = false;
3427 break;
3428 }
3429 }
3430 }
3431
chaviwca27f252018-02-06 16:46:39 -08003432 for (const DisplayState& display : displays) {
3433 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003434 }
3435
Marissa Walle2ffb422018-10-12 11:33:52 -07003436 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003437 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003438 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003439 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003440 // If the state doesn't require a traversal and there are callbacks, send them now
3441 if (!(clientStateFlags & eTraversalNeeded)) {
3442 mTransactionCompletedThread.sendCallbacks();
3443 }
3444 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003445
3446 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3447 // as destroyed should only occur after setting all other states. This is to allow for a
3448 // child re-parent to happen before marking its original parent as destroyed (which would
3449 // then mark the child as destroyed).
3450 for (const ComposerState& state : states) {
3451 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003452 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003453
chaviw273171b2018-12-26 11:46:30 -08003454 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3455
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003456 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3457 // anyway. This can be used as a flush mechanism for previous async transactions.
3458 // Empty animation transaction can be used to simulate back-pressure, so also force a
3459 // transaction for empty animation transactions.
3460 if (transactionFlags == 0 &&
3461 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003462 transactionFlags = eTransactionNeeded;
3463 }
3464
Mathias Agopian386aa982011-11-07 21:58:03 -08003465 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003466 if (mInterceptor->isEnabled()) {
3467 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003468 }
Irvel468051e2016-06-13 16:44:44 -07003469
Mathias Agopian386aa982011-11-07 21:58:03 -08003470 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003471 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3472 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003473 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003474
3475 // if this is a synchronous transaction, wait for it to take effect
3476 // before returning.
3477 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003478 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003479 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003480 if (flags & eAnimation) {
3481 mAnimTransactionPending = true;
3482 }
3483 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003484 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3485 if (CC_UNLIKELY(err != NO_ERROR)) {
3486 // just in case something goes wrong in SF, return to the
3487 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003488 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3489 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003490 break;
3491 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003492 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003493 }
3494}
3495
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003496uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3497 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3498 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003499
Mathias Agopiane57f2922012-08-09 16:29:12 -07003500 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003501 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3502
3503 const uint32_t what = s.what;
3504 if (what & DisplayState::eSurfaceChanged) {
3505 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3506 state.surface = s.surface;
3507 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003508 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003509 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003510 if (what & DisplayState::eLayerStackChanged) {
3511 if (state.layerStack != s.layerStack) {
3512 state.layerStack = s.layerStack;
3513 flags |= eDisplayTransactionNeeded;
3514 }
3515 }
3516 if (what & DisplayState::eDisplayProjectionChanged) {
3517 if (state.orientation != s.orientation) {
3518 state.orientation = s.orientation;
3519 flags |= eDisplayTransactionNeeded;
3520 }
3521 if (state.frame != s.frame) {
3522 state.frame = s.frame;
3523 flags |= eDisplayTransactionNeeded;
3524 }
3525 if (state.viewport != s.viewport) {
3526 state.viewport = s.viewport;
3527 flags |= eDisplayTransactionNeeded;
3528 }
3529 }
3530 if (what & DisplayState::eDisplaySizeChanged) {
3531 if (state.width != s.width) {
3532 state.width = s.width;
3533 flags |= eDisplayTransactionNeeded;
3534 }
3535 if (state.height != s.height) {
3536 state.height = s.height;
3537 flags |= eDisplayTransactionNeeded;
3538 }
3539 }
3540
Mathias Agopiane57f2922012-08-09 16:29:12 -07003541 return flags;
3542}
3543
Robert Carrd4ae7f32018-06-07 16:10:57 -07003544bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3545 IPCThreadState* ipc = IPCThreadState::self();
3546 const int pid = ipc->getCallingPid();
3547 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003548 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003549 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003550 return false;
3551 }
3552 return true;
3553}
3554
chaviwca27f252018-02-06 16:46:39 -08003555uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3556 const layer_state_t& s = composerState.state;
3557 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3558
Mathias Agopian13127d82013-03-05 17:47:11 -08003559 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003560 if (layer == nullptr) {
3561 return 0;
3562 }
3563
chaviw8b3871a2017-11-01 17:41:01 -07003564 uint32_t flags = 0;
3565
Garfield Tan8a3083e2018-12-03 13:21:07 -08003566 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003567 bool geometryAppliesWithResize =
3568 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003569
3570 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3571 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003572 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003573 layer->pushPendingState();
3574 }
3575
chaviw8b3871a2017-11-01 17:41:01 -07003576 if (what & layer_state_t::ePositionChanged) {
3577 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3578 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003579 }
chaviw8b3871a2017-11-01 17:41:01 -07003580 }
3581 if (what & layer_state_t::eLayerChanged) {
3582 // NOTE: index needs to be calculated before we update the state
3583 const auto& p = layer->getParent();
3584 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003585 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003586 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003587 mCurrentState.layersSortedByZ.removeAt(idx);
3588 mCurrentState.layersSortedByZ.add(layer);
3589 // we need traversal (state changed)
3590 // AND transaction (list changed)
3591 flags |= eTransactionNeeded|eTraversalNeeded;
3592 }
chaviw8b3871a2017-11-01 17:41:01 -07003593 } else {
3594 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003595 flags |= eTransactionNeeded|eTraversalNeeded;
3596 }
3597 }
chaviw8b3871a2017-11-01 17:41:01 -07003598 }
3599 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003600 // NOTE: index needs to be calculated before we update the state
3601 const auto& p = layer->getParent();
3602 if (p == nullptr) {
3603 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3604 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3605 mCurrentState.layersSortedByZ.removeAt(idx);
3606 mCurrentState.layersSortedByZ.add(layer);
3607 // we need traversal (state changed)
3608 // AND transaction (list changed)
3609 flags |= eTransactionNeeded|eTraversalNeeded;
3610 }
3611 } else {
3612 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3613 flags |= eTransactionNeeded|eTraversalNeeded;
3614 }
chaviw8b3871a2017-11-01 17:41:01 -07003615 }
3616 }
3617 if (what & layer_state_t::eSizeChanged) {
3618 if (layer->setSize(s.w, s.h)) {
3619 flags |= eTraversalNeeded;
3620 }
3621 }
3622 if (what & layer_state_t::eAlphaChanged) {
3623 if (layer->setAlpha(s.alpha))
3624 flags |= eTraversalNeeded;
3625 }
3626 if (what & layer_state_t::eColorChanged) {
3627 if (layer->setColor(s.color))
3628 flags |= eTraversalNeeded;
3629 }
Peiyong Lind3788632018-09-18 16:01:31 -07003630 if (what & layer_state_t::eColorTransformChanged) {
3631 if (layer->setColorTransform(s.colorTransform)) {
3632 flags |= eTraversalNeeded;
3633 }
3634 }
chaviw8b3871a2017-11-01 17:41:01 -07003635 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003636 // TODO: b/109894387
3637 //
3638 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3639 // rotation. To see the problem observe that if we have a square parent, and a child
3640 // of the same size, then we rotate the child 45 degrees around it's center, the child
3641 // must now be cropped to a non rectangular 8 sided region.
3642 //
3643 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3644 // private API, and the WindowManager only uses rotation in one case, which is on a top
3645 // level layer in which cropping is not an issue.
3646 //
3647 // However given that abuse of rotation matrices could lead to surfaces extending outside
3648 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3649 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3650 // transformations.
3651 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003652 flags |= eTraversalNeeded;
3653 }
3654 if (what & layer_state_t::eTransparentRegionChanged) {
3655 if (layer->setTransparentRegionHint(s.transparentRegion))
3656 flags |= eTraversalNeeded;
3657 }
3658 if (what & layer_state_t::eFlagsChanged) {
3659 if (layer->setFlags(s.flags, s.mask))
3660 flags |= eTraversalNeeded;
3661 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003662 if (what & layer_state_t::eCropChanged_legacy) {
3663 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003664 flags |= eTraversalNeeded;
3665 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003666 if (what & layer_state_t::eCornerRadiusChanged) {
3667 if (layer->setCornerRadius(s.cornerRadius))
3668 flags |= eTraversalNeeded;
3669 }
chaviw8b3871a2017-11-01 17:41:01 -07003670 if (what & layer_state_t::eLayerStackChanged) {
3671 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3672 // We only allow setting layer stacks for top level layers,
3673 // everything else inherits layer stack from its parent.
3674 if (layer->hasParent()) {
3675 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3676 layer->getName().string());
3677 } else if (idx < 0) {
3678 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3679 "that also does not appear in the top level layer list. Something"
3680 " has gone wrong.", layer->getName().string());
3681 } else if (layer->setLayerStack(s.layerStack)) {
3682 mCurrentState.layersSortedByZ.removeAt(idx);
3683 mCurrentState.layersSortedByZ.add(layer);
3684 // we need traversal (state changed)
3685 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003686 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003687 }
3688 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003689 if (what & layer_state_t::eDeferTransaction_legacy) {
3690 if (s.barrierHandle_legacy != nullptr) {
3691 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3692 } else if (s.barrierGbp_legacy != nullptr) {
3693 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003694 if (authenticateSurfaceTextureLocked(gbp)) {
3695 const auto& otherLayer =
3696 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003697 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003698 } else {
3699 ALOGE("Attempt to defer transaction to to an"
3700 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003701 }
3702 }
chaviw8b3871a2017-11-01 17:41:01 -07003703 // We don't trigger a traversal here because if no other state is
3704 // changed, we don't want this to cause any more work
3705 }
3706 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003707 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003708 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003709 if (!hadParent) {
3710 mCurrentState.layersSortedByZ.remove(layer);
3711 }
chaviw8b3871a2017-11-01 17:41:01 -07003712 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003713 }
chaviw8b3871a2017-11-01 17:41:01 -07003714 }
3715 if (what & layer_state_t::eReparentChildren) {
3716 if (layer->reparentChildren(s.reparentHandle)) {
3717 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003718 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003719 }
chaviw8b3871a2017-11-01 17:41:01 -07003720 if (what & layer_state_t::eDetachChildren) {
3721 layer->detachChildren();
3722 }
3723 if (what & layer_state_t::eOverrideScalingModeChanged) {
3724 layer->setOverrideScalingMode(s.overrideScalingMode);
3725 // We don't trigger a traversal here because if no other state is
3726 // changed, we don't want this to cause any more work
3727 }
Marissa Wall61c58622018-07-18 10:12:20 -07003728 if (what & layer_state_t::eTransformChanged) {
3729 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3730 }
3731 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3732 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3733 flags |= eTraversalNeeded;
3734 }
3735 if (what & layer_state_t::eCropChanged) {
3736 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3737 }
Marissa Wall861616d2018-10-22 12:52:23 -07003738 if (what & layer_state_t::eFrameChanged) {
3739 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3740 }
Marissa Wall61c58622018-07-18 10:12:20 -07003741 if (what & layer_state_t::eBufferChanged) {
3742 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3743 }
3744 if (what & layer_state_t::eAcquireFenceChanged) {
3745 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3746 }
3747 if (what & layer_state_t::eDataspaceChanged) {
3748 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3749 }
3750 if (what & layer_state_t::eHdrMetadataChanged) {
3751 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3752 }
3753 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3754 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3755 }
3756 if (what & layer_state_t::eApiChanged) {
3757 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3758 }
3759 if (what & layer_state_t::eSidebandStreamChanged) {
3760 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3761 }
Robert Carr720e5062018-07-30 17:45:14 -07003762 if (what & layer_state_t::eInputInfoChanged) {
3763 layer->setInputInfo(s.inputInfo);
3764 flags |= eTraversalNeeded;
3765 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003766 std::vector<sp<CallbackHandle>> callbackHandles;
3767 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3768 mTransactionCompletedThread.run();
3769 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3770 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3771 }
3772 }
3773 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3774 // Do not put anything that updates layer state or modifies flags after
3775 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003776 return flags;
3777}
3778
chaviwca27f252018-02-06 16:46:39 -08003779void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3780 const layer_state_t& state = composerState.state;
3781 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3782
3783 sp<Layer> layer(client->getLayerUser(state.surface));
3784 if (layer == nullptr) {
3785 return;
3786 }
3787
chaviwca27f252018-02-06 16:46:39 -08003788 if (state.what & layer_state_t::eDestroySurface) {
3789 removeLayerLocked(mStateLock, layer);
3790 }
3791}
3792
chaviw273171b2018-12-26 11:46:30 -08003793uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3794 uint32_t flags = 0;
3795 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3796 flags |= eTraversalNeeded;
3797 }
3798
3799 mInputWindowCommands.merge(inputWindowCommands);
3800 return flags;
3801}
3802
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003803status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003804 const String8& name,
3805 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003806 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003807 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003808 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003809{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003810 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003811 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003812 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003813 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003814 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003815
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003816 status_t result = NO_ERROR;
3817
3818 sp<Layer> layer;
3819
Cody Northropbc755282017-03-31 12:00:08 -06003820 String8 uniqueName = getUniqueLayerName(name);
3821
Mathias Agopian3165cc22012-08-08 19:42:09 -07003822 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003823 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003824 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3825 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003826
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003827 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003828 case ISurfaceComposerClient::eFXSurfaceBufferState:
3829 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3830 break;
chaviw13fdc492017-06-27 12:40:18 -07003831 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003832 // check if buffer size is set for color layer.
3833 if (w > 0 || h > 0) {
3834 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3835 int(w), int(h));
3836 return BAD_VALUE;
3837 }
3838
chaviw13fdc492017-06-27 12:40:18 -07003839 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003840 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003841 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003842 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003843 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003844 // check if buffer size is set for container layer.
3845 if (w > 0 || h > 0) {
3846 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3847 int(w), int(h));
3848 return BAD_VALUE;
3849 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07003850 result = createContainerLayer(client,
3851 uniqueName, w, h, flags,
3852 handle, &layer);
3853 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003854 default:
3855 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003856 break;
3857 }
3858
Dan Stoza7d89d062015-04-30 13:29:25 -07003859 if (result != NO_ERROR) {
3860 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003861 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003862
Chia-I Wuab0c3192017-08-01 11:29:00 -07003863 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3864 // TODO b/64227542
3865 if (windowType == 441731) {
3866 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3867 layer->setPrimaryDisplayOnly();
3868 }
3869
Albert Chaulk479c60c2017-01-27 14:21:34 -05003870 layer->setInfo(windowType, ownerUid);
3871
Robert Carrb89ea9d2018-12-10 13:01:14 -08003872 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
3873 result = addClientLayer(client, *handle, *gbp, layer, *parent,
3874 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003875 if (result != NO_ERROR) {
3876 return result;
3877 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003878 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003879
3880 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003881 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003882}
3883
Cody Northropbc755282017-03-31 12:00:08 -06003884String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3885{
3886 bool matchFound = true;
3887 uint32_t dupeCounter = 0;
3888
3889 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3890 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3891
Dan Stoza436ccf32018-06-21 12:10:12 -07003892 // Grab the state lock since we're accessing mCurrentState
3893 Mutex::Autolock lock(mStateLock);
3894
Cody Northropbc755282017-03-31 12:00:08 -06003895 // Loop over layers until we're sure there is no matching name
3896 while (matchFound) {
3897 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003898 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003899 if (layer->getName() == uniqueName) {
3900 matchFound = true;
3901 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3902 }
3903 });
3904 }
3905
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003906 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3907 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003908
3909 return uniqueName;
3910}
3911
Marissa Wallfd668622018-05-10 10:21:13 -07003912status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3913 uint32_t w, uint32_t h, uint32_t flags,
3914 PixelFormat& format, sp<IBinder>* handle,
3915 sp<IGraphicBufferProducer>* gbp,
3916 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003917 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003918 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003919 case PIXEL_FORMAT_TRANSPARENT:
3920 case PIXEL_FORMAT_TRANSLUCENT:
3921 format = PIXEL_FORMAT_RGBA_8888;
3922 break;
3923 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003924 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003925 break;
3926 }
3927
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003928 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003929 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003930 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003931 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003932 *handle = layer->getHandle();
3933 *gbp = layer->getProducer();
3934 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003935 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003936
Marissa Wallfd668622018-05-10 10:21:13 -07003937 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003938 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003939}
3940
Marissa Wall61c58622018-07-18 10:12:20 -07003941status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3942 uint32_t w, uint32_t h, uint32_t flags,
3943 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003944 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003945 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003946 *handle = layer->getHandle();
3947 *outLayer = layer;
3948
3949 return NO_ERROR;
3950}
3951
chaviw13fdc492017-06-27 12:40:18 -07003952status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003953 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003954 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003955{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003956 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003957 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003958 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003959}
3960
Robert Carr6b3f6c52018-08-13 13:05:17 -07003961status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3962 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3963 sp<IBinder>* handle, sp<Layer>* outLayer)
3964{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003965 *outLayer =
3966 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003967 *handle = (*outLayer)->getHandle();
3968 return NO_ERROR;
3969}
3970
3971
Mathias Agopianac9fa422013-02-11 16:40:36 -08003972status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003973{
Robert Carr9524cb32017-02-13 11:32:32 -08003974 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003975 status_t err = NO_ERROR;
3976 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003977 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003978 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003979 err = removeLayer(l);
3980 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3981 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003982 }
3983 return err;
3984}
3985
Robert Carr2e102c92018-10-23 12:11:15 -07003986void SurfaceFlinger::markLayerPendingRemovalLocked(const Mutex&, const sp<Layer>& layer) {
3987 mLayersPendingRemoval.add(layer);
3988 mLayersRemoved = true;
3989 setTransactionFlags(eTransactionNeeded);
3990}
3991
Robert Carr695d5282018-12-18 15:27:58 -08003992void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003993{
Robert Carr2e102c92018-10-23 12:11:15 -07003994 Mutex::Autolock lock(mStateLock);
3995 markLayerPendingRemovalLocked(mStateLock, layer);
Robert Carr695d5282018-12-18 15:27:58 -08003996 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003997}
3998
Mathias Agopianb60314a2012-04-10 22:09:54 -07003999// ---------------------------------------------------------------------------
4000
Andy McFadden13a082e2012-08-24 10:16:42 -07004001void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004002 const auto displayToken = getInternalDisplayToken();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004003 if (!displayToken) return;
4004
Jesse Hall01e29052013-02-19 16:13:35 -08004005 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004006 Vector<ComposerState> state;
4007 Vector<DisplayState> displays;
4008 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004009 d.what = DisplayState::eDisplayProjectionChanged |
4010 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004011 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08004012 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004013 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004014 d.frame.makeInvalid();
4015 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004016 d.width = 0;
4017 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004018 displays.add(d);
chaviw273171b2018-12-26 11:46:30 -08004019 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004020
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004021 const auto display = getDisplayDevice(displayToken);
4022 if (!display) return;
4023
Dominik Laskowskie9774092018-12-11 10:04:24 -08004024 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004025
Dominik Laskowski075d3172018-05-24 15:50:06 -07004026 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08004027 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07004028 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004029
Brian Andersond0010582017-03-07 13:20:31 -08004030 // Use phase of 0 since phase is not known.
4031 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07004032 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
4033 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004034}
4035
4036void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004037 // Async since we may be called from the main thread.
4038 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004039}
4040
Dominik Laskowskie9774092018-12-11 10:04:24 -08004041void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004042 if (display->isVirtual()) {
4043 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004044 return;
4045 }
4046
Dominik Laskowski075d3172018-05-24 15:50:06 -07004047 const auto displayId = display->getId();
4048 LOG_ALWAYS_FATAL_IF(!displayId);
4049
Dominik Laskowski34157762018-10-31 13:07:19 -07004050 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004051
4052 int currentMode = display->getPowerMode();
4053 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004054 return;
4055 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004056
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004057 display->setPowerMode(mode);
4058
Lloyd Pique4dccc412018-01-22 17:21:36 -08004059 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004060 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004061 }
4062
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004063 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004064 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004065 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004066 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004067 if (mUseScheduler) {
4068 mScheduler->onScreenAcquired(mAppConnectionHandle);
4069 } else {
4070 mEventThread->onScreenAcquired();
4071 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004072 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004073 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004074
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004075 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004076 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004077 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004078
4079 struct sched_param param = {0};
4080 param.sched_priority = 1;
4081 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4082 ALOGW("Couldn't set SCHED_FIFO on display on");
4083 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004084 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004085 // Turn off the display
4086 struct sched_param param = {0};
4087 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4088 ALOGW("Couldn't set SCHED_OTHER on display off");
4089 }
4090
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004091 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004092 if (mUseScheduler) {
4093 mScheduler->disableHardwareVsync(true);
4094 } else {
4095 disableHardwareVsync(true); // also cancels any in-progress resync
4096 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004097 if (mUseScheduler) {
4098 mScheduler->onScreenReleased(mAppConnectionHandle);
4099 } else {
4100 mEventThread->onScreenReleased();
4101 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004102 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004103
Dominik Laskowski075d3172018-05-24 15:50:06 -07004104 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004105 mVisibleRegionsDirty = true;
4106 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004107 } else if (mode == HWC_POWER_MODE_DOZE ||
4108 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004109 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004110 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004111 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004112 if (mUseScheduler) {
4113 mScheduler->onScreenAcquired(mAppConnectionHandle);
4114 } else {
4115 mEventThread->onScreenAcquired();
4116 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004117 resyncToHardwareVsync(true);
4118 }
4119 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4120 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004121 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004122 if (mUseScheduler) {
4123 mScheduler->disableHardwareVsync(true);
4124 } else {
4125 disableHardwareVsync(true); // also cancels any in-progress resync
4126 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004127 if (mUseScheduler) {
4128 mScheduler->onScreenReleased(mAppConnectionHandle);
4129 } else {
4130 mEventThread->onScreenReleased();
4131 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004132 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004133 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004134 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004135 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004136 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004137 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004138
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004139 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004140 mTimeStats->setPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004141 }
4142
Dominik Laskowski34157762018-10-31 13:07:19 -07004143 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004144}
4145
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004146void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004147 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004148 const auto display = getDisplayDevice(displayToken);
4149 if (!display) {
4150 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4151 displayToken.get());
4152 } else if (display->isVirtual()) {
4153 ALOGW("Attempt to set power mode %d for virtual display", mode);
4154 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004155 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004156 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004157 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004158}
4159
4160// ---------------------------------------------------------------------------
4161
Lloyd Pique755e3192018-01-31 16:46:15 -08004162status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4163 NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004164 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004165
Mathias Agopianbd115332013-04-18 16:41:04 -07004166 IPCThreadState* ipc = IPCThreadState::self();
4167 const int pid = ipc->getCallingPid();
4168 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004169
Mathias Agopianbd115332013-04-18 16:41:04 -07004170 if ((uid != AID_SHELL) &&
4171 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004172 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4173 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004174 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004175 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004176 // (this would indicate SF is stuck, but we want to be able to
4177 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004178 status_t err = mStateLock.timedLock(s2ns(1));
4179 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004180 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004181 StringAppendF(&result,
4182 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4183 "(no locks held)\n",
4184 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004185 }
4186
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004187 bool dumpAll = true;
4188 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004189 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004190
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004191 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004192 if ((index < numArgs) &&
4193 (args[index] == String16("--list"))) {
4194 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004195 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004196 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004197 }
4198
4199 if ((index < numArgs) &&
4200 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004201 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004202 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004203 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004204 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004205
4206 if ((index < numArgs) &&
4207 (args[index] == String16("--latency-clear"))) {
4208 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004209 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004210 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004211 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004212
4213 if ((index < numArgs) &&
4214 (args[index] == String16("--dispsync"))) {
4215 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004216 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004217 dumpAll = false;
4218 }
Dan Stozab90cf072015-03-05 11:05:59 -08004219
4220 if ((index < numArgs) &&
4221 (args[index] == String16("--static-screen"))) {
4222 index++;
4223 dumpStaticScreenStats(result);
4224 dumpAll = false;
4225 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004226
4227 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004228 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004229 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004230 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004231 dumpAll = false;
4232 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004233
4234 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4235 index++;
4236 dumpWideColorInfo(result);
4237 dumpAll = false;
4238 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004239
4240 if ((index < numArgs) &&
4241 (args[index] == String16("--enable-layer-stats"))) {
4242 index++;
4243 mLayerStats.enable();
4244 dumpAll = false;
4245 }
4246
4247 if ((index < numArgs) &&
4248 (args[index] == String16("--disable-layer-stats"))) {
4249 index++;
4250 mLayerStats.disable();
4251 dumpAll = false;
4252 }
4253
4254 if ((index < numArgs) &&
4255 (args[index] == String16("--clear-layer-stats"))) {
4256 index++;
4257 mLayerStats.clear();
4258 dumpAll = false;
4259 }
4260
4261 if ((index < numArgs) &&
4262 (args[index] == String16("--dump-layer-stats"))) {
4263 index++;
4264 mLayerStats.dump(result);
4265 dumpAll = false;
4266 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004267
4268 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004269 (args[index] == String16("--frame-composition"))) {
4270 index++;
4271 dumpFrameCompositionInfo(result);
4272 dumpAll = false;
4273 }
4274
4275 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004276 (args[index] == String16("--display-identification"))) {
4277 index++;
4278 dumpDisplayIdentificationData(result);
4279 dumpAll = false;
4280 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004281
4282 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4283 index++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004284 mTimeStats->parseArgs(asProto, args, index, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004285 dumpAll = false;
4286 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004287 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004288
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004289 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004290 if (asProto) {
4291 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4292 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4293 } else {
4294 dumpAllLocked(args, index, result);
4295 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004296 }
4297
Mathias Agopian9795c422009-08-26 16:36:26 -07004298 if (locked) {
4299 mStateLock.unlock();
4300 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004301 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004302 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004303 return NO_ERROR;
4304}
4305
Yiwei Zhang5434a782018-12-05 18:06:32 -08004306void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */, size_t& /* index */,
4307 std::string& result) const {
4308 mCurrentState.traverseInZOrder(
4309 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004310}
4311
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004312void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004313 std::string& result) const {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004314 String8 name;
4315 if (index < args.size()) {
4316 name = String8(args[index]);
4317 index++;
4318 }
4319
Dominik Laskowski075d3172018-05-24 15:50:06 -07004320 if (const auto displayId = getInternalDisplayId();
4321 displayId && getHwComposer().isConnected(*displayId)) {
4322 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004323 const nsecs_t period = activeConfig->getVsyncPeriod();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004324 StringAppendF(&result, "%" PRId64 "\n", period);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004325 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004326
4327 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004328 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004329 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004330 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004331 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004332 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004333 }
Robert Carr2047fae2016-11-28 14:09:09 -08004334 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004335 }
4336}
4337
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004338void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004339 std::string& /* result */) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004340 String8 name;
4341 if (index < args.size()) {
4342 name = String8(args[index]);
4343 index++;
4344 }
4345
Robert Carr2047fae2016-11-28 14:09:09 -08004346 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004347 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004348 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004349 }
Robert Carr2047fae2016-11-28 14:09:09 -08004350 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004351
Svetoslavd85084b2014-03-20 10:28:31 -07004352 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004353}
4354
Jamie Gennis6547ff42013-07-16 20:12:42 -07004355// This should only be called from the main thread. Otherwise it would need
4356// the lock and should use mCurrentState rather than mDrawingState.
4357void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004358 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004359 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004360 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004361
4362 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4363}
4364
Yiwei Zhang5434a782018-12-05 18:06:32 -08004365void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004366 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004367
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004368 if (isLayerTripleBufferingDisabled())
4369 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004370
Yiwei Zhang5434a782018-12-05 18:06:32 -08004371 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4372 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4373 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4374 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4375 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4376 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004377 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004378}
4379
Yiwei Zhang5434a782018-12-05 18:06:32 -08004380void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4381 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004382 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4383 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004384 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004385 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004386 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004387 }
David Sodman4a36e932017-11-07 14:29:47 -08004388 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004389 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004390 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004391 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4392 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004393}
4394
Dan Stozae77c7662016-05-13 11:37:28 -07004395void SurfaceFlinger::recordBufferingStats(const char* layerName,
4396 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004397 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4398 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004399 for (const auto& segment : history) {
4400 if (!segment.usedThirdBuffer) {
4401 stats.twoBufferTime += segment.totalTime;
4402 }
4403 if (segment.occupancyAverage < 1.0f) {
4404 stats.doubleBufferedTime += segment.totalTime;
4405 } else if (segment.occupancyAverage < 2.0f) {
4406 stats.tripleBufferedTime += segment.totalTime;
4407 }
4408 ++stats.numSegments;
4409 stats.totalTime += segment.totalTime;
4410 }
4411}
4412
Yiwei Zhang5434a782018-12-05 18:06:32 -08004413void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4414 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004415
4416 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4417 const size_t count = currentLayers.size();
4418 for (size_t i=0 ; i<count ; i++) {
4419 currentLayers[i]->dumpFrameEvents(result);
4420 }
4421}
4422
Yiwei Zhang5434a782018-12-05 18:06:32 -08004423void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004424 result.append("Buffering stats:\n");
4425 result.append(" [Layer name] <Active time> <Two buffer> "
4426 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004427 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004428 typedef std::tuple<std::string, float, float, float> BufferTuple;
4429 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004430 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004431 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004432 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004433 if (stats.numSegments == 0) {
4434 continue;
4435 }
4436 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4437 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4438 stats.totalTime;
4439 float doubleBufferRatio = static_cast<float>(
4440 stats.doubleBufferedTime) / stats.totalTime;
4441 float tripleBufferRatio = static_cast<float>(
4442 stats.tripleBufferedTime) / stats.totalTime;
4443 sorted.insert({activeTime, {name, twoBufferRatio,
4444 doubleBufferRatio, tripleBufferRatio}});
4445 }
4446 for (const auto& sortedPair : sorted) {
4447 float activeTime = sortedPair.first;
4448 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004449 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4450 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004451 }
4452 result.append("\n");
4453}
4454
Yiwei Zhang5434a782018-12-05 18:06:32 -08004455void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004456 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004457 const auto displayId = display->getId();
4458 if (!displayId) {
4459 continue;
4460 }
4461 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004462 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004463 continue;
4464 }
4465
Yiwei Zhang5434a782018-12-05 18:06:32 -08004466 StringAppendF(&result,
4467 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4468 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004469 uint8_t port;
4470 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004471 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004472 result.append("no identification data\n");
4473 continue;
4474 }
4475
4476 if (!isEdid(data)) {
4477 result.append("unknown identification data: ");
4478 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004479 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004480 }
4481 result.append("\n");
4482 continue;
4483 }
4484
4485 const auto edid = parseEdid(data);
4486 if (!edid) {
4487 result.append("invalid EDID: ");
4488 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004489 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004490 }
4491 result.append("\n");
4492 continue;
4493 }
4494
Yiwei Zhang5434a782018-12-05 18:06:32 -08004495 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004496 result.append(edid->displayName.data(), edid->displayName.length());
4497 result.append("\"\n");
4498 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004499}
4500
Yiwei Zhang5434a782018-12-05 18:06:32 -08004501void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4502 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4503 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4504 StringAppendF(&result, "DisplayColorSetting: %s\n",
4505 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004506
4507 // TODO: print out if wide-color mode is active or not
4508
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004509 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004510 const auto displayId = display->getId();
4511 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004512 continue;
4513 }
4514
Yiwei Zhang5434a782018-12-05 18:06:32 -08004515 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004516 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004517 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004518 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004519 }
4520
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004521 ColorMode currentMode = display->getActiveColorMode();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004522 StringAppendF(&result, " Current color mode: %s (%d)\n",
4523 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004524 }
4525 result.append("\n");
4526}
4527
Yiwei Zhang5434a782018-12-05 18:06:32 -08004528void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004529 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004530 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4531 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004532 continue;
4533 }
4534
Dominik Laskowski05275f12018-11-01 15:03:24 -07004535 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004536 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4537 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004538 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004539 compositionInfo.dump(result, nullptr);
4540 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004541 }
4542 }
David Sodman7e4ae112018-02-09 15:02:28 -08004543}
4544
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004545LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004546 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004547 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4548 const State& state = useDrawing ? mDrawingState : mCurrentState;
4549 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004550 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004551 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004552 });
4553
4554 return layersProto;
4555}
4556
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004557LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004558 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004559
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004560 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004561 resolution->set_w(display.getWidth());
4562 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004563
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004564 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4565 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4566 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004567
Dominik Laskowski075d3172018-05-24 15:50:06 -07004568 const auto displayId = display.getId();
4569 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004570 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004571 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004572 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004573 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004574 }
4575 });
4576
4577 return layersProto;
4578}
4579
Mathias Agopian74d211a2013-04-22 16:55:35 +02004580void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004581 std::string& result) const {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004582 bool colorize = false;
4583 if (index < args.size()
4584 && (args[index] == String16("--color"))) {
4585 colorize = true;
4586 index++;
4587 }
4588
4589 Colorizer colorizer(colorize);
4590
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004591 // figure out if we're stuck somewhere
4592 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004593 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004594 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4595
4596 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004597 * Dump library configuration.
4598 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004599
4600 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004601 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004602 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004603 appendSfConfigString(result);
4604 appendUiConfigString(result);
4605 appendGuiConfigString(result);
4606 result.append("\n");
4607
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004608 result.append("\nDisplay identification data:\n");
4609 dumpDisplayIdentificationData(result);
4610
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004611 result.append("\nWide-Color information:\n");
4612 dumpWideColorInfo(result);
4613
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004614 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004615 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004616 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004617 result.append(SyncFeatures::getInstance().toString());
4618 result.append("\n");
4619
Andy McFadden41d67d72014-04-25 16:58:34 -07004620 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004621 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004622 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004623
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004624 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4625 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004626 if (const auto displayId = getInternalDisplayId();
4627 displayId && getHwComposer().isConnected(*displayId)) {
4628 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004629 StringAppendF(&result,
4630 "Display %s: app phase %" PRId64 " ns, "
4631 "sf phase %" PRId64 " ns, "
4632 "early app phase %" PRId64 " ns, "
4633 "early sf phase %" PRId64 " ns, "
4634 "early app gl phase %" PRId64 " ns, "
4635 "early sf gl phase %" PRId64 " ns, "
4636 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4637 to_string(*displayId).c_str(), vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
4638 appEarlyOffset, sfEarlyOffset, appEarlyGlOffset, sfEarlyGlOffset,
4639 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004640 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004641 result.append("\n");
4642
Dan Stozab90cf072015-03-05 11:05:59 -08004643 // Dump static screen stats
4644 result.append("\n");
4645 dumpStaticScreenStats(result);
4646 result.append("\n");
4647
Yiwei Zhang5434a782018-12-05 18:06:32 -08004648 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004649
Dan Stozae77c7662016-05-13 11:37:28 -07004650 dumpBufferingStats(result);
4651
Andy McFadden4803b742012-09-24 19:07:20 -07004652 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004653 * Dump the visible layer list
4654 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004655 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004656 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4657 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4658 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004659 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004660
Chia-I Wu2f884132018-09-13 15:17:58 -07004661 {
4662 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4663 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004664 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004665 result.append("\n");
4666 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004667
David Sodman7e4ae112018-02-09 15:02:28 -08004668 result.append("\nFrame-Composition information:\n");
4669 dumpFrameCompositionInfo(result);
4670 result.append("\n");
4671
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004672 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004673 * Dump Display state
4674 */
4675
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004676 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004677 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004678 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004679 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004680 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004681 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004682 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004683
4684 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004685 * Dump SurfaceFlinger global state
4686 */
4687
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004688 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004689 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004690 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004691
David Sodmanbc815282017-11-05 18:57:52 -08004692 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004693
Dominik Laskowski075d3172018-05-24 15:50:06 -07004694 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004695 display->undefinedRegion.dump(result, "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004696 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4697 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004698 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004699 StringAppendF(&result,
4700 " transaction-flags : %08x\n"
4701 " gpu_to_cpu_unsupported : %d\n",
4702 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004703
Dominik Laskowski075d3172018-05-24 15:50:06 -07004704 if (const auto displayId = getInternalDisplayId();
4705 displayId && getHwComposer().isConnected(*displayId)) {
4706 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004707 StringAppendF(&result,
4708 " refresh-rate : %f fps\n"
4709 " x-dpi : %f\n"
4710 " y-dpi : %f\n",
4711 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4712 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004713 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004714
Yiwei Zhang5434a782018-12-05 18:06:32 -08004715 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004716
Yiwei Zhang5434a782018-12-05 18:06:32 -08004717 StringAppendF(&result, " use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004718 /*
4719 * VSYNC state
4720 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004721 if (mUseScheduler) {
4722 mScheduler->dump(mAppConnectionHandle, result);
4723 } else {
4724 mEventThread->dump(result);
4725 }
Dan Stozae22aec72016-08-01 13:20:59 -07004726 result.append("\n");
4727
4728 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004729 * Tracing state
4730 */
4731 mTracing.dump(result);
4732 result.append("\n");
4733
4734 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004735 * HWC layer minidump
4736 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004737 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004738 const auto displayId = display->getId();
4739 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004740 continue;
4741 }
4742
Yiwei Zhang5434a782018-12-05 18:06:32 -08004743 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004744 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004745 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004746 result.append("\n");
4747 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004748
4749 /*
4750 * Dump HWComposer state
4751 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004752 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004753 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004754 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004755 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004756 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004757 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004758
4759 /*
4760 * Dump gralloc state
4761 */
4762 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4763 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004764
4765 /*
4766 * Dump VrFlinger state if in use.
4767 */
4768 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4769 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004770 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004771 result.append("\n");
4772 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004773}
4774
Dominik Laskowski075d3172018-05-24 15:50:06 -07004775const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004776 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004777 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004778 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004779 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004780 }
4781 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004782
Dominik Laskowski34157762018-10-31 13:07:19 -07004783 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004784 static const Vector<sp<Layer>> empty;
4785 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004786}
4787
Keun young Park63f165f2012-08-31 10:53:36 -07004788bool SurfaceFlinger::startDdmConnection()
4789{
4790 void* libddmconnection_dso =
4791 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4792 if (!libddmconnection_dso) {
4793 return false;
4794 }
4795 void (*DdmConnection_start)(const char* name);
4796 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004797 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004798 if (!DdmConnection_start) {
4799 dlclose(libddmconnection_dso);
4800 return false;
4801 }
4802 (*DdmConnection_start)(getServiceName());
4803 return true;
4804}
4805
Chia-I Wu28f320b2018-05-03 11:02:56 -07004806void SurfaceFlinger::updateColorMatrixLocked() {
4807 mat4 colorMatrix;
4808 if (mGlobalSaturationFactor != 1.0f) {
4809 // Rec.709 luma coefficients
4810 float3 luminance{0.213f, 0.715f, 0.072f};
4811 luminance *= 1.0f - mGlobalSaturationFactor;
4812 mat4 saturationMatrix = mat4(
4813 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4814 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4815 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4816 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4817 );
4818 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4819 } else {
4820 colorMatrix = mClientColorMatrix * mDaltonizer();
4821 }
4822
4823 if (mCurrentState.colorMatrix != colorMatrix) {
4824 mCurrentState.colorMatrix = colorMatrix;
4825 mCurrentState.colorMatrixChanged = true;
4826 setTransactionFlags(eTransactionNeeded);
4827 }
4828}
4829
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004830status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004831#pragma clang diagnostic push
4832#pragma clang diagnostic error "-Wswitch-enum"
4833 switch (static_cast<ISurfaceComposerTag>(code)) {
4834 // These methods should at minimum make sure that the client requested
4835 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004836 case BOOT_FINISHED:
4837 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004838 case CREATE_DISPLAY:
4839 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004840 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004841 case GET_ACTIVE_COLOR_MODE:
4842 case GET_ANIMATION_FRAME_STATS:
4843 case GET_HDR_CAPABILITIES:
4844 case SET_ACTIVE_CONFIG:
4845 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004846 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004847 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004848 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004849 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4850 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004851 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4852 IPCThreadState* ipc = IPCThreadState::self();
4853 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4854 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004855 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004856 }
Robert Carr1db73f62016-12-21 12:58:51 -08004857 return OK;
4858 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004859 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004860 IPCThreadState* ipc = IPCThreadState::self();
4861 const int pid = ipc->getCallingPid();
4862 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004863 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4864 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004865 return PERMISSION_DENIED;
4866 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004867 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004868 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004869 // Used by apps to hook Choreographer to SurfaceFlinger.
4870 case CREATE_DISPLAY_EVENT_CONNECTION:
4871 // The following calls are currently used by clients that do not
4872 // request necessary permissions. However, they do not expose any secret
4873 // information, so it is OK to pass them.
4874 case AUTHENTICATE_SURFACE:
4875 case GET_ACTIVE_CONFIG:
4876 case GET_BUILT_IN_DISPLAY:
4877 case GET_DISPLAY_COLOR_MODES:
4878 case GET_DISPLAY_CONFIGS:
4879 case GET_DISPLAY_STATS:
4880 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4881 // Calling setTransactionState is safe, because you need to have been
4882 // granted a reference to Client* and Handle* to do anything with it.
4883 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004884 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004885 case GET_COLOR_MANAGEMENT:
Peiyong Lin0256f722018-08-31 15:45:10 -07004886 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004887 return OK;
4888 }
4889 case CAPTURE_LAYERS:
4890 case CAPTURE_SCREEN: {
4891 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004892 IPCThreadState* ipc = IPCThreadState::self();
4893 const int pid = ipc->getCallingPid();
4894 const int uid = ipc->getCallingUid();
4895 if ((uid != AID_GRAPHICS) &&
4896 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4897 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4898 return PERMISSION_DENIED;
4899 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004900 return OK;
4901 }
4902 // The following codes are deprecated and should never be allowed to access SF.
4903 case CONNECT_DISPLAY_UNUSED:
4904 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4905 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4906 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004907 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004908 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004909
4910 // These codes are used for the IBinder protocol to either interrogate the recipient
4911 // side of the transaction for its canonical interface descriptor or to dump its state.
4912 // We let them pass by default.
4913 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4914 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4915 code == IBinder::SYSPROPS_TRANSACTION) {
4916 return OK;
4917 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004918 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004919 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004920 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004921 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4922 return OK;
4923 }
4924 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4925 return PERMISSION_DENIED;
4926#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004927}
4928
Ana Krulec13be8ad2018-08-21 02:43:56 +00004929status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4930 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004931 status_t credentialCheck = CheckTransactCodeCredentials(code);
4932 if (credentialCheck != OK) {
4933 return credentialCheck;
4934 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004935
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004936 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4937 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004938 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004939 IPCThreadState* ipc = IPCThreadState::self();
4940 const int uid = ipc->getCallingUid();
4941 if (CC_UNLIKELY(uid != AID_SYSTEM
4942 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004943 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004944 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004945 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004946 return PERMISSION_DENIED;
4947 }
4948 int n;
4949 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004950 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004951 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004952 return NO_ERROR;
4953 case 1002: // SHOW_UPDATES
4954 n = data.readInt32();
4955 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004956 invalidateHwcGeometry();
4957 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004958 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004959 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004960 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004961 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004962 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004963 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004964 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004965 setTransactionFlags(
4966 eTransactionNeeded|
4967 eDisplayTransactionNeeded|
4968 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004969 return NO_ERROR;
4970 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004971 case 1006:{ // send empty update
4972 signalRefresh();
4973 return NO_ERROR;
4974 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004975 case 1008: // toggle use of hw composer
4976 n = data.readInt32();
4977 mDebugDisableHWC = n ? 1 : 0;
4978 invalidateHwcGeometry();
4979 repaintEverything();
4980 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004981 case 1009: // toggle use of transform hint
4982 n = data.readInt32();
4983 mDebugDisableTransformHint = n ? 1 : 0;
4984 invalidateHwcGeometry();
4985 repaintEverything();
4986 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004987 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004988 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004989 reply->writeInt32(0);
4990 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004991 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004992 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004993 return NO_ERROR;
4994 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004995 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004996 if (!display) {
4997 return NAME_NOT_FOUND;
4998 }
4999
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005000 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005001 return NO_ERROR;
5002 }
5003 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005004 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005005 // daltonize
5006 n = data.readInt32();
5007 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005008 case 1:
5009 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5010 break;
5011 case 2:
5012 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5013 break;
5014 case 3:
5015 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5016 break;
5017 default:
5018 mDaltonizer.setType(ColorBlindnessType::None);
5019 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005020 }
5021 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005022 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005023 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005024 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005025 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005026
5027 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005028 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005029 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005030 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005031 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005032 // apply a color matrix
5033 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005034 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005035 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005036 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005037 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005038 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005039 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005040 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005041 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005042 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005043 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005044
5045 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5046 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005047 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005048 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5049 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5050 }
5051
Chia-I Wu28f320b2018-05-03 11:02:56 -07005052 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005053 return NO_ERROR;
5054 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005055 // This is an experimental interface
5056 // Needs to be shifted to proper binder interface when we productize
5057 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005058 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005059 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005060 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005061 return NO_ERROR;
5062 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005063 case 1017: {
5064 n = data.readInt32();
5065 mForceFullDamage = static_cast<bool>(n);
5066 return NO_ERROR;
5067 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005068 case 1018: { // Modify Choreographer's phase offset
5069 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005070 if (mUseScheduler) {
5071 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5072 } else {
5073 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5074 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005075 return NO_ERROR;
5076 }
5077 case 1019: { // Modify SurfaceFlinger's phase offset
5078 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005079 if (mUseScheduler) {
5080 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5081 } else {
5082 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5083 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005084 return NO_ERROR;
5085 }
Irvel468051e2016-06-13 16:44:44 -07005086 case 1020: { // Layer updates interceptor
5087 n = data.readInt32();
5088 if (n) {
5089 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005090 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005091 }
5092 else{
5093 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005094 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005095 }
5096 return NO_ERROR;
5097 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005098 case 1021: { // Disable HWC virtual displays
5099 n = data.readInt32();
5100 mUseHwcVirtualDisplays = !n;
5101 return NO_ERROR;
5102 }
Romain Guy0147a172017-06-01 13:53:56 -07005103 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005104 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005105 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005106
Chia-I Wu28f320b2018-05-03 11:02:56 -07005107 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005108 return NO_ERROR;
5109 }
Romain Guy54f154a2017-10-24 21:40:32 +01005110 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005111 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005112 invalidateHwcGeometry();
5113 repaintEverything();
5114 return NO_ERROR;
5115 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005116 // Deprecate, use 1030 to check whether the device is color managed.
5117 case 1024: {
5118 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005119 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005120 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005121 n = data.readInt32();
5122 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005123 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005124 mTracing.enable();
5125 doTracing("tracing.enable");
5126 reply->writeInt32(NO_ERROR);
5127 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005128 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005129 status_t err = mTracing.disable();
5130 reply->writeInt32(err);
5131 }
5132 return NO_ERROR;
5133 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005134 case 1026: { // Get layer tracing status
5135 reply->writeBool(mTracing.isEnabled());
5136 return NO_ERROR;
5137 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005138 // Is a DisplayColorSetting supported?
5139 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005140 const auto display = getDefaultDisplayDevice();
5141 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005142 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005143 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005144
5145 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5146 switch (setting) {
5147 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005148 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005149 break;
5150 case DisplayColorSetting::UNMANAGED:
5151 reply->writeBool(true);
5152 break;
5153 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005154 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005155 break;
5156 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005157 reply->writeBool(
5158 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005159 break;
5160 }
5161 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005162 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005163 // Is VrFlinger active?
5164 case 1028: {
5165 Mutex::Autolock _l(mStateLock);
5166 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5167 return NO_ERROR;
5168 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005169 // Is device color managed?
5170 case 1030: {
5171 reply->writeBool(useColorManagement);
5172 return NO_ERROR;
5173 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005174 // Override default composition data space
5175 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5176 // && adb shell stop zygote && adb shell start zygote
5177 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5178 // adb shell stop zygote && adb shell start zygote
5179 case 1031: {
5180 Mutex::Autolock _l(mStateLock);
5181 n = data.readInt32();
5182 if (n) {
5183 n = data.readInt32();
5184 if (n) {
5185 Dataspace dataspace = static_cast<Dataspace>(n);
5186 if (!validateCompositionDataspace(dataspace)) {
5187 return BAD_VALUE;
5188 }
5189 mDefaultCompositionDataspace = dataspace;
5190 }
5191 n = data.readInt32();
5192 if (n) {
5193 Dataspace dataspace = static_cast<Dataspace>(n);
5194 if (!validateCompositionDataspace(dataspace)) {
5195 return BAD_VALUE;
5196 }
5197 mWideColorGamutCompositionDataspace = dataspace;
5198 }
5199 } else {
5200 // restore composition data space.
5201 mDefaultCompositionDataspace = defaultCompositionDataspace;
5202 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5203 }
5204 return NO_ERROR;
5205 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005206 }
5207 }
5208 return err;
5209}
5210
Steven Thomas6d8110b2017-08-31 18:24:21 -07005211void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005212 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005213 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005214}
5215
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005216// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5217class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005218public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005219 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5220 ~WindowDisconnector() {
5221 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005222 }
5223
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005224private:
5225 ANativeWindow* mWindow;
5226 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005227};
5228
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005229status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005230 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5231 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005232 uint32_t reqWidth, uint32_t reqHeight,
5233 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005234 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005235 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005236
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005237 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005238
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005239 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5240
Chia-I Wu20261cb2018-08-23 12:55:44 -07005241 sp<DisplayDevice> display;
5242 {
5243 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005244
Chia-I Wu20261cb2018-08-23 12:55:44 -07005245 display = getDisplayDeviceLocked(displayToken);
5246 if (!display) return BAD_VALUE;
5247
Chia-I Wucb023152018-08-28 12:57:23 -07005248 // set the requested width/height to the logical display viewport size
5249 // by default
5250 if (reqWidth == 0 || reqHeight == 0) {
5251 reqWidth = uint32_t(display->getViewport().width());
5252 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005253 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005254 }
5255
Peiyong Lin0e003c92018-09-17 11:09:51 -07005256 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5257 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005258
5259 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005260 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005261 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5262 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005263}
5264
5265status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005266 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5267 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005268 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005269 ATRACE_CALL();
5270
5271 class LayerRenderArea : public RenderArea {
5272 public:
Robert Carr578038f2018-03-09 12:25:24 -08005273 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005274 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5275 bool childrenOnly)
5276 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005277 mLayer(layer),
5278 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005279 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005280 mFlinger(flinger),
5281 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005282 const ui::Transform& getTransform() const override { return mTransform; }
Ady Abraham83729882018-12-07 12:26:48 -08005283 Rect getBounds() const override { return mLayer->getBufferSize(StateSet::Drawing); }
Marissa Wall61c58622018-07-18 10:12:20 -07005284 int getHeight() const override {
Ady Abraham83729882018-12-07 12:26:48 -08005285 return mLayer->getBufferSize(StateSet::Drawing).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005286 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005287 int getWidth() const override {
Ady Abraham83729882018-12-07 12:26:48 -08005288 return mLayer->getBufferSize(StateSet::Drawing).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005289 }
chaviwa76b2712017-09-20 12:02:26 -07005290 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005291 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005292 Rect getSourceCrop() const override {
5293 if (mCrop.isEmpty()) {
5294 return getBounds();
5295 } else {
5296 return mCrop;
5297 }
5298 }
Robert Carr578038f2018-03-09 12:25:24 -08005299 class ReparentForDrawing {
5300 public:
5301 const sp<Layer>& oldParent;
5302 const sp<Layer>& newParent;
5303
5304 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5305 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005306 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005307 }
Robert Carr15eae092018-03-23 13:43:53 -07005308 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005309 };
5310
5311 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005312 const Rect sourceCrop = getSourceCrop();
5313 // no need to check rotation because there is none
5314 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5315 sourceCrop.height() != getReqHeight();
5316
Robert Carr578038f2018-03-09 12:25:24 -08005317 if (!mChildrenOnly) {
5318 mTransform = mLayer->getTransform().inverse();
5319 drawLayers();
5320 } else {
5321 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005322 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005323 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5324 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005325
5326 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5327 drawLayers();
5328 }
5329 }
chaviwa76b2712017-09-20 12:02:26 -07005330
chaviwa76b2712017-09-20 12:02:26 -07005331 private:
chaviw7206d492017-11-10 16:16:12 -08005332 const sp<Layer> mLayer;
5333 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005334
5335 // In the "childrenOnly" case we reparent the children to a screenshot
5336 // layer which has no properties set and which does not draw.
5337 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005338 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005339 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005340
5341 SurfaceFlinger* mFlinger;
5342 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005343 };
5344
5345 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5346 auto parent = layerHandle->owner.promote();
5347
Robert Carr2e102c92018-10-23 12:11:15 -07005348 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005349 ALOGE("captureLayers called with a removed parent");
5350 return NAME_NOT_FOUND;
5351 }
5352
Robert Carr578038f2018-03-09 12:25:24 -08005353 const int uid = IPCThreadState::self()->getCallingUid();
5354 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Ady Abraham83729882018-12-07 12:26:48 -08005355 if (!forSystem && parent->getCurrentFlags() & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005356 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5357 return PERMISSION_DENIED;
5358 }
5359
chaviw7206d492017-11-10 16:16:12 -08005360 Rect crop(sourceCrop);
5361 if (sourceCrop.width() <= 0) {
5362 crop.left = 0;
Ady Abraham83729882018-12-07 12:26:48 -08005363 crop.right = parent->getBufferSize(StateSet::Current).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005364 }
5365
5366 if (sourceCrop.height() <= 0) {
5367 crop.top = 0;
Ady Abraham83729882018-12-07 12:26:48 -08005368 crop.bottom = parent->getBufferSize(StateSet::Current).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005369 }
5370
5371 int32_t reqWidth = crop.width() * frameScale;
5372 int32_t reqHeight = crop.height() * frameScale;
5373
Chia-I Wu20261cb2018-08-23 12:55:44 -07005374 // really small crop or frameScale
5375 if (reqWidth <= 0) {
5376 reqWidth = 1;
5377 }
5378 if (reqHeight <= 0) {
5379 reqHeight = 1;
5380 }
5381
Peiyong Lin0e003c92018-09-17 11:09:51 -07005382 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005383
Robert Carr578038f2018-03-09 12:25:24 -08005384 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005385 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5386 if (!layer->isVisible()) {
5387 return;
Robert Carr578038f2018-03-09 12:25:24 -08005388 } else if (childrenOnly && layer == parent.get()) {
5389 return;
chaviwa76b2712017-09-20 12:02:26 -07005390 }
5391 visitor(layer);
5392 });
5393 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005394 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005395}
5396
5397status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5398 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005399 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005400 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005401 bool useIdentityTransform) {
5402 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005403
Peiyong Lin0e003c92018-09-17 11:09:51 -07005404 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005405 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5406 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005407 *outBuffer =
5408 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5409 static_cast<android_pixel_format>(reqPixelFormat), 1,
5410 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005411
5412 // This mutex protects syncFd and captureResult for communication of the return values from the
5413 // main thread back to this Binder thread
5414 std::mutex captureMutex;
5415 std::condition_variable captureCondition;
5416 std::unique_lock<std::mutex> captureLock(captureMutex);
5417 int syncFd = -1;
5418 std::optional<status_t> captureResult;
5419
Robert Carr03480e22018-01-04 16:02:06 -08005420 const int uid = IPCThreadState::self()->getCallingUid();
5421 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5422
Dominik Laskowski8c001672018-05-30 16:52:06 -07005423 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005424 // If there is a refresh pending, bug out early and tell the binder thread to try again
5425 // after the refresh.
5426 if (mRefreshPending) {
5427 ATRACE_NAME("Skipping screenshot for now");
5428 std::unique_lock<std::mutex> captureLock(captureMutex);
5429 captureResult = std::make_optional<status_t>(EAGAIN);
5430 captureCondition.notify_one();
5431 return;
5432 }
5433
5434 status_t result = NO_ERROR;
5435 int fd = -1;
5436 {
5437 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005438 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005439 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5440 useIdentityTransform, forSystem, &fd);
5441 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005442 }
5443
5444 {
5445 std::unique_lock<std::mutex> captureLock(captureMutex);
5446 syncFd = fd;
5447 captureResult = std::make_optional<status_t>(result);
5448 captureCondition.notify_one();
5449 }
5450 });
5451
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005452 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005453 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005454 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005455 while (*captureResult == EAGAIN) {
5456 captureResult.reset();
5457 result = postMessageAsync(message);
5458 if (result != NO_ERROR) {
5459 return result;
5460 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005461 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005462 }
5463 result = *captureResult;
5464 }
5465
5466 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005467 sync_wait(syncFd, -1);
5468 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005469 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005470
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005471 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005472}
5473
chaviwa76b2712017-09-20 12:02:26 -07005474void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005475 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005476 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005477 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005478
Lloyd Pique144e1162017-12-20 16:44:52 -08005479 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005480
chaviwa76b2712017-09-20 12:02:26 -07005481 const auto reqWidth = renderArea.getReqWidth();
5482 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005483 const auto sourceCrop = renderArea.getSourceCrop();
5484 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005485
Peiyong Lin0e003c92018-09-17 11:09:51 -07005486 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005487 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005488
Mathias Agopian180f10d2013-04-10 22:55:41 -07005489 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005490 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005491
5492 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005493 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005494 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005495
chaviw50da5042018-04-09 13:49:37 -07005496 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005497 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005498 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005499
chaviwa76b2712017-09-20 12:02:26 -07005500 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005501 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005502 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005503 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005504 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005505}
5506
chaviwa76b2712017-09-20 12:02:26 -07005507status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5508 TraverseLayersFunction traverseLayers,
5509 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005510 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005511 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005512 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005513 ATRACE_CALL();
5514
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005515 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005516
5517 traverseLayers([&](Layer* layer) {
5518 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5519 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005520
Robert Carr03480e22018-01-04 16:02:06 -08005521 // We allow the system server to take screenshots of secure layers for
5522 // use in situations like the Screen-rotation animation and place
5523 // the impetus on WindowManager to not persist them.
5524 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005525 ALOGW("FB is protected: PERMISSION_DENIED");
5526 return PERMISSION_DENIED;
5527 }
Peiyong Linfb530cf2018-12-15 05:07:38 +00005528 auto& engine(getRenderEngine());
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005529
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005530 // this binds the given EGLImage as a framebuffer for the
5531 // duration of this scope.
Peiyong Linfb530cf2018-12-15 05:07:38 +00005532 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005533 if (bufferBond.getStatus() != NO_ERROR) {
5534 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005535 return INVALID_OPERATION;
5536 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005537
Dan Stozaabcda352017-06-01 14:37:39 -07005538 // this will in fact render into our dequeued buffer
5539 // via an FBO, which means we didn't have to create
5540 // an EGLSurface and therefore we're not
5541 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005542 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005543
Peiyong Linfb530cf2018-12-15 05:07:38 +00005544 base::unique_fd syncFd = engine.flush();
Alec Mouri492bc572018-09-11 21:40:04 +00005545 if (syncFd < 0) {
Peiyong Linfb530cf2018-12-15 05:07:38 +00005546 engine.finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005547 }
Alec Mouri492bc572018-09-11 21:40:04 +00005548 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005549
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005550 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005551}
5552
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005553// ---------------------------------------------------------------------------
5554
Dan Stoza412903f2017-04-27 13:42:17 -07005555void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5556 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005557}
5558
Dan Stoza412903f2017-04-27 13:42:17 -07005559void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5560 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005561}
5562
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005563void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005564 const LayerVector::Visitor& visitor) {
5565 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005566 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005567 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005568 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005569 continue;
5570 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005571 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005572 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005573 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005574 return;
5575 }
chaviwa76b2712017-09-20 12:02:26 -07005576 if (!layer->isVisible()) {
5577 return;
5578 }
5579 visitor(layer);
5580 });
5581 }
5582}
5583
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005584}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005585
Lloyd Pique074e8122018-07-26 12:57:23 -07005586
Mathias Agopian3f844832013-08-07 21:24:32 -07005587#if defined(__gl_h_)
5588#error "don't include gl/gl.h in this file"
5589#endif
5590
5591#if defined(__gl2_h_)
5592#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005593#endif