blob: 4aea3697f46f6d4d167134b30d157675c21aadda [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Robert Carr720e5062018-07-30 17:45:14 -070040#include <input/IInputFlinger.h>
41
Chia-I Wud49d6692018-06-27 07:17:41 +080042#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060043#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070045#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070046
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070048#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070049#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080050#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080051#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080052#include <gui/Surface.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070053#include <renderengine/RenderEngine.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070054#include <ui/GraphicBufferAllocator.h>
55#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070056#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080057
Mathias Agopiancde87a32012-09-13 14:09:01 -070058#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059#include <utils/String8.h>
60#include <utils/String16.h>
61#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070062#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080063#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Mathias Agopian921e6ac2012-07-23 23:11:29 -070065#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070066#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080067
Robert Carr578038f2018-03-09 12:25:24 -080068#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070069#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070070#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020071#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080072#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020073#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080074#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080075#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080076#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070078#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080079#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070080#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070081#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070083#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
Steven Thomasb02664d2017-07-26 18:48:28 -070085#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070086#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070087#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070088#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070089#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070090#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070091#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070092#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070093#include "Scheduler/EventControlThread.h"
94#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070095#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070096#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070097#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080098#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070099
Mathias Agopianff2ed702013-09-01 21:36:12 -0700100#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700101
David Sodman7e4ae112018-02-09 15:02:28 -0800102#include "android-base/stringprintf.h"
103
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900104#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800105#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700106#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800107#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900108#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900109
chaviw1d044282017-09-27 12:19:28 -0700110#include <layerproto/LayerProtoParser.h>
111
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800112namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700113
Jaesoo Lee43518572017-01-23 19:03:16 +0900114using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900115using namespace android::hardware::configstore::V1_0;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800116using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700117using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700118using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700119using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700120using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900121
Steven Thomasb02664d2017-07-26 18:48:28 -0700122namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700123
124#pragma clang diagnostic push
125#pragma clang diagnostic error "-Wswitch-enum"
126
127bool isWideColorMode(const ColorMode colorMode) {
128 switch (colorMode) {
129 case ColorMode::DISPLAY_P3:
130 case ColorMode::ADOBE_RGB:
131 case ColorMode::DCI_P3:
132 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700133 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700134 case ColorMode::BT2100_PQ:
135 case ColorMode::BT2100_HLG:
136 return true;
137 case ColorMode::NATIVE:
138 case ColorMode::STANDARD_BT601_625:
139 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
140 case ColorMode::STANDARD_BT601_525:
141 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
142 case ColorMode::STANDARD_BT709:
143 case ColorMode::SRGB:
144 return false;
145 }
146 return false;
147}
148
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700149ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
150 switch (rotation) {
151 case ISurfaceComposer::eRotateNone:
152 return ui::Transform::ROT_0;
153 case ISurfaceComposer::eRotate90:
154 return ui::Transform::ROT_90;
155 case ISurfaceComposer::eRotate180:
156 return ui::Transform::ROT_180;
157 case ISurfaceComposer::eRotate270:
158 return ui::Transform::ROT_270;
159 }
160 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
161 return ui::Transform::ROT_0;
162}
163
Peiyong Linfca547f2018-07-09 13:03:33 -0700164#pragma clang diagnostic pop
165
Steven Thomasb02664d2017-07-26 18:48:28 -0700166class ConditionalLock {
167public:
168 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
169 if (lock) {
170 mMutex.lock();
171 }
172 }
173 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
174private:
175 Mutex& mMutex;
176 bool mLocked;
177};
Peiyong Linfca547f2018-07-09 13:03:33 -0700178
Peiyong Lin9d846a52018-11-05 13:18:20 -0800179// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
180bool validateCompositionDataspace(Dataspace dataspace) {
181 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
182}
183
Steven Thomasb02664d2017-07-26 18:48:28 -0700184} // namespace anonymous
185
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800186// ---------------------------------------------------------------------------
187
Mathias Agopian99b49842011-06-27 16:05:52 -0700188const String16 sHardwareTest("android.permission.HARDWARE_TEST");
189const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
190const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
191const String16 sDump("android.permission.DUMP");
192
193// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800194int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
195int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700196int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700197bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800198uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800199bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800200bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800201int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600202bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700203int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700204bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700205bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700206Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
207ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
208Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
209ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700210
Kalle Raitaa099a242017-01-11 11:17:29 -0800211std::string getHwcServiceName() {
212 char value[PROPERTY_VALUE_MAX] = {};
213 property_get("debug.sf.hwc_service_name", value, "default");
214 ALOGI("Using HWComposer service: '%s'", value);
215 return std::string(value);
216}
217
218bool useTrebleTestingOverride() {
219 char value[PROPERTY_VALUE_MAX] = {};
220 property_get("debug.sf.treble_testing_override", value, "false");
221 ALOGI("Treble testing override: '%s'", value);
222 return std::string(value) == "true";
223}
224
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800225std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
226 switch(displayColorSetting) {
227 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700228 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800229 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700230 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800231 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700232 return std::string("Enhanced");
233 default:
234 return std::string("Unknown ") +
235 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800236 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800237}
238
David Sodmanbc815282017-11-05 18:57:52 -0800239SurfaceFlingerBE::SurfaceFlingerBE()
240 : mHwcServiceName(getHwcServiceName()),
241 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800242 mFrameBuckets(),
243 mTotalTime(0),
244 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800245 mComposerSequenceId(0) {
246}
247
Lloyd Pique90c115d2018-09-18 21:39:42 -0700248SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
249 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800250 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700251 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700252 mTransactionPending(false),
253 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700254 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700255 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800256 mBootTime(systemTime()),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800258 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800259 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800260 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800261 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700262 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700263 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700264 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700265 mDebugInTransaction(0),
266 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700267 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800268 mTimeStats(factory.createTimeStats()),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700269 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700270 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800271 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800272 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800273 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700274 mVrFlingerRequestsDisplay(false),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700275 mMainThreadId(std::this_thread::get_id()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800276
Lloyd Pique90c115d2018-09-18 21:39:42 -0700277SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
278 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800279 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800280
281 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
282 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
283
284 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
285 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
286
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800287 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
288 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800289
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700290 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
291 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
292
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700293 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
294 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
295
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800296 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
297 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
298
Steven Thomas050b2c82017-03-06 11:45:16 -0800299 // Vr flinger is only enabled on Daydream ready devices.
300 useVrFlinger = getBool< ISurfaceFlingerConfigs,
301 &ISurfaceFlingerConfigs::useVrFlinger>(false);
302
Fabien Sanglard1971b632017-03-10 14:50:03 -0800303 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
304 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
305
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600306 hasWideColorDisplay =
307 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700308 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700309 getBool<V1_2::ISurfaceFlingerConfigs,
310 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
311
312 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
313 if (surfaceFlingerConfigsServiceV1_2) {
314 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
Peiyong Linc6780972018-10-28 15:24:08 -0700315 [&](auto tmpDefaultDataspace, auto tmpDefaultPixelFormat,
316 auto tmpWideColorGamutDataspace, auto tmpWideColorGamutPixelFormat) {
317 defaultCompositionDataspace = tmpDefaultDataspace;
318 defaultCompositionPixelFormat = tmpDefaultPixelFormat;
319 wideColorGamutCompositionDataspace = tmpWideColorGamutDataspace;
320 wideColorGamutCompositionPixelFormat = tmpWideColorGamutPixelFormat;
321 });
Peiyong Lin0256f722018-08-31 15:45:10 -0700322 }
Peiyong Lin9d846a52018-11-05 13:18:20 -0800323 mDefaultCompositionDataspace = defaultCompositionDataspace;
324 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600325
Peiyong Linb3839ad2018-09-05 15:37:19 -0700326 useContextPriority = getBool<ISurfaceFlingerConfigs,
327 &ISurfaceFlingerConfigs::useContextPriority>(true);
328
Iris Chang7501ed62018-04-30 14:45:42 +0800329 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700330 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
331 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800332 V1_1::DisplayOrientation::ORIENTATION_0);
333
334 switch (primaryDisplayOrientation) {
335 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700336 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800337 break;
338 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700339 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800340 break;
341 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700342 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800343 break;
344 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700345 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800346 break;
347 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700348 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800349
Lloyd Pique90c115d2018-09-18 21:39:42 -0700350 mPrimaryDispSync =
351 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
352 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700353
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800354 // debugging stuff...
355 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700356
Mathias Agopianb4b17302013-03-20 18:36:41 -0700357 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700358 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700359
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800360 property_get("debug.sf.showupdates", value, "0");
361 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700362
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700363 property_get("debug.sf.ddms", value, "0");
364 mDebugDDMS = atoi(value);
365 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700366 if (!startDdmConnection()) {
367 // start failed, and DDMS debugging not enabled
368 mDebugDDMS = 0;
369 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700370 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700371 ALOGI_IF(mDebugRegion, "showupdates enabled");
372 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700373
374 property_get("debug.sf.disable_backpressure", value, "0");
375 mPropagateBackpressure = !atoi(value);
376 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700377
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800378 property_get("debug.sf.enable_hwc_vds", value, "0");
379 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800380 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800381
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800382 property_get("ro.sf.disable_triple_buffer", value, "1");
383 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800384 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700385
Yiwei Zhang243b3782018-05-15 17:40:04 -0700386 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700387 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
388 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
389
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200390 property_get("debug.sf.early_phase_offset_ns", value, "-1");
391 const int earlySfOffsetNs = atoi(value);
392
393 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
394 const int earlyGlSfOffsetNs = atoi(value);
395
396 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
397 const int earlyAppOffsetNs = atoi(value);
398
399 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
400 const int earlyGlAppOffsetNs = atoi(value);
401
Ana Krulec98b5b242018-08-10 15:03:23 -0700402 property_get("debug.sf.use_scheduler", value, "0");
403 mUseScheduler = atoi(value);
404
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200405 const VSyncModulator::Offsets earlyOffsets =
406 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
407 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
408 const VSyncModulator::Offsets earlyGlOffsets =
409 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
410 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
411 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
412 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700413
Romain Guy11d63f42017-07-20 12:47:14 -0700414 // We should be reading 'persist.sys.sf.color_saturation' here
415 // but since /data may be encrypted, we need to wait until after vold
416 // comes online to attempt to read the property. The property is
417 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800418
419 if (useTrebleTestingOverride()) {
420 // Without the override SurfaceFlinger cannot connect to HIDL
421 // services that are not listed in the manifests. Considered
422 // deriving the setting from the set service name, but it
423 // would be brittle if the name that's not 'default' is used
424 // for production purposes later on.
425 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
426 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800427}
428
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800429void SurfaceFlinger::onFirstRef()
430{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800431 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800432}
433
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800434SurfaceFlinger::~SurfaceFlinger()
435{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800436}
437
Dan Stozac7014012014-02-14 15:03:43 -0800438void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800439{
440 // the window manager died on us. prepare its eulogy.
441
Andy McFadden13a082e2012-08-24 10:16:42 -0700442 // restore initial conditions (default device unblank, etc)
443 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800444
445 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700446 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800447}
448
Robert Carr1db73f62016-12-21 12:58:51 -0800449static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700450 status_t err = client->initCheck();
451 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800452 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800453 }
Robert Carr1db73f62016-12-21 12:58:51 -0800454 return nullptr;
455}
456
457sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
458 return initClient(new Client(this));
459}
460
461sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
462 const sp<IGraphicBufferProducer>& gbp) {
463 if (authenticateSurfaceTexture(gbp) == false) {
464 return nullptr;
465 }
466 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
467 if (layer == nullptr) {
468 return nullptr;
469 }
470
471 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800472}
473
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700474sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
475 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700476{
477 class DisplayToken : public BBinder {
478 sp<SurfaceFlinger> flinger;
479 virtual ~DisplayToken() {
480 // no more references, this display must be terminated
481 Mutex::Autolock _l(flinger->mStateLock);
482 flinger->mCurrentState.displays.removeItem(this);
483 flinger->setTransactionFlags(eDisplayTransactionNeeded);
484 }
485 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700486 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700487 : flinger(flinger) {
488 }
489 };
490
491 sp<BBinder> token = new DisplayToken(this);
492
493 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700494 // Display ID is assigned when virtual display is allocated by HWC.
495 DisplayDeviceState state;
496 state.isSecure = secure;
497 state.displayName = displayName;
498 mCurrentState.displays.add(token, state);
499 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700500 return token;
501}
502
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700503void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700504 Mutex::Autolock _l(mStateLock);
505
Dominik Laskowski075d3172018-05-24 15:50:06 -0700506 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
507 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700508 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700509 return;
510 }
511
Dominik Laskowski075d3172018-05-24 15:50:06 -0700512 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
513 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700514 ALOGE("destroyDisplay called for non-virtual display");
515 return;
516 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700517 mInterceptor->saveDisplayDeletion(state.sequenceId);
518 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700519 setTransactionFlags(eDisplayTransactionNeeded);
520}
521
Mathias Agopiane57f2922012-08-09 16:29:12 -0700522sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700523 std::optional<DisplayId> displayId;
524
525 if (id == HWC_DISPLAY_PRIMARY) {
526 displayId = getInternalDisplayId();
527 } else if (id == HWC_DISPLAY_EXTERNAL) {
528 displayId = getExternalDisplayId();
529 }
530
531 if (!displayId) {
532 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800533 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700534 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700535
536 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700537}
538
Ady Abraham37965d42018-11-01 13:43:32 -0700539status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
540 if (!outGetColorManagement) {
541 return BAD_VALUE;
542 }
543 *outGetColorManagement = useColorManagement;
544 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700545}
546
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800547void SurfaceFlinger::bootFinished()
548{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700549 if (mStartPropertySetThread->join() != NO_ERROR) {
550 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800551 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800552 const nsecs_t now = systemTime();
553 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000554 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700555
556 // wait patiently for the window manager death
557 const String16 name("window");
558 sp<IBinder> window(defaultServiceManager()->getService(name));
559 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700560 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700561 }
Robert Carr720e5062018-07-30 17:45:14 -0700562 sp<IBinder> input(defaultServiceManager()->getService(
563 String16("inputflinger")));
564 if (input == nullptr) {
565 ALOGE("Failed to link to input service");
566 } else {
567 mInputFlinger = interface_cast<IInputFlinger>(input);
568 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700569
Steven Thomas050b2c82017-03-06 11:45:16 -0800570 if (mVrFlinger) {
571 mVrFlinger->OnBootFinished();
572 }
573
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700574 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700575 // formerly we would just kill the process, but we now ask it to exit so it
576 // can choose where to stop the animation.
577 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700578
579 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
580 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
581 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700582
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800583 postMessageAsync(new LambdaMessage([this] {
584 readPersistentProperties();
585 mBootStage = BootStage::FINISHED;
586 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800587}
588
Dan Stoza436ccf32018-06-21 12:10:12 -0700589uint32_t SurfaceFlinger::getNewTexture() {
590 {
591 std::lock_guard lock(mTexturePoolMutex);
592 if (!mTexturePool.empty()) {
593 uint32_t name = mTexturePool.back();
594 mTexturePool.pop_back();
595 ATRACE_INT("TexturePoolSize", mTexturePool.size());
596 return name;
597 }
598
599 // The pool was too small, so increase it for the future
600 ++mTexturePoolSize;
601 }
602
603 // The pool was empty, so we need to get a new texture name directly using a
604 // blocking call to the main thread
605 uint32_t name = 0;
606 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
607 return name;
608}
609
Mathias Agopian3f844832013-08-07 21:24:32 -0700610void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700611 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700612}
613
Wei Wangf9b05ee2017-07-19 20:59:39 -0700614// Do not call property_set on main thread which will be blocked by init
615// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700616void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700617 ALOGI( "SurfaceFlinger's main thread ready to run. "
618 "Initializing graphics H/W...");
619
Thierry Strudel2924d012017-08-14 15:19:37 -0700620 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900621
Steven Thomasb02664d2017-07-26 18:48:28 -0700622 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800623
Steven Thomasb02664d2017-07-26 18:48:28 -0700624 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700625 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700626 mScheduler = getFactory().createScheduler([this](bool enabled) {
627 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
628 });
629
Ana Krulec98b5b242018-08-10 15:03:23 -0700630 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700631 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700632 [this] { resyncWithRateLimit(); },
633 impl::EventThread::InterceptVSyncsCallback());
634 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700635 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700636 [this] { resyncWithRateLimit(); },
637 [this](nsecs_t timestamp) {
638 mInterceptor->saveVSyncEvent(timestamp);
639 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800640
Ana Krulec98b5b242018-08-10 15:03:23 -0700641 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700642 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
643 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700644 } else {
645 mEventThreadSource =
646 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
647 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
648 mEventThread =
649 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
650 [this] { resyncWithRateLimit(); },
651 impl::EventThread::InterceptVSyncsCallback(),
652 "appEventThread");
653 mSfEventThreadSource =
654 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
655 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
656
657 mSFEventThread =
658 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
659 [this] { resyncWithRateLimit(); },
660 [this](nsecs_t timestamp) {
661 mInterceptor->saveVSyncEvent(timestamp);
662 },
663 "sfEventThread");
664 mEventQueue->setEventThread(mSFEventThread.get());
665 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
666 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800667
Steven Thomasb02664d2017-07-26 18:48:28 -0700668 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700669 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700670 renderEngineFeature |= (useColorManagement ?
671 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700672 renderEngineFeature |= (useContextPriority ?
673 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700674
675 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
676 getBE().mRenderEngine =
Peiyong Linc6780972018-10-28 15:24:08 -0700677 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
678 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800679 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700680
681 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
682 "Starting with vr flinger active is not currently supported.");
Lloyd Pique90c115d2018-09-18 21:39:42 -0700683 getBE().mHwc = getFactory().createHWComposer(getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -0700684 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800685 // Process any initial hotplug and resulting display changes.
686 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700687 const auto display = getDefaultDisplayDeviceLocked();
688 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700689 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700690 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800691
Steven Thomas050b2c82017-03-06 11:45:16 -0800692 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700693 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700694 // This callback is called from the vr flinger dispatch thread. We
695 // need to call signalTransaction(), which requires holding
696 // mStateLock when we're not on the main thread. Acquiring
697 // mStateLock from the vr flinger dispatch thread might trigger a
698 // deadlock in surface flinger (see b/66916578), so post a message
699 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700700 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700701 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
702 mVrFlingerRequestsDisplay = requestDisplay;
703 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700704 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800705 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700706 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
707 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700708 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700709 .value_or(0),
710 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800711 if (!mVrFlinger) {
712 ALOGE("Failed to start vrflinger");
713 }
714 }
715
Lloyd Pique90c115d2018-09-18 21:39:42 -0700716 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700717 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700718
Mathias Agopian92a979a2012-08-02 18:32:23 -0700719 // initialize our drawing state
720 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700721
Andy McFadden13a082e2012-08-24 10:16:42 -0700722 // set initial conditions (e.g. unblank default device)
723 initializeDisplays();
724
David Sodmanbc815282017-11-05 18:57:52 -0800725 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700726
Wei Wangf9b05ee2017-07-19 20:59:39 -0700727 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700728
729 const bool presentFenceReliable =
730 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
731 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700732
733 if (mStartPropertySetThread->Start() != NO_ERROR) {
734 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800735 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800736
Chia-I Wud49d6692018-06-27 07:17:41 +0800737 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
738 // is used to saturate legacy sRGB content. However, to make sure the same color under
739 // Display P3 will be saturated to the same color, we intentionally break the API spec
740 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
741 // such saturation matrix on Display P3 is understood fully, the API should always return
742 // identify matrix.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700743 mEnhancedSaturationMatrix =
744 getHwComposer().getDataspaceSaturationMatrix(*display->getId(), Dataspace::SRGB_LINEAR);
Chia-I Wud49d6692018-06-27 07:17:41 +0800745
746 // we will apply this on Display P3.
747 if (mEnhancedSaturationMatrix != mat4()) {
748 ColorSpace srgb(ColorSpace::sRGB());
749 ColorSpace displayP3(ColorSpace::DisplayP3());
750 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
751 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
752 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
753 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800754
Dan Stoza9e56aa02015-11-02 13:00:03 -0800755 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700756}
757
Romain Guy11d63f42017-07-20 12:47:14 -0700758void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700759 Mutex::Autolock _l(mStateLock);
760
Romain Guy11d63f42017-07-20 12:47:14 -0700761 char value[PROPERTY_VALUE_MAX];
762
763 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800764 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700765 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800766 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100767
768 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700769 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700770}
771
Mathias Agopiana67e4182012-06-19 17:26:12 -0700772void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800773 // Start boot animation service by setting a property mailbox
774 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700775 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800776 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700777 if (mStartPropertySetThread->join() != NO_ERROR) {
778 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800779 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700780}
781
Mathias Agopian875d8e12013-06-07 15:35:48 -0700782size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800783 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700784}
785
Mathias Agopian875d8e12013-06-07 15:35:48 -0700786size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800787 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700788}
789
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800790// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800791
Jamie Gennis582270d2011-08-17 18:19:00 -0700792bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800793 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800794 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800795 return authenticateSurfaceTextureLocked(bufferProducer);
796}
797
798bool SurfaceFlinger::authenticateSurfaceTextureLocked(
799 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800800 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800801 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800802}
803
Brian Anderson6b376712017-04-04 10:51:39 -0700804status_t SurfaceFlinger::getSupportedFrameTimestamps(
805 std::vector<FrameEvent>* outSupported) const {
806 *outSupported = {
807 FrameEvent::REQUESTED_PRESENT,
808 FrameEvent::ACQUIRE,
809 FrameEvent::LATCH,
810 FrameEvent::FIRST_REFRESH_START,
811 FrameEvent::LAST_REFRESH_START,
812 FrameEvent::GPU_COMPOSITION_DONE,
813 FrameEvent::DEQUEUE_READY,
814 FrameEvent::RELEASE,
815 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700816 ConditionalLock _l(mStateLock,
817 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700818 if (!getHwComposer().hasCapability(
819 HWC2::Capability::PresentFenceIsNotReliable)) {
820 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
821 }
822 return NO_ERROR;
823}
824
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700825status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
826 Vector<DisplayInfo>* configs) {
827 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700828 return BAD_VALUE;
829 }
830
Dominik Laskowski075d3172018-05-24 15:50:06 -0700831 const auto displayId = getPhysicalDisplayId(displayToken);
832 if (!displayId) {
833 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700834 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835
Mathias Agopian8b736f12012-08-13 17:54:26 -0700836 // TODO: Not sure if display density should handled by SF any longer
837 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700838 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700839 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700840 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800841 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700842 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700843 }
844 return density;
845 }
846 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700847 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700848 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700849 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700850 return getDensityFromProperty("ro.sf.lcd_density"); }
851 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700852
Dan Stoza7f7da322014-05-02 15:26:25 -0700853 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700854
Steven Thomas6d8110b2017-08-31 18:24:21 -0700855 ConditionalLock _l(mStateLock,
856 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700857 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700858 DisplayInfo info = DisplayInfo();
859
Dan Stoza9e56aa02015-11-02 13:00:03 -0800860 float xdpi = hwConfig->getDpiX();
861 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700862
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700863 info.w = hwConfig->getWidth();
864 info.h = hwConfig->getHeight();
865 // Default display viewport to display width and height
866 info.viewportW = info.w;
867 info.viewportH = info.h;
868
Dominik Laskowski075d3172018-05-24 15:50:06 -0700869 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700870 // The density of the device is provided by a build property
871 float density = Density::getBuildDensity() / 160.0f;
872 if (density == 0) {
873 // the build doesn't provide a density -- this is wrong!
874 // use xdpi instead
875 ALOGE("ro.sf.lcd_density must be defined as a build property");
876 density = xdpi / 160.0f;
877 }
878 if (Density::getEmuDensity()) {
879 // if "qemu.sf.lcd_density" is specified, it overrides everything
880 xdpi = ydpi = density = Density::getEmuDensity();
881 density /= 160.0f;
882 }
883 info.density = density;
884
885 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700886 const auto display = getDefaultDisplayDeviceLocked();
887 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700888
889 // This is for screenrecord
890 const Rect viewport = display->getViewport();
891 if (viewport.isValid()) {
892 info.viewportW = uint32_t(viewport.getWidth());
893 info.viewportH = uint32_t(viewport.getHeight());
894 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700895 } else {
896 // TODO: where should this value come from?
897 static const int TV_DENSITY = 213;
898 info.density = TV_DENSITY / 160.0f;
899 info.orientation = 0;
900 }
901
Dan Stoza7f7da322014-05-02 15:26:25 -0700902 info.xdpi = xdpi;
903 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800904 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900905 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800906
Andy McFadden91b2ca82014-06-13 14:04:23 -0700907 // This is how far in advance a buffer must be queued for
908 // presentation at a given time. If you want a buffer to appear
909 // on the screen at time N, you must submit the buffer before
910 // (N - presentationDeadline).
911 //
912 // Normally it's one full refresh period (to give SF a chance to
913 // latch the buffer), but this can be reduced by configuring a
914 // DispSync offset. Any additional delays introduced by the hardware
915 // composer or panel must be accounted for here.
916 //
917 // We add an additional 1ms to allow for processing time and
918 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800919 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800920 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700921
922 // All non-virtual displays are currently considered secure.
923 info.secure = true;
924
Dominik Laskowski075d3172018-05-24 15:50:06 -0700925 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700926 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800927 std::swap(info.w, info.h);
928 }
929
Michael Wright28f24d02016-07-12 13:30:53 -0700930 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700931 }
932
Dan Stoza7f7da322014-05-02 15:26:25 -0700933 return NO_ERROR;
934}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700935
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700936status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
937 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700938 return BAD_VALUE;
939 }
940
Ana Krulece588e312018-09-18 12:32:24 -0700941 if (mUseScheduler) {
942 mScheduler->getDisplayStatInfo(stats);
943 } else {
944 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
945 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
946 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700947 return NO_ERROR;
948}
949
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700950int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
951 const auto display = getDisplayDevice(displayToken);
952 if (!display) {
953 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800954 return BAD_VALUE;
955 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700956
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700957 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700958}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700959
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700960void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700961 if (display->isVirtual()) {
962 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
963 return;
964 }
965
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700966 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700967 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700968 return;
969 }
970
Dominik Laskowski075d3172018-05-24 15:50:06 -0700971 const auto displayId = display->getId();
972 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700973
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700974 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700975 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700976}
977
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700978status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700979 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700980 Vector<DisplayInfo> configs;
981 getDisplayConfigs(displayToken, &configs);
982 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
983 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
984 configs.size());
985 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700986 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700987 const auto display = getDisplayDevice(displayToken);
988 if (!display) {
989 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
990 displayToken.get());
991 } else if (display->isVirtual()) {
992 ALOGW("Attempt to set active config %d for virtual display", mode);
993 } else {
994 setActiveConfigInternal(display, mode);
995 }
996 }));
997
Mathias Agopian888c8222012-08-04 21:10:38 -0700998 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700999}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001000
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001001status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1002 Vector<ColorMode>* outColorModes) {
1003 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001004 return BAD_VALUE;
1005 }
1006
Dominik Laskowski075d3172018-05-24 15:50:06 -07001007 const auto displayId = getPhysicalDisplayId(displayToken);
1008 if (!displayId) {
1009 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -07001010 }
1011
Peiyong Lina52f0292018-03-14 17:26:31 -07001012 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001013 {
1014 ConditionalLock _l(mStateLock,
1015 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001016 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001017 }
Michael Wright28f24d02016-07-12 13:30:53 -07001018 outColorModes->clear();
1019 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1020
1021 return NO_ERROR;
1022}
1023
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001024ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1025 if (const auto display = getDisplayDevice(displayToken)) {
1026 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001027 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001028 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001029}
1030
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001031void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1032 Dataspace dataSpace, RenderIntent renderIntent) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001033 if (display->isVirtual()) {
1034 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
1035 return;
1036 }
1037
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001038 ColorMode currentMode = display->getActiveColorMode();
1039 Dataspace currentDataSpace = display->getCompositionDataSpace();
1040 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001041
Peiyong Lin38e9a562018-04-10 16:24:20 -07001042 if (mode == currentMode && dataSpace == currentDataSpace &&
1043 renderIntent == currentRenderIntent) {
1044 return;
1045 }
1046
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001047 display->setActiveColorMode(mode);
1048 display->setCompositionDataSpace(dataSpace);
1049 display->setActiveRenderIntent(renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001050
Dominik Laskowski075d3172018-05-24 15:50:06 -07001051 const auto displayId = display->getId();
1052 LOG_ALWAYS_FATAL_IF(!displayId);
1053 getHwComposer().setActiveColorMode(*displayId, mode, renderIntent);
1054
Dominik Laskowski34157762018-10-31 13:07:19 -07001055 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), display=%s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001056 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
Dominik Laskowski34157762018-10-31 13:07:19 -07001057 renderIntent, to_string(*displayId).c_str());
Michael Wright28f24d02016-07-12 13:30:53 -07001058}
1059
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001060status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001061 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001062 Vector<ColorMode> modes;
1063 getDisplayColorModes(displayToken, &modes);
1064 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1065 if (mode < ColorMode::NATIVE || !exists) {
1066 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1067 decodeColorMode(mode).c_str(), mode, displayToken.get());
1068 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001069 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001070 const auto display = getDisplayDevice(displayToken);
1071 if (!display) {
1072 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1073 decodeColorMode(mode).c_str(), mode, displayToken.get());
1074 } else if (display->isVirtual()) {
1075 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1076 decodeColorMode(mode).c_str(), mode);
1077 } else {
1078 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1079 RenderIntent::COLORIMETRIC);
1080 }
1081 }));
1082
Michael Wright28f24d02016-07-12 13:30:53 -07001083 return NO_ERROR;
1084}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001085
Svetoslavd85084b2014-03-20 10:28:31 -07001086status_t SurfaceFlinger::clearAnimationFrameStats() {
1087 Mutex::Autolock _l(mStateLock);
1088 mAnimFrameTracker.clearStats();
1089 return NO_ERROR;
1090}
1091
1092status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1093 Mutex::Autolock _l(mStateLock);
1094 mAnimFrameTracker.getStats(outStats);
1095 return NO_ERROR;
1096}
1097
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001098status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1099 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001100 Mutex::Autolock _l(mStateLock);
1101
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001102 const auto display = getDisplayDeviceLocked(displayToken);
1103 if (!display) {
1104 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001105 return BAD_VALUE;
1106 }
1107
Peiyong Linfb069302018-04-25 14:34:31 -07001108 // At this point the DisplayDeivce should already be set up,
1109 // meaning the luminance information is already queried from
1110 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001111 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001112 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1113 capabilities.getDesiredMaxLuminance(),
1114 capabilities.getDesiredMaxAverageLuminance(),
1115 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001116
1117 return NO_ERROR;
1118}
1119
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001120status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1121 ui::PixelFormat* outFormat,
1122 ui::Dataspace* outDataspace,
1123 uint8_t* outComponentMask) const {
1124 if (!outFormat || !outDataspace || !outComponentMask) {
1125 return BAD_VALUE;
1126 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001127 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001128 if (!display || !display->getId()) {
1129 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1130 return BAD_VALUE;
1131 }
1132 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1133 outDataspace, outComponentMask);
1134}
1135
Kevin DuBois74e53772018-11-19 10:52:38 -08001136status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1137 bool enable, uint8_t componentMask,
1138 uint64_t maxFrames) const {
1139 const auto display = getDisplayDevice(displayToken);
1140 if (!display || !display->getId()) {
1141 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1142 return BAD_VALUE;
1143 }
1144
1145 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1146 componentMask, maxFrames);
1147}
1148
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001149status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1150 uint64_t maxFrames, uint64_t timestamp,
1151 DisplayedFrameStats* outStats) const {
1152 const auto display = getDisplayDevice(displayToken);
1153 if (!display || !display->getId()) {
1154 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1155 return BAD_VALUE;
1156 }
1157
1158 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1159 outStats);
1160}
1161
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001162status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001163 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001164 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001165
Chia-I Wu90f669f2017-10-05 14:24:41 -07001166 if (mInjectVSyncs == enable) {
1167 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001168 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001169
Ana Krulec98b5b242018-08-10 15:03:23 -07001170 // TODO(akrulec): Part of the Injector should be refactored, so that it
1171 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001172 if (enable) {
1173 ALOGV("VSync Injections enabled");
1174 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001175 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001176 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001177 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001178 impl::EventThread::InterceptVSyncsCallback(),
1179 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001180 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001181 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001182 } else {
1183 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001184 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001185 }
1186
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001187 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001188 }));
1189
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001190 return NO_ERROR;
1191}
1192
1193status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001194 Mutex::Autolock _l(mStateLock);
1195
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001196 if (!mInjectVSyncs) {
1197 ALOGE("VSync Injections not enabled");
1198 return BAD_VALUE;
1199 }
1200 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1201 ALOGV("Injecting VSync inside SurfaceFlinger");
1202 mVSyncInjector->onInjectSyncEvent(when);
1203 }
1204 return NO_ERROR;
1205}
1206
Lloyd Pique755e3192018-01-31 16:46:15 -08001207status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1208 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001209 // Try to acquire a lock for 1s, fail gracefully
1210 const status_t err = mStateLock.timedLock(s2ns(1));
1211 const bool locked = (err == NO_ERROR);
1212 if (!locked) {
1213 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1214 return TIMED_OUT;
1215 }
1216
1217 outLayers->clear();
1218 mCurrentState.traverseInZOrder([&](Layer* layer) {
1219 outLayers->push_back(layer->getLayerDebugInfo());
1220 });
1221
1222 mStateLock.unlock();
1223 return NO_ERROR;
1224}
1225
Peiyong Linc6780972018-10-28 15:24:08 -07001226status_t SurfaceFlinger::getCompositionPreference(
1227 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1228 Dataspace* outWideColorGamutDataspace,
1229 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001230 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001231 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001232 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001233 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001234 return NO_ERROR;
1235}
1236
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001237// ----------------------------------------------------------------------------
1238
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001239sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1240 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001241 if (mUseScheduler) {
1242 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1243 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1244 } else {
1245 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1246 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001247 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001248 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1249 return mSFEventThread->createEventConnection();
1250 } else {
1251 return mEventThread->createEventConnection();
1252 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001253 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001254}
1255
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001256// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001257
1258void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001259 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001260}
1261
1262void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001263 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001264}
1265
1266void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001267 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001268}
1269
1270void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001271 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001272 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001273}
1274
1275status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001276 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001277 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001278}
1279
1280status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001281 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001282 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001283 if (res == NO_ERROR) {
1284 msg->wait();
1285 }
1286 return res;
1287}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001288
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001289void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001290 do {
1291 waitForEvent();
1292 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001293}
1294
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001295void SurfaceFlinger::enableHardwareVsync() {
1296 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001297 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001298 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001299 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001300 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001301 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001302}
1303
Jesse Hall948fe0c2013-10-14 12:56:09 -07001304void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001305 Mutex::Autolock _l(mHWVsyncLock);
1306
Jesse Hall948fe0c2013-10-14 12:56:09 -07001307 if (makeAvailable) {
1308 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001309 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1310 if (mUseScheduler) {
1311 mScheduler->makeHWSyncAvailable(true);
1312 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001313 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001314 // Hardware vsync is not currently available, so abort the resync
1315 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001316 return;
1317 }
1318
Dominik Laskowski075d3172018-05-24 15:50:06 -07001319 const auto displayId = getInternalDisplayId();
1320 if (!displayId || !getHwComposer().isConnected(*displayId)) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001321 return;
1322 }
1323
Dominik Laskowski075d3172018-05-24 15:50:06 -07001324 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001325 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001326
Ana Krulece588e312018-09-18 12:32:24 -07001327 if (mUseScheduler) {
1328 mScheduler->setVsyncPeriod(period);
1329 } else {
1330 mPrimaryDispSync->reset();
1331 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001332
Ana Krulece588e312018-09-18 12:32:24 -07001333 if (!mPrimaryHWVsyncEnabled) {
1334 mPrimaryDispSync->beginResync();
1335 mEventControlThread->setVsyncEnabled(true);
1336 mPrimaryHWVsyncEnabled = true;
1337 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001338 }
1339}
1340
Jesse Hall948fe0c2013-10-14 12:56:09 -07001341void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001342 Mutex::Autolock _l(mHWVsyncLock);
1343 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001344 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001345 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001346 mPrimaryHWVsyncEnabled = false;
1347 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001348 if (makeUnavailable) {
1349 mHWVsyncAvailable = false;
1350 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001351}
1352
Tim Murray4a4e4a22016-04-19 16:29:23 +00001353void SurfaceFlinger::resyncWithRateLimit() {
1354 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001355
1356 // No explicit locking is needed here since EventThread holds a lock while calling this method
1357 static nsecs_t sLastResyncAttempted = 0;
1358 const nsecs_t now = systemTime();
1359 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001360 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001361 }
Dan Stoza57164302017-05-08 14:03:54 -07001362 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001363}
1364
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001365void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1366 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001367 ATRACE_NAME("SF onVsync");
1368
Steven Thomas3cfac282017-02-06 12:29:30 -08001369 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001370 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001371 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001372 return;
1373 }
1374
Dominik Laskowski075d3172018-05-24 15:50:06 -07001375 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001376 return;
1377 }
1378
Dominik Laskowski075d3172018-05-24 15:50:06 -07001379 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001380 // For now, we don't do anything with external display vsyncs.
1381 return;
1382 }
1383
Ana Krulece588e312018-09-18 12:32:24 -07001384 if (mUseScheduler) {
1385 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001386 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001387 bool needsHwVsync = false;
1388 { // Scope for the lock
1389 Mutex::Autolock _l(mHWVsyncLock);
1390 if (mPrimaryHWVsyncEnabled) {
1391 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1392 }
1393 }
1394
1395 if (needsHwVsync) {
1396 enableHardwareVsync();
1397 } else {
1398 disableHardwareVsync(false);
1399 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001400 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001401}
1402
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001403void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001404 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1405 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001406}
1407
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001408void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001409 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001410 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001411 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001412
Lloyd Piqueba04e622017-12-14 17:11:26 -08001413 // Ignore events that do not have the right sequenceId.
1414 if (sequenceId != getBE().mComposerSequenceId) {
1415 return;
1416 }
1417
Steven Thomasb02664d2017-07-26 18:48:28 -07001418 // Only lock if we're not on the main thread. This function is normally
1419 // called on a hwbinder thread, but for the primary display it's called on
1420 // the main thread with the state lock already held, so don't attempt to
1421 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001422 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001423
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001424 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001425
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001426 if (std::this_thread::get_id() == mMainThreadId) {
1427 // Process all pending hot plug events immediately if we are on the main thread.
1428 processDisplayHotplugEventsLocked();
1429 }
1430
Lloyd Piqueba04e622017-12-14 17:11:26 -08001431 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001432}
1433
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001434void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001435 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001436 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001437 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001438 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001439 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001440}
1441
Dominik Laskowski075d3172018-05-24 15:50:06 -07001442void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001443 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001444 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001445 if (const auto displayId = getInternalDisplayId()) {
1446 getHwComposer().setVsyncEnabled(*displayId,
1447 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1448 }
Mathias Agopian86303202012-07-24 22:46:10 -07001449}
1450
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001451// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001452void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001453 if (mUseScheduler) {
1454 mScheduler->disableHardwareVsync(true);
1455 } else {
1456 disableHardwareVsync(true);
1457 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001458 // Clear the drawing state so that the logic inside of
1459 // handleTransactionLocked will fire. It will determine the delta between
1460 // mCurrentState and mDrawingState and re-apply all changes when we make the
1461 // transition.
1462 mDrawingState.displays.clear();
1463 mDisplays.clear();
1464}
1465
Steven Thomas050b2c82017-03-06 11:45:16 -08001466void SurfaceFlinger::updateVrFlinger() {
1467 if (!mVrFlinger)
1468 return;
1469 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001470 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001471 return;
1472 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001473
David Sodman105b7dc2017-11-04 20:28:14 -07001474 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001475 ALOGE("Vr flinger is only supported for remote hardware composer"
1476 " service connections. Ignoring request to transition to vr"
1477 " flinger.");
1478 mVrFlingerRequestsDisplay = false;
1479 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001480 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001481
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001482 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001483
Steven Thomas0123ac62018-07-12 11:32:34 -07001484 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001485 LOG_ALWAYS_FATAL_IF(!display);
1486 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001487 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1488 // called below. Clear the reference now so we don't accidentally use it
1489 // later.
1490 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001491
Steven Thomasb02664d2017-07-26 18:48:28 -07001492 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001493 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001494 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001495
Steven Thomasb02664d2017-07-26 18:48:28 -07001496 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001497 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Pique90c115d2018-09-18 21:39:42 -07001498 getBE().mHwc = getFactory().createHWComposer(
1499 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -07001500 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001501
David Sodman105b7dc2017-11-04 20:28:14 -07001502 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1503 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001504
1505 if (vrFlingerRequestsDisplay) {
1506 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001507 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001508
1509 mVisibleRegionsDirty = true;
1510 invalidateHwcGeometry();
1511
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001512 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001513 display = getDefaultDisplayDeviceLocked();
1514 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001515 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001516
Steven Thomasb02664d2017-07-26 18:48:28 -07001517 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski075d3172018-05-24 15:50:06 -07001518 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001519 const nsecs_t period = activeConfig->getVsyncPeriod();
1520 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001521
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001522 // The present fences returned from vr_hwc are not an accurate
1523 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001524 if (mUseScheduler) {
1525 mScheduler->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() || !hasSyncFramework);
1526 } else {
1527 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1528 !hasSyncFramework);
1529 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001530
Steven Thomasb02664d2017-07-26 18:48:28 -07001531 // Use phase of 0 since phase is not known.
1532 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001533 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1534 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001535
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001536 resyncToHardwareVsync(false);
1537
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001538 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001539 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001540}
1541
Mathias Agopian4fec8732012-06-29 14:12:52 -07001542void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001543 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001544 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001545 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001546 if (mUseScheduler) {
1547 // This call is made each time SF wakes up and creates a new frame.
1548 mScheduler->incrementFrameCounter();
1549 }
Dan Stoza50182882016-07-08 12:02:20 -07001550 bool frameMissed = !mHadClientComposition &&
1551 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001552 (mPreviousPresentFence->getSignalTime() ==
1553 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001554 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001555 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001556 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001557 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001558 if (mPropagateBackpressure) {
1559 signalLayerUpdate();
1560 break;
1561 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001562 }
Dan Stoza50182882016-07-08 12:02:20 -07001563
Steven Thomas050b2c82017-03-06 11:45:16 -08001564 // Now that we're going to make it to the handleMessageTransaction()
1565 // call below it's safe to call updateVrFlinger(), which will
1566 // potentially trigger a display handoff.
1567 updateVrFlinger();
1568
Dan Stoza6b9454d2014-11-07 16:00:59 -08001569 bool refreshNeeded = handleMessageTransaction();
1570 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001571 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001572 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001573 // Signal a refresh if a transaction modified the window state,
1574 // a new buffer was latched, or if HWC has requested a full
1575 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001576 signalRefresh();
1577 }
1578 break;
1579 }
1580 case MessageQueue::REFRESH: {
1581 handleMessageRefresh();
1582 break;
1583 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001584 }
1585}
1586
Dan Stoza6b9454d2014-11-07 16:00:59 -08001587bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001588 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001589 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001590 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001591 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001592 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001593 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001594}
1595
Mathias Agopian4fec8732012-06-29 14:12:52 -07001596void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001597 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001598
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001599 mRefreshPending = false;
1600
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001601 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001602 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001603 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001604 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001605 for (const auto& [token, display] : mDisplays) {
1606 beginFrame(display);
1607 prepareFrame(display);
1608 doDebugFlashRegions(display, repaintEverything);
1609 doComposition(display, repaintEverything);
1610 }
1611
Adrian Roos1e1a1282017-11-01 19:05:31 +01001612 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001613 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001614
1615 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001616 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001617
Dan Stozabfbffeb2016-07-21 14:49:33 -07001618 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001619 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001620 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001621 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001622 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001623
Alec Mouri86770e52018-09-24 22:40:58 +00001624 // Setup RenderEngine sync fences if native sync is supported.
1625 if (getBE().mRenderEngine->useNativeFenceSync()) {
1626 if (mHadClientComposition) {
1627 base::unique_fd flushFence(getRenderEngine().flush());
1628 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1629 getBE().flushFence = new Fence(std::move(flushFence));
1630 } else {
1631 // Cleanup for hygiene.
1632 getBE().flushFence = Fence::NO_FENCE;
1633 }
1634 }
1635
Jorim Jaggi90535212018-05-23 23:44:06 +02001636 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001637
David Sodman7e4ae112018-02-09 15:02:28 -08001638 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001639 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001640 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001641 compositionInfo.hwc.hwcLayer = nullptr;
1642 }
David Sodmanba340492018-08-05 21:51:33 -07001643 }
David Sodman7e4ae112018-02-09 15:02:28 -08001644
1645 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001646}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001647
David Sodmanfa9b2af2017-12-24 13:28:59 -08001648
1649bool SurfaceFlinger::handleMessageInvalidate() {
1650 ATRACE_CALL();
1651 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001652}
1653
David Sodman79bba0e2018-08-05 18:07:49 -07001654void SurfaceFlinger::calculateWorkingSet() {
1655 ATRACE_CALL();
1656 ALOGV(__FUNCTION__);
1657
David Sodman79bba0e2018-08-05 18:07:49 -07001658 // build the h/w work list
1659 if (CC_UNLIKELY(mGeometryInvalid)) {
1660 mGeometryInvalid = false;
1661 for (const auto& [token, display] : mDisplays) {
1662 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001663 if (!displayId) {
1664 continue;
1665 }
David Sodman79bba0e2018-08-05 18:07:49 -07001666
Dominik Laskowski075d3172018-05-24 15:50:06 -07001667 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
1668 for (size_t i = 0; i < currentLayers.size(); i++) {
1669 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001670
Dominik Laskowski075d3172018-05-24 15:50:06 -07001671 if (!layer->hasHwcLayer(*displayId)) {
1672 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1673 layer->forceClientComposition(*displayId);
1674 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001675 }
1676 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001677
1678 layer->setGeometry(display, i);
1679 if (mDebugDisableHWC || mDebugRegion) {
1680 layer->forceClientComposition(*displayId);
1681 }
David Sodman79bba0e2018-08-05 18:07:49 -07001682 }
1683 }
1684 }
1685
1686 // Set the per-frame data
1687 for (const auto& [token, display] : mDisplays) {
1688 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001689 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001690 continue;
1691 }
1692
1693 if (mDrawingState.colorMatrixChanged) {
1694 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001695 status_t result =
1696 getHwComposer().setColorTransform(*displayId, mDrawingState.colorMatrix);
Dominik Laskowski34157762018-10-31 13:07:19 -07001697 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %s: %d",
1698 to_string(*displayId).c_str(), result);
David Sodman79bba0e2018-08-05 18:07:49 -07001699 }
1700 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1701 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001702 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001703 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1704 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1705 !display->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001706 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001707 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1708 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1709 !display->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001710 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001711 }
1712
Peiyong Lind3788632018-09-18 16:01:31 -07001713 // TODO(b/111562338) remove when composer 2.3 is shipped.
1714 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001715 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001716 }
1717
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001718 if (layer->getRoundedCornerState().radius > 0.0f) {
1719 layer->forceClientComposition(*displayId);
1720 }
1721
Dominik Laskowski075d3172018-05-24 15:50:06 -07001722 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001723 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001724 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001725 continue;
1726 }
1727
Dominik Laskowski075d3172018-05-24 15:50:06 -07001728 layer->setPerFrameData(*displayId, display->getTransform(), display->getViewport(),
1729 display->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001730 }
1731
Peiyong Lin13effd12018-07-24 17:01:47 -07001732 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001733 ColorMode colorMode;
1734 Dataspace dataSpace;
1735 RenderIntent renderIntent;
1736 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1737 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1738 }
1739 }
1740
1741 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001742
1743 for (const auto& [token, display] : mDisplays) {
1744 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001745 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001746 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001747
1748 if (displayId) {
1749 if (!layer->setHwcLayer(*displayId)) {
1750 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1751 }
1752 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001753 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001754
Dominik Laskowski05275f12018-11-01 15:03:24 -07001755 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001756 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1757 }
1758 }
David Sodman79bba0e2018-08-05 18:07:49 -07001759}
1760
David Sodmanfa9b2af2017-12-24 13:28:59 -08001761void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001762{
1763 // is debugging enabled
1764 if (CC_LIKELY(!mDebugRegion))
1765 return;
1766
David Sodmanfa9b2af2017-12-24 13:28:59 -08001767 if (display->isPoweredOn()) {
1768 // transform the dirty region into this screen's coordinate space
1769 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1770 if (!dirtyRegion.isEmpty()) {
1771 // redraw the whole screen
1772 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001773
David Sodmanfa9b2af2017-12-24 13:28:59 -08001774 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001775 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001776 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001777
Alec Mouri0a9c7b82018-11-16 13:05:25 -08001778 display->queueBuffer(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001779 }
1780 }
1781
David Sodmanfa9b2af2017-12-24 13:28:59 -08001782 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001783
1784 if (mDebugRegion > 1) {
1785 usleep(mDebugRegion * 1000);
1786 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001787
Dominik Laskowski05275f12018-11-01 15:03:24 -07001788 prepareFrame(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001789}
1790
Adrian Roos1e1a1282017-11-01 19:05:31 +01001791void SurfaceFlinger::doTracing(const char* where) {
1792 ATRACE_CALL();
1793 ATRACE_NAME(where);
1794 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001795 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001796 }
1797}
1798
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001799void SurfaceFlinger::logLayerStats() {
1800 ATRACE_CALL();
1801 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001802 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001803 if (display->isPrimary()) {
1804 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001805 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001806 }
1807 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001808
1809 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001810 }
1811}
1812
David Sodman2b406362017-12-15 13:33:47 -08001813void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001814{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001815 ATRACE_CALL();
1816 ALOGV("preComposition");
1817
David Sodman2b406362017-12-15 13:33:47 -08001818 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1819
Mathias Agopiancd60f992012-08-16 16:28:27 -07001820 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001821 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001822 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001823 needExtraInvalidate = true;
1824 }
Robert Carr2047fae2016-11-28 14:09:09 -08001825 });
1826
Mathias Agopiancd60f992012-08-16 16:28:27 -07001827 if (needExtraInvalidate) {
1828 signalLayerUpdate();
1829 }
1830}
1831
Ana Krulece588e312018-09-18 12:32:24 -07001832void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1833 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001834 // Update queue of past composite+present times and determine the
1835 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001836 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001837 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001838 while (!getBE().mCompositePresentTimes.empty()) {
1839 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001840 // Cached values should have been updated before calling this method,
1841 // which helps avoid duplicate syscalls.
1842 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1843 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1844 break;
1845 }
1846 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001847 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001848 }
1849
1850 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001851 while (getBE().mCompositePresentTimes.size() > 16) {
1852 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001853 }
1854
Ana Krulece588e312018-09-18 12:32:24 -07001855 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001856}
1857
Ana Krulece588e312018-09-18 12:32:24 -07001858void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1859 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001860 // Integer division and modulo round toward 0 not -inf, so we need to
1861 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001862 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1863 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1864 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001865
Brian Andersond0010582017-03-07 13:20:31 -08001866 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1867 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001868 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001869 }
1870
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001871 // Snap the latency to a value that removes scheduling jitter from the
1872 // composition and present times, which often have >1ms of jitter.
1873 // Reducing jitter is important if an app attempts to extrapolate
1874 // something (such as user input) to an accurate diasplay time.
1875 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1876 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001877 nsecs_t bias = stats.vsyncPeriod / 2;
1878 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1879 nsecs_t snappedCompositeToPresentLatency =
1880 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001881
David Sodman99974d22017-11-28 12:04:33 -08001882 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001883 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1884 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001885 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001886}
1887
David Sodman2b406362017-12-15 13:33:47 -08001888void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001889{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001890 ATRACE_CALL();
1891 ALOGV("postComposition");
1892
Brian Anderson3546a3f2016-07-14 11:51:14 -07001893 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001894 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001895 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001896 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001897 }
1898
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001899 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001900 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001901
David Sodman73beded2017-11-15 11:56:06 -08001902 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001903 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001904 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001905 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001906 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001907 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001908 } else {
1909 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1910 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001911
David Sodman73beded2017-11-15 11:56:06 -08001912 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001913 mPreviousPresentFence =
Dominik Laskowski075d3172018-05-24 15:50:06 -07001914 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001915 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001916 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001917
Ana Krulece588e312018-09-18 12:32:24 -07001918 DisplayStatInfo stats;
1919 if (mUseScheduler) {
1920 mScheduler->getDisplayStatInfo(&stats);
1921 } else {
1922 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1923 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
1924 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001925
David Sodman2b406362017-12-15 13:33:47 -08001926 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001927 // when we started doing work for this frame, but that should be okay
1928 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07001929 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001930 CompositorTiming compositorTiming;
1931 {
David Sodman99974d22017-11-28 12:04:33 -08001932 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1933 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001934 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001935
Robert Carr2047fae2016-11-28 14:09:09 -08001936 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001937 bool frameLatched = layer->onPostComposition(display->getId(), glCompositionDoneFenceTime,
1938 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001939 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001940 recordBufferingStats(layer->getName().string(),
1941 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001942 }
Robert Carr2047fae2016-11-28 14:09:09 -08001943 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001944
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001945 if (presentFenceTime->isValid()) {
Ana Krulece588e312018-09-18 12:32:24 -07001946 if (mUseScheduler) {
1947 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001948 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001949 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
1950 enableHardwareVsync();
1951 } else {
1952 disableHardwareVsync(false);
1953 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001954 }
1955 }
1956
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001957 if (!hasSyncFramework) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001958 if (display && getHwComposer().isConnected(*display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07001959 if (mUseScheduler) {
1960 mScheduler->enableHardwareVsync();
1961 } else {
1962 enableHardwareVsync();
1963 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001964 }
1965 }
1966
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001967 if (mAnimCompositionPending) {
1968 mAnimCompositionPending = false;
1969
Brian Anderson4e606e32017-03-16 15:34:57 -07001970 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001971 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001972 std::move(presentFenceTime));
Dominik Laskowski075d3172018-05-24 15:50:06 -07001973 } else if (display && getHwComposer().isConnected(*display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001974 // The HWC doesn't support present fences, so use the refresh
1975 // timestamp instead.
Dominik Laskowski075d3172018-05-24 15:50:06 -07001976 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001977 mAnimFrameTracker.setActualPresentTime(presentTime);
1978 }
1979 mAnimFrameTracker.advanceFrame();
1980 }
Dan Stozab90cf072015-03-05 11:05:59 -08001981
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001982 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001983 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001984 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001985 }
1986
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001987 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001988
Dominik Laskowski075d3172018-05-24 15:50:06 -07001989 if (display && getHwComposer().isConnected(*display->getId()) && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08001990 return;
1991 }
1992
1993 nsecs_t currentTime = systemTime();
1994 if (mHasPoweredOff) {
1995 mHasPoweredOff = false;
1996 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001997 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001998 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001999 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2000 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002001 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002002 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002003 }
David Sodman4a36e932017-11-07 14:29:47 -08002004 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002005 }
David Sodman4a36e932017-11-07 14:29:47 -08002006 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002007
2008 {
2009 std::lock_guard lock(mTexturePoolMutex);
2010 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
2011 if (refillCount > 0) {
2012 const size_t offset = mTexturePool.size();
2013 mTexturePool.resize(mTexturePoolSize);
2014 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2015 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2016 }
2017 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002018
Marissa Wallfda30bb2018-10-12 11:34:28 -07002019 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002020 mTransactionCompletedThread.sendCallbacks();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002021}
2022
2023void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002024 ATRACE_CALL();
2025 ALOGV("rebuildLayerStacks");
2026
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002027 // We need to clear these out now as these may be holding on to a
2028 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2029 // also holds a reference. When the set of visible layers is recomputed,
2030 // some layers may be destroyed if the only thing keeping them alive was
2031 // that list of visible layers associated with each display. The layer
2032 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2033 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2034 for (const auto& [token, display] : mDisplays) {
2035 getBE().mCompositionInfo[token].clear();
2036 }
2037
Mathias Agopiancd60f992012-08-16 16:28:27 -07002038 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002039 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002040 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002041 mVisibleRegionsDirty = false;
2042 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002043
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002044 for (const auto& pair : mDisplays) {
2045 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07002046 Region opaqueRegion;
2047 Region dirtyRegion;
2048 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002049 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07002050 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002051 const Rect bounds = display->getBounds();
2052 if (display->isPoweredOn()) {
2053 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002054
Jeff Sharkey76488112017-02-27 14:15:18 -07002055 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002056 bool hwcLayerDestroyed = false;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002057 const auto displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002058 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002059 Region drawRegion(tr.transform(
2060 layer->visibleNonTransparentRegion));
2061 drawRegion.andSelf(bounds);
2062 if (!drawRegion.isEmpty()) {
2063 layersSortedByZ.add(layer);
2064 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002065 // Clear out the HWC layer if this layer was
2066 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002067 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002068 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002069 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002070 // WM changes display->layerStack upon sleep/awake.
2071 // Here we make sure we delete the HWC layers even if
2072 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002073 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002074 }
2075
2076 // If a layer is not going to get a release fence because
2077 // it is invisible, but it is also going to release its
2078 // old buffer, add it to the list of layers needing
2079 // fences.
2080 if (hwcLayerDestroyed) {
2081 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2082 mLayersWithQueuedFrames.cend(), layer);
2083 if (found != mLayersWithQueuedFrames.cend()) {
2084 layersNeedingFences.add(layer);
2085 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002086 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002087 });
2088 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002089 display->setVisibleLayersSortedByZ(layersSortedByZ);
2090 display->setLayersNeedingFences(layersNeedingFences);
2091 display->undefinedRegion.set(bounds);
2092 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2093 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002094 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002095 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002096}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002097
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002098// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002099// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002100// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002101// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002102// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002103// The returned HDR data space is one of
2104// - Dataspace::UNKNOWN
2105// - Dataspace::BT2020_HLG
2106// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002107Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2108 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002109 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002110 *outHdrDataSpace = Dataspace::UNKNOWN;
2111
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002112 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002113 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002114 case Dataspace::V0_SCRGB:
2115 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002116 case Dataspace::BT2020:
2117 case Dataspace::BT2020_ITU:
2118 case Dataspace::BT2020_LINEAR:
2119 case Dataspace::DISPLAY_BT2020:
2120 bestDataSpace = Dataspace::DISPLAY_BT2020;
2121 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002122 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002123 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002124 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002125 case Dataspace::BT2020_PQ:
2126 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002127 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002128 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002129 case Dataspace::BT2020_HLG:
2130 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002131 // When there's mixed PQ content and HLG content, we set the HDR
2132 // data space to be BT2020_PQ and convert HLG to PQ.
2133 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2134 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002135 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002136 break;
2137 default:
2138 break;
2139 }
Romain Guy54f154a2017-10-24 21:40:32 +01002140 }
2141
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002142 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002143}
2144
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002145// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002146void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2147 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002148 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2149 *outMode = ColorMode::NATIVE;
2150 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002151 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002152 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002153 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002154
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002155 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002156 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002157
Peiyong Lindfde5112018-06-05 10:58:41 -07002158 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002159 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002160 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002161 if (isHdr) {
2162 bestDataSpace = hdrDataSpace;
2163 }
2164
Chia-I Wu0d711262018-05-21 15:19:35 -07002165 RenderIntent intent;
2166 switch (mDisplayColorSetting) {
2167 case DisplayColorSetting::MANAGED:
2168 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002169 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002170 break;
2171 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002172 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002173 break;
2174 default: // vendor display color setting
2175 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2176 break;
2177 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002178
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002179 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002180}
2181
David Sodmanfa9b2af2017-12-24 13:28:59 -08002182void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002183{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002184 bool dirty = !display->getDirtyRegion(false).isEmpty();
2185 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2186 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002187
David Sodmanfa9b2af2017-12-24 13:28:59 -08002188 // If nothing has changed (!dirty), don't recompose.
2189 // If something changed, but we don't currently have any visible layers,
2190 // and didn't when we last did a composition, then skip it this time.
2191 // The second rule does two things:
2192 // - When all layers are removed from a display, we'll emit one black
2193 // frame, then nothing more until we get new layers.
2194 // - When a display is created with a private layer stack, we won't
2195 // emit any black frames until a layer is added to the layer stack.
2196 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002197
Dominik Laskowski075d3172018-05-24 15:50:06 -07002198 const char flagPrefix[] = {'-', '+'};
2199 static_cast<void>(flagPrefix);
2200 ALOGV_IF(display->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2201 __FUNCTION__, mustRecompose ? "doing" : "skipping", display->getDebugName().c_str(),
2202 flagPrefix[dirty], flagPrefix[empty], flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002203
David Sodmanfa9b2af2017-12-24 13:28:59 -08002204 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002205
David Sodmanfa9b2af2017-12-24 13:28:59 -08002206 if (mustRecompose) {
2207 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002208 }
2209}
2210
David Sodmanfa9b2af2017-12-24 13:28:59 -08002211void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002212{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002213 if (!display->isPoweredOn()) {
2214 return;
David Sodman2b406362017-12-15 13:33:47 -08002215 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002216
Dominik Laskowski05275f12018-11-01 15:03:24 -07002217 status_t result = display->prepareFrame(getHwComposer(),
2218 getBE().mCompositionInfo[display->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002219 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
2220 display->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002221}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002222
David Sodmanfa9b2af2017-12-24 13:28:59 -08002223void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002224 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002225 ALOGV("doComposition");
2226
David Sodmanfa9b2af2017-12-24 13:28:59 -08002227 if (display->isPoweredOn()) {
2228 // transform the dirty region into this screen's coordinate space
2229 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002230
David Sodmanfa9b2af2017-12-24 13:28:59 -08002231 // repaint the framebuffer (if needed)
2232 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002233
David Sodmanfa9b2af2017-12-24 13:28:59 -08002234 display->dirtyRegion.clear();
2235 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002236 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002237 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002238}
2239
David Sodmanfa9b2af2017-12-24 13:28:59 -08002240void SurfaceFlinger::postFrame()
2241{
2242 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002243 const auto display = getDefaultDisplayDeviceLocked();
2244 if (display && getHwComposer().isConnected(*display->getId())) {
2245 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002246 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2247 logFrameStats();
2248 }
2249 }
2250}
2251
2252void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002253{
Mathias Agopian841cde52012-03-01 15:44:37 -08002254 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002255 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002256
David Sodmanfa9b2af2017-12-24 13:28:59 -08002257 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002258
David Sodmanfa9b2af2017-12-24 13:28:59 -08002259 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002260 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002261 if (displayId) {
2262 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002263 }
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002264 display->onPresentDisplayCompleted();
David Sodman15094112018-10-11 09:39:37 -07002265 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002266 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002267
Chia-I Wu7b549592017-11-15 09:14:57 -08002268 // The layer buffer from the previous frame (if any) is released
2269 // by HWC only when the release fence from this frame (if any) is
2270 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002271 if (displayId && layer->hasHwcLayer(*displayId)) {
2272 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2273 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002274 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002275
2276 // If the layer was client composited in the previous frame, we
2277 // need to merge with the previous client target acquire fence.
2278 // Since we do not track that, always merge with the current
2279 // client target acquire fence when it is available, even though
2280 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002281 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002282 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002283 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002284 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002285
David Sodman15094112018-10-11 09:39:37 -07002286 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002287 }
Chia-I Wu83806892017-11-16 10:50:20 -08002288
2289 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002290 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002291 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002292 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002293 sp<Fence> presentFence =
2294 displayId ? getBE().mHwc->getPresentFence(*displayId) : Fence::NO_FENCE;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002295 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002296 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002297 }
2298 }
2299
Dominik Laskowski075d3172018-05-24 15:50:06 -07002300 if (displayId) {
2301 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002302 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002303 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002304}
2305
Mathias Agopian87baae12012-07-31 12:38:26 -07002306void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002307{
Mathias Agopian841cde52012-03-01 15:44:37 -08002308 ATRACE_CALL();
2309
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002310 // here we keep a copy of the drawing state (that is the state that's
2311 // going to be overwritten by handleTransactionLocked()) outside of
2312 // mStateLock so that the side-effects of the State assignment
2313 // don't happen with mStateLock held (which can cause deadlocks).
2314 State drawingState(mDrawingState);
2315
Mathias Agopianca4d3602011-05-19 15:38:14 -07002316 Mutex::Autolock _l(mStateLock);
2317 const nsecs_t now = systemTime();
2318 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002319
Mathias Agopianca4d3602011-05-19 15:38:14 -07002320 // Here we're guaranteed that some transaction flags are set
2321 // so we can call handleTransactionLocked() unconditionally.
2322 // We call getTransactionFlags(), which will also clear the flags,
2323 // with mStateLock held to guarantee that mCurrentState won't change
2324 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002325
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002326 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002327 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002328 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002329
Mathias Agopianca4d3602011-05-19 15:38:14 -07002330 mLastTransactionTime = systemTime() - now;
2331 mDebugInTransaction = 0;
2332 invalidateHwcGeometry();
2333 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002334}
2335
Lloyd Piqueba04e622017-12-14 17:11:26 -08002336void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2337 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002338 const std::optional<DisplayIdentificationInfo> info =
2339 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002340
Dominik Laskowski075d3172018-05-24 15:50:06 -07002341 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002342 continue;
2343 }
2344
Lloyd Piqueba04e622017-12-14 17:11:26 -08002345 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002346 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002347 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002348 mPhysicalDisplayTokens[info->id] = new BBinder();
2349 DisplayDeviceState state;
2350 state.displayId = info->id;
2351 state.isSecure = true; // All physical displays are currently considered secure.
2352 state.displayName = info->name;
2353 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2354 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002355 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002356 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002357 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002358
Dominik Laskowski075d3172018-05-24 15:50:06 -07002359 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2360 if (index >= 0) {
2361 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2362 mInterceptor->saveDisplayDeletion(state.sequenceId);
2363 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002364 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002365 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002366 }
2367
2368 processDisplayChangesLocked();
2369 }
2370
2371 mPendingHotplugEvents.clear();
2372}
2373
Lloyd Pique99d3da52018-01-22 17:48:03 -08002374sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002375 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
2376 const DisplayDeviceState& state, const sp<DisplaySurface>& dispSurface,
2377 const sp<IGraphicBufferProducer>& producer) {
2378 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
2379 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002380 creationArgs.isSecure = state.isSecure;
2381 creationArgs.displaySurface = dispSurface;
2382 creationArgs.hasWideColorGamut = false;
2383 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002384
Dominik Laskowski075d3172018-05-24 15:50:06 -07002385 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2386 creationArgs.isPrimary = isInternalDisplay;
2387
2388 if (useColorManagement && displayId) {
2389 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002390 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002391 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002392 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002393 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002394
Dominik Laskowski7e045462018-05-30 13:02:02 -07002395 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002396 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002397 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002398 }
tangrobin6753a022018-08-10 10:58:54 +08002399 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002400
Dominik Laskowski075d3172018-05-24 15:50:06 -07002401 if (displayId) {
2402 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002403 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002404 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002405 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002406
Lloyd Pique90c115d2018-09-18 21:39:42 -07002407 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002408 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002409 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002410
Lloyd Pique99d3da52018-01-22 17:48:03 -08002411 // Make sure that composition can never be stalled by a virtual display
2412 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002413 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002414 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002415 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2416 }
2417
Dominik Laskowski075d3172018-05-24 15:50:06 -07002418 creationArgs.displayInstallOrientation =
2419 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002420
Lloyd Pique99d3da52018-01-22 17:48:03 -08002421 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002422 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002423
Lloyd Pique90c115d2018-09-18 21:39:42 -07002424 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002425
2426 if (maxFrameBufferAcquiredBuffers >= 3) {
2427 nativeWindowSurface->preallocateBuffers();
2428 }
2429
2430 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002431 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002432 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002433 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002434 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002435 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002436 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002437 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002438 if (!state.isVirtual()) {
2439 LOG_ALWAYS_FATAL_IF(!displayId);
2440 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002441 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002442
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002443 display->setLayerStack(state.layerStack);
2444 display->setProjection(state.orientation, state.viewport, state.frame);
2445 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002446
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002447 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002448}
2449
Lloyd Pique347200f2017-12-14 17:00:15 -08002450void SurfaceFlinger::processDisplayChangesLocked() {
2451 // here we take advantage of Vector's copy-on-write semantics to
2452 // improve performance by skipping the transaction entirely when
2453 // know that the lists are identical
2454 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2455 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2456 if (!curr.isIdenticalTo(draw)) {
2457 mVisibleRegionsDirty = true;
2458 const size_t cc = curr.size();
2459 size_t dc = draw.size();
2460
2461 // find the displays that were removed
2462 // (ie: in drawing state but not in current state)
2463 // also handle displays that changed
2464 // (ie: displays that are in both lists)
2465 for (size_t i = 0; i < dc;) {
2466 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2467 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002468 // Save display IDs before disconnecting.
2469 const auto internalDisplayId = getInternalDisplayId();
2470 const auto externalDisplayId = getExternalDisplayId();
2471
Lloyd Pique347200f2017-12-14 17:00:15 -08002472 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002473 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2474 display->disconnect(getHwComposer());
2475 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002476 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002477 if (mUseScheduler) {
2478 mScheduler->hotplugReceived(mAppConnectionHandle,
2479 EventThread::DisplayType::Primary, false);
2480 } else {
2481 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2482 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002483 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002484 if (mUseScheduler) {
2485 mScheduler->hotplugReceived(mAppConnectionHandle,
2486 EventThread::DisplayType::External, false);
2487 } else {
2488 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2489 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002490 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002491 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002492 } else {
2493 // this display is in both lists. see if something changed.
2494 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002495 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002496 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2497 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2498 if (state_binder != draw_binder) {
2499 // changing the surface is like destroying and
2500 // recreating the DisplayDevice, so we just remove it
2501 // from the drawing state, so that it get re-added
2502 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002503 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2504 display->disconnect(getHwComposer());
2505 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002506 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002507 mDrawingState.displays.removeItemsAt(i);
2508 dc--;
2509 // at this point we must loop to the next item
2510 continue;
2511 }
2512
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002513 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002514 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002515 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002516 }
2517 if ((state.orientation != draw[i].orientation) ||
2518 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002519 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002520 }
2521 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002522 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002523 }
2524 }
2525 }
2526 ++i;
2527 }
2528
2529 // find displays that were added
2530 // (ie: in current state but not in drawing state)
2531 for (size_t i = 0; i < cc; i++) {
2532 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2533 const DisplayDeviceState& state(curr[i]);
2534
2535 sp<DisplaySurface> dispSurface;
2536 sp<IGraphicBufferProducer> producer;
2537 sp<IGraphicBufferProducer> bqProducer;
2538 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002539 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002540
Dominik Laskowski075d3172018-05-24 15:50:06 -07002541 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002542 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002543 // Virtual displays without a surface are dormant:
2544 // they have external state (layer stack, projection,
2545 // etc.) but no internal state (i.e. a DisplayDevice).
2546 if (state.surface != nullptr) {
2547 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002548 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002549 int width = 0;
2550 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2551 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2552 int height = 0;
2553 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2554 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2555 int intFormat = 0;
2556 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2557 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002558 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002559
Dominik Laskowski075d3172018-05-24 15:50:06 -07002560 displayId =
2561 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002562 }
2563
2564 // TODO: Plumb requested format back up to consumer
2565
2566 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002567 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002568 bqProducer, bqConsumer,
2569 state.displayName);
2570
2571 dispSurface = vds;
2572 producer = vds;
2573 }
2574 } else {
2575 ALOGE_IF(state.surface != nullptr,
2576 "adding a supported display, but rendering "
2577 "surface is provided (%p), ignoring it",
2578 state.surface.get());
2579
Dominik Laskowski075d3172018-05-24 15:50:06 -07002580 displayId = state.displayId;
2581 LOG_ALWAYS_FATAL_IF(!displayId);
2582 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002583 producer = bqProducer;
2584 }
2585
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002586 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002587 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002588 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002589 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002590 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002591 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002592 LOG_ALWAYS_FATAL_IF(!displayId);
2593
2594 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002595 if (mUseScheduler) {
2596 mScheduler->hotplugReceived(mAppConnectionHandle,
2597 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002598 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002599 } else {
2600 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2601 true);
2602 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002603 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002604 if (mUseScheduler) {
2605 mScheduler->hotplugReceived(mAppConnectionHandle,
2606 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002607 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002608 } else {
2609 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2610 true);
2611 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002612 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002613 }
2614 }
2615 }
2616 }
2617 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002618
2619 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002620}
2621
Mathias Agopian87baae12012-07-31 12:38:26 -07002622void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002623{
Dan Stoza7dde5992015-05-22 09:51:44 -07002624 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002625 mCurrentState.traverseInZOrder([](Layer* layer) {
2626 layer->notifyAvailableFrames();
2627 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002628
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002629 /*
2630 * Traversal of the children
2631 * (perform the transaction for each of them if needed)
2632 */
2633
Robert Carr720e5062018-07-30 17:45:14 -07002634 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002635 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002636 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002637 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002638 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002639
2640 const uint32_t flags = layer->doTransaction(0);
2641 if (flags & Layer::eVisibleRegion)
2642 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002643
2644 if (flags & Layer::eInputInfoChanged) {
2645 inputChanged = true;
2646 }
Robert Carr2047fae2016-11-28 14:09:09 -08002647 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002648 }
2649
2650 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002651 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002652 */
2653
Mathias Agopiane57f2922012-08-09 16:29:12 -07002654 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002655 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002656 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002657 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002658
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002659 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002660 // The transform hint might have changed for some layers
2661 // (either because a display has changed, or because a layer
2662 // as changed).
2663 //
2664 // Walk through all the layers in currentLayers,
2665 // and update their transform hint.
2666 //
2667 // If a layer is visible only on a single display, then that
2668 // display is used to calculate the hint, otherwise we use the
2669 // default display.
2670 //
2671 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2672 // the hint is set before we acquire a buffer from the surface texture.
2673 //
2674 // NOTE: layer transactions have taken place already, so we use their
2675 // drawing state. However, SurfaceFlinger's own transaction has not
2676 // happened yet, so we must use the current state layer list
2677 // (soon to become the drawing state list).
2678 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002679 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002680 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002681 bool first = true;
2682 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002683 // NOTE: we rely on the fact that layers are sorted by
2684 // layerStack first (so we don't have to traverse the list
2685 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002686 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002687 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002688 currentlayerStack = layerStack;
2689 // figure out if this layerstack is mirrored
2690 // (more than one display) if so, pick the default display,
2691 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002692 hintDisplay = nullptr;
2693 for (const auto& [token, display] : mDisplays) {
2694 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2695 if (hintDisplay) {
2696 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002697 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002698 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002699 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002700 }
2701 }
2702 }
2703 }
Chet Haase91d25932013-04-11 15:24:55 -07002704
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002705 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002706 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2707 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002708
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002709 // could be null when this layer is using a layerStack
2710 // that is not visible on any display. Also can occur at
2711 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002712 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002713 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002714
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002715 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002716 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002717 if (hintDisplay) {
2718 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002719 }
Robert Carr2047fae2016-11-28 14:09:09 -08002720
2721 first = false;
2722 });
Mathias Agopian84300952012-11-21 16:02:13 -08002723 }
2724
2725
Mathias Agopian3559b072012-08-15 13:46:03 -07002726 /*
2727 * Perform our own transaction if needed
2728 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002729
2730 if (mLayersAdded) {
2731 mLayersAdded = false;
2732 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002733 mVisibleRegionsDirty = true;
2734 }
2735
2736 // some layers might have been removed, so
2737 // we need to update the regions they're exposing.
2738 if (mLayersRemoved) {
2739 mLayersRemoved = false;
2740 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002741 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002742 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002743 // this layer is not visible anymore
2744 // TODO: we could traverse the tree from front to back and
2745 // compute the actual visible region
2746 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002747 Region visibleReg;
2748 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002749 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002750 }
Robert Carr2047fae2016-11-28 14:09:09 -08002751 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002752 }
2753
2754 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002755
Robert Carr720e5062018-07-30 17:45:14 -07002756 if ((inputChanged || mVisibleRegionsDirty) && mInputFlinger) {
2757 updateInputWindows();
2758 }
2759
Riley Andrews03414a12014-07-01 14:22:59 -07002760 updateCursorAsync();
2761}
2762
Robert Carr720e5062018-07-30 17:45:14 -07002763void SurfaceFlinger::updateInputWindows() {
2764 ATRACE_CALL();
2765
2766 Vector<InputWindowInfo> inputHandles;
2767
2768 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2769 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002770 // When calculating the screen bounds we ignore the transparent region since it may
2771 // result in an unwanted offset.
2772 inputHandles.add(layer->fillInputInfo(
2773 layer->computeScreenBounds(false /* reduceTransparentRegion */)));
Robert Carr720e5062018-07-30 17:45:14 -07002774 }
2775 });
2776 mInputFlinger->setInputWindows(inputHandles);
2777}
2778
Riley Andrews03414a12014-07-01 14:22:59 -07002779void SurfaceFlinger::updateCursorAsync()
2780{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002781 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002782 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002783 continue;
2784 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002785
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002786 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2787 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002788 }
2789 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002790}
2791
chaviw61626f22018-11-15 16:26:27 -08002792void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2793 if (layer->hasReadyFrame()) {
2794 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2795 if (layer->shouldPresentNow(expectedPresentTime)) {
2796 bool ignored = false;
2797 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
2798 }
2799 }
2800 layer->releasePendingBuffer(systemTime());
2801}
2802
Mathias Agopian4fec8732012-06-29 14:12:52 -07002803void SurfaceFlinger::commitTransaction()
2804{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002805 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002806 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002807 for (const auto& l : mLayersPendingRemoval) {
2808 recordBufferingStats(l->getName().string(),
2809 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002810
2811 // We need to release the HWC layers when the Layer is removed
2812 // from the current state otherwise the HWC layer just continues
2813 // showing at its last configured state until we eventually
2814 // abandon the buffer queue.
2815 if (l->isRemovedFromCurrentState()) {
Robert Carr3aee9892018-11-07 12:53:41 -08002816 l->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* child) {
chaviw61626f22018-11-15 16:26:27 -08002817 child->destroyHwcLayersForAllDisplays();
2818 latchAndReleaseBuffer(child);
Robert Carr3aee9892018-11-07 12:53:41 -08002819 });
Robert Carr2e102c92018-10-23 12:11:15 -07002820 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002821 }
2822 mLayersPendingRemoval.clear();
2823 }
2824
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002825 // If this transaction is part of a window animation then the next frame
2826 // we composite should be considered an animation as well.
2827 mAnimCompositionPending = mAnimTransactionPending;
2828
Mathias Agopian4fec8732012-06-29 14:12:52 -07002829 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002830 // clear the "changed" flags in current state
2831 mCurrentState.colorMatrixChanged = false;
2832
Robert Carr1f0a16a2016-10-24 16:27:39 -07002833 mDrawingState.traverseInZOrder([](Layer* layer) {
2834 layer->commitChildList();
2835 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002836 mTransactionPending = false;
2837 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002838 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002839}
2840
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002841void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2842 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002843 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002844 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002845
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002846 Region aboveOpaqueLayers;
2847 Region aboveCoveredLayers;
2848 Region dirty;
2849
Mathias Agopian87baae12012-07-31 12:38:26 -07002850 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002851
Robert Carr2047fae2016-11-28 14:09:09 -08002852 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002853 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002854 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002855
Jesse Hall01e29052013-02-19 16:13:35 -08002856 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002857 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002858 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002859 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002860
Mathias Agopianab028732010-03-16 16:41:46 -07002861 /*
2862 * opaqueRegion: area of a surface that is fully opaque.
2863 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002864 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002865
2866 /*
2867 * visibleRegion: area of a surface that is visible on screen
2868 * and not fully transparent. This is essentially the layer's
2869 * footprint minus the opaque regions above it.
2870 * Areas covered by a translucent surface are considered visible.
2871 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002872 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002873
2874 /*
2875 * coveredRegion: area of a surface that is covered by all
2876 * visible regions above it (which includes the translucent areas).
2877 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002878 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002879
Jesse Halla8026d22012-09-25 13:25:04 -07002880 /*
2881 * transparentRegion: area of a surface that is hinted to be completely
2882 * transparent. This is only used to tell when the layer has no visible
2883 * non-transparent regions and can be removed from the layer list. It
2884 * does not affect the visibleRegion of this layer or any layers
2885 * beneath it. The hint may not be correct if apps don't respect the
2886 * SurfaceView restrictions (which, sadly, some don't).
2887 */
2888 Region transparentRegion;
2889
Mathias Agopianab028732010-03-16 16:41:46 -07002890
2891 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002892 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002893 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002894 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07002895
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002896 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002897 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002898 if (!visibleRegion.isEmpty()) {
2899 // Remove the transparent area from the visible region
2900 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002901 if (tr.preserveRects()) {
2902 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002903 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002904 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002905 // transformation too complex, can't do the
2906 // transparent region optimization.
2907 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002908 }
Mathias Agopianab028732010-03-16 16:41:46 -07002909 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002910
Mathias Agopianab028732010-03-16 16:41:46 -07002911 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002912 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002913 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002914 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002915 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002916 // the opaque region is the layer's footprint
2917 opaqueRegion = visibleRegion;
2918 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002919 }
2920 }
2921
Robert Carre5f4f692018-01-12 13:12:28 -08002922 if (visibleRegion.isEmpty()) {
2923 layer->clearVisibilityRegions();
2924 return;
2925 }
2926
Mathias Agopianab028732010-03-16 16:41:46 -07002927 // Clip the covered region to the visible region
2928 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2929
2930 // Update aboveCoveredLayers for next (lower) layer
2931 aboveCoveredLayers.orSelf(visibleRegion);
2932
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002933 // subtract the opaque region covered by the layers above us
2934 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002935
2936 // compute this layer's dirty region
2937 if (layer->contentDirty) {
2938 // we need to invalidate the whole region
2939 dirty = visibleRegion;
2940 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002941 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002942 layer->contentDirty = false;
2943 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002944 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002945 * the exposed region consists of two components:
2946 * 1) what's VISIBLE now and was COVERED before
2947 * 2) what's EXPOSED now less what was EXPOSED before
2948 *
2949 * note that (1) is conservative, we start with the whole
2950 * visible region but only keep what used to be covered by
2951 * something -- which mean it may have been exposed.
2952 *
2953 * (2) handles areas that were not covered by anything but got
2954 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002955 */
Mathias Agopianab028732010-03-16 16:41:46 -07002956 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002957 const Region oldVisibleRegion = layer->visibleRegion;
2958 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002959 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2960 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002961 }
2962 dirty.subtractSelf(aboveOpaqueLayers);
2963
2964 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002965 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002966
Mathias Agopianab028732010-03-16 16:41:46 -07002967 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002968 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002969
Jesse Halla8026d22012-09-25 13:25:04 -07002970 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002971 layer->setVisibleRegion(visibleRegion);
2972 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002973 layer->setVisibleNonTransparentRegion(
2974 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002975 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002976
Mathias Agopian87baae12012-07-31 12:38:26 -07002977 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002978}
2979
Chia-I Wuab0c3192017-08-01 11:29:00 -07002980void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002981 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002982 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2983 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002984 }
2985 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002986}
2987
Dan Stoza6b9454d2014-11-07 16:00:59 -08002988bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002989{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002990 ALOGV("handlePageFlip");
2991
Brian Andersond6927fb2016-07-23 23:37:30 -07002992 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002993
Mathias Agopian4fec8732012-06-29 14:12:52 -07002994 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002995 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002996 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002997
2998 // Store the set of layers that need updates. This set must not change as
2999 // buffers are being latched, as this could result in a deadlock.
3000 // Example: Two producers share the same command stream and:
3001 // 1.) Layer 0 is latched
3002 // 2.) Layer 0 gets a new frame
3003 // 2.) Layer 1 gets a new frame
3004 // 3.) Layer 1 is latched.
3005 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3006 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003007 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003008 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003009 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003010 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3011 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003012 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003013 } else {
3014 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003015 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003016 } else {
3017 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003018 }
Robert Carr2047fae2016-11-28 14:09:09 -08003019 });
3020
Dan Stoza9e56aa02015-11-02 13:00:03 -08003021 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri86770e52018-09-24 22:40:58 +00003022 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
Dan Stozaee44edd2015-03-23 15:50:23 -07003023 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003024 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07003025 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06003026 newDataLatched = true;
3027 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003028 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003029
Alec Mouri86770e52018-09-24 22:40:58 +00003030 // Clear the renderengine fence here...
3031 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3032 // clear instead of sp::clear.
3033 getBE().flushFence = Fence::NO_FENCE;
3034
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003035 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003036
3037 // If we will need to wake up at some time in the future to deal with a
3038 // queued frame that shouldn't be displayed during this vsync period, wake
3039 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003040 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003041 signalLayerUpdate();
3042 }
3043
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003044 // enter boot animation on first buffer latch
3045 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3046 ALOGI("Enter boot animation");
3047 mBootStage = BootStage::BOOTANIMATION;
3048 }
3049
Dan Stoza6b9454d2014-11-07 16:00:59 -08003050 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003051 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003052}
3053
Mathias Agopianad456f92011-01-13 17:53:01 -08003054void SurfaceFlinger::invalidateHwcGeometry()
3055{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003056 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003057}
3058
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003059void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& display,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003060 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003061 // We only need to actually compose the display if:
3062 // 1) It is being handled by hardware composer, which may need this to
3063 // keep its virtual display state machine in sync, or
3064 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski34157762018-10-31 13:07:19 -07003065 if (!display->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003066 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003067 return;
3068 }
3069
Dan Stoza9e56aa02015-11-02 13:00:03 -08003070 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003071 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003072
3073 // swap buffers (presentation)
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003074 display->queueBuffer(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003075}
3076
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003077bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003078 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003079
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003080 const Region bounds(display->bounds());
3081 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003082 const auto displayId = display->getId();
3083 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003084 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003085
Peiyong Lind3788632018-09-18 16:01:31 -07003086 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003087 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003088 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003089
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003090 // Framebuffer will live in this scope for GPU composition.
3091 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
3092
Dan Stoza9e56aa02015-11-02 13:00:03 -08003093 if (hasClientComposition) {
3094 ALOGV("hasClientComposition");
3095
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003096 sp<GraphicBuffer> buf = display->dequeueBuffer();
3097
3098 if (buf == nullptr) {
3099 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3100 "client composition for this frame",
3101 display->getDisplayName().c_str());
3102 return false;
3103 }
3104
3105 // Bind the framebuffer in this scope.
3106 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3107 buf->getNativeBuffer());
3108
3109 if (fbo->getStatus() != NO_ERROR) {
3110 ALOGW("Binding buffer for display [%s] failed with status: %d",
3111 display->getDisplayName().c_str(), fbo->getStatus());
3112 return false;
3113 }
3114
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003115 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003116 if (display->hasWideColorGamut()) {
3117 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003118 }
3119 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003120 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003121 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003122
Dominik Laskowski7e045462018-05-30 13:02:02 -07003123 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003124 const bool skipClientColorTransform =
3125 getBE().mHwc
3126 ->hasDisplayCapability(displayId,
3127 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003128
Peiyong Lind3788632018-09-18 16:01:31 -07003129 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003130 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3131 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003132 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003133 }
3134
Chia-I Wud49d6692018-06-27 07:17:41 +08003135 // The current enhanced saturation matrix is designed to enhance Display P3,
3136 // thus we only apply this matrix when the render intent is not colorimetric
3137 // and the output color space is Display P3.
3138 needsEnhancedColorMatrix =
3139 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3140 outputDataspace == Dataspace::DISPLAY_P3);
3141 if (needsEnhancedColorMatrix) {
3142 colorMatrix *= mEnhancedSaturationMatrix;
3143 }
3144
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003145 display->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003146
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003147 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003148 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003149 // when using overlays, we assume a fully transparent framebuffer
3150 // NOTE: we could reduce how much we need to clear, for instance
3151 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003152 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003153 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003154 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003155 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003156 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003157 // we're left with the letterbox region
3158 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003159 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003160
3161 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003162 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003163
Mathias Agopianb9494d52012-04-18 02:28:45 -07003164 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003165 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003166 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003167 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003168 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003169 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003170
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003171 const Rect& bounds = display->getBounds();
3172 const Rect& scissor = display->getScissor();
3173 if (scissor != bounds) {
3174 // scissor doesn't match the screen's dimensions, so we
3175 // need to clear everything outside of it and enable
3176 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003177
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003178 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003179 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003180 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003181 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003182
Mathias Agopian85d751c2012-08-29 16:59:24 -07003183 /*
3184 * and then, render the layers targeted at the framebuffer
3185 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003186
Dan Stoza9e56aa02015-11-02 13:00:03 -08003187 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003188 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003189 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003190 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003191 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003192 displayTransform.transform(layer->visibleRegion)));
3193 ALOGV("Layer: %s", layer->getName().string());
3194 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003195 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003196 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003197 case HWC2::Composition::Cursor:
3198 case HWC2::Composition::Device:
3199 case HWC2::Composition::Sideband:
3200 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003201 LOG_ALWAYS_FATAL_IF(!displayId);
David Sodmanc1498e62018-09-12 14:36:26 -07003202 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003203 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
David Sodmanc1498e62018-09-12 14:36:26 -07003204 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003205 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003206 // never clear the very first layer since we're
3207 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003208 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003209 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003210 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003211 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003212 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003213 if (layer->hasColorTransform()) {
3214 mat4 tmpMatrix;
3215 if (applyColorMatrix) {
3216 tmpMatrix = mDrawingState.colorMatrix;
3217 }
3218 tmpMatrix *= layer->getColorTransform();
3219 if (needsEnhancedColorMatrix) {
3220 tmpMatrix *= mEnhancedSaturationMatrix;
3221 }
3222 getRenderEngine().setColorTransform(tmpMatrix);
3223 } else {
3224 getRenderEngine().setColorTransform(colorMatrix);
3225 }
David Sodmanc1498e62018-09-12 14:36:26 -07003226 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003227 break;
3228 }
3229 default:
3230 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003231 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003232 } else {
3233 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003234 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003235 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003236 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003237
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003238 // Perform some cleanup steps if we used client composition.
3239 if (hasClientComposition) {
3240 getRenderEngine().setColorTransform(mat4());
3241 getBE().mRenderEngine->disableScissor();
3242 display->finishBuffer();
3243 // Clear out error flags here so that we don't wait until next
3244 // composition to log.
3245 getRenderEngine().checkErrors();
3246 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003247 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003248}
3249
Chia-I Wu28e3a252018-09-07 12:05:02 -07003250void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003251 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003252 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003253}
3254
Dan Stoza7d89d062015-04-30 13:29:25 -07003255status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003256 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003257 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003258 const sp<Layer>& lbc,
3259 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003260{
Dan Stoza7d89d062015-04-30 13:29:25 -07003261 // add this layer to the current state list
3262 {
3263 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003264 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003265 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3266 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003267 return NO_MEMORY;
3268 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003269 if (parent == nullptr) {
3270 mCurrentState.layersSortedByZ.add(lbc);
3271 } else {
Robert Carr2e102c92018-10-23 12:11:15 -07003272 if (parent->isRemovedFromCurrentState()) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003273 ALOGE("addClientLayer called with a removed parent");
chaviw61626f22018-11-15 16:26:27 -08003274 lbc->onRemovedFromCurrentState();
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003275 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003276 parent->addChild(lbc);
3277 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003278
Yiwei Zhang243b3782018-05-15 17:40:04 -07003279 if (gbc != nullptr) {
3280 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3281 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3282 mMaxGraphicBufferProducerListSize,
3283 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3284 mGraphicBufferProducerList.size(),
3285 mMaxGraphicBufferProducerListSize, mNumLayers);
3286 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003287 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003288 }
3289
Mathias Agopian96f08192010-06-02 23:28:45 -07003290 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003291 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003292
Dan Stoza7d89d062015-04-30 13:29:25 -07003293 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003294}
3295
Robert Carr8d2711b2018-11-14 16:36:18 -08003296status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003297 Mutex::Autolock _l(mStateLock);
Robert Carr8d2711b2018-11-14 16:36:18 -08003298 return removeLayerLocked(mStateLock, layer);
chaviwca27f252018-02-06 16:46:39 -08003299}
Robert Carr7f9b8992017-03-10 11:08:39 -08003300
Robert Carr8d2711b2018-11-14 16:36:18 -08003301status_t SurfaceFlinger::removeLayerLocked(const Mutex& lock, const sp<Layer>& layer) {
chaviw5aedec92018-10-22 10:40:38 -07003302 if (layer->isLayerDetached()) {
3303 return NO_ERROR;
3304 }
3305
Robert Carr1f0a16a2016-10-24 16:27:39 -07003306 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003307 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003308 if (p != nullptr) {
Chia-I Wufae51c42017-06-15 12:53:59 -07003309 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003310 } else {
3311 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003312 }
3313
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003314 layer->onRemovedFromCurrentState();
Robert Carr2e102c92018-10-23 12:11:15 -07003315
3316 markLayerPendingRemovalLocked(lock, layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003317 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003318}
3319
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003320uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003321 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003322}
3323
Mathias Agopian3f844832013-08-07 21:24:32 -07003324uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003325 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003326}
3327
Mathias Agopian3f844832013-08-07 21:24:32 -07003328uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003329 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003330}
3331
3332uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003333 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003334 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003335 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003336 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003337 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003338 }
3339 return old;
3340}
3341
chaviwca27f252018-02-06 16:46:39 -08003342bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3343 for (const ComposerState& state : states) {
3344 // Here we need to check that the interface we're given is indeed
3345 // one of our own. A malicious client could give us a nullptr
3346 // IInterface, or one of its own or even one of our own but a
3347 // different type. All these situations would cause us to crash.
3348 if (state.client == nullptr) {
3349 return true;
3350 }
3351
3352 sp<IBinder> binder = IInterface::asBinder(state.client);
3353 if (binder == nullptr) {
3354 return true;
3355 }
3356
3357 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3358 return true;
3359 }
3360 }
3361 return false;
3362}
3363
Mathias Agopian8b33f032012-07-24 20:43:54 -07003364void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003365 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003366 const Vector<DisplayState>& displays,
3367 uint32_t flags)
3368{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003369 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003370 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003371 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003372
chaviwca27f252018-02-06 16:46:39 -08003373 if (containsAnyInvalidClientState(states)) {
3374 return;
3375 }
3376
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003377 if (flags & eAnimation) {
3378 // For window updates that are part of an animation we must wait for
3379 // previous animation "frames" to be handled.
3380 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003381 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003382 if (CC_UNLIKELY(err != NO_ERROR)) {
3383 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003384 // caller after a few seconds.
3385 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3386 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003387 mAnimTransactionPending = false;
3388 break;
3389 }
3390 }
3391 }
3392
chaviwca27f252018-02-06 16:46:39 -08003393 for (const DisplayState& display : displays) {
3394 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003395 }
3396
Marissa Walle2ffb422018-10-12 11:33:52 -07003397 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003398 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003399 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003400 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003401 // If the state doesn't require a traversal and there are callbacks, send them now
3402 if (!(clientStateFlags & eTraversalNeeded)) {
3403 mTransactionCompletedThread.sendCallbacks();
3404 }
3405 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003406
3407 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3408 // as destroyed should only occur after setting all other states. This is to allow for a
3409 // child re-parent to happen before marking its original parent as destroyed (which would
3410 // then mark the child as destroyed).
3411 for (const ComposerState& state : states) {
3412 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003413 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003414
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003415 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3416 // anyway. This can be used as a flush mechanism for previous async transactions.
3417 // Empty animation transaction can be used to simulate back-pressure, so also force a
3418 // transaction for empty animation transactions.
3419 if (transactionFlags == 0 &&
3420 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003421 transactionFlags = eTransactionNeeded;
3422 }
3423
Mathias Agopian386aa982011-11-07 21:58:03 -08003424 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003425 if (mInterceptor->isEnabled()) {
3426 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003427 }
Irvel468051e2016-06-13 16:44:44 -07003428
Mathias Agopian386aa982011-11-07 21:58:03 -08003429 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003430 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3431 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003432 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003433
3434 // if this is a synchronous transaction, wait for it to take effect
3435 // before returning.
3436 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003437 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003438 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003439 if (flags & eAnimation) {
3440 mAnimTransactionPending = true;
3441 }
3442 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003443 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3444 if (CC_UNLIKELY(err != NO_ERROR)) {
3445 // just in case something goes wrong in SF, return to the
3446 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003447 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3448 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003449 break;
3450 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003451 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003452 }
3453}
3454
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003455uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3456 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3457 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003458
Mathias Agopiane57f2922012-08-09 16:29:12 -07003459 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003460 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3461
3462 const uint32_t what = s.what;
3463 if (what & DisplayState::eSurfaceChanged) {
3464 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3465 state.surface = s.surface;
3466 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003467 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003468 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003469 if (what & DisplayState::eLayerStackChanged) {
3470 if (state.layerStack != s.layerStack) {
3471 state.layerStack = s.layerStack;
3472 flags |= eDisplayTransactionNeeded;
3473 }
3474 }
3475 if (what & DisplayState::eDisplayProjectionChanged) {
3476 if (state.orientation != s.orientation) {
3477 state.orientation = s.orientation;
3478 flags |= eDisplayTransactionNeeded;
3479 }
3480 if (state.frame != s.frame) {
3481 state.frame = s.frame;
3482 flags |= eDisplayTransactionNeeded;
3483 }
3484 if (state.viewport != s.viewport) {
3485 state.viewport = s.viewport;
3486 flags |= eDisplayTransactionNeeded;
3487 }
3488 }
3489 if (what & DisplayState::eDisplaySizeChanged) {
3490 if (state.width != s.width) {
3491 state.width = s.width;
3492 flags |= eDisplayTransactionNeeded;
3493 }
3494 if (state.height != s.height) {
3495 state.height = s.height;
3496 flags |= eDisplayTransactionNeeded;
3497 }
3498 }
3499
Mathias Agopiane57f2922012-08-09 16:29:12 -07003500 return flags;
3501}
3502
Robert Carrd4ae7f32018-06-07 16:10:57 -07003503bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3504 IPCThreadState* ipc = IPCThreadState::self();
3505 const int pid = ipc->getCallingPid();
3506 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003507 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003508 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003509 return false;
3510 }
3511 return true;
3512}
3513
chaviwca27f252018-02-06 16:46:39 -08003514uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3515 const layer_state_t& s = composerState.state;
3516 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3517
Mathias Agopian13127d82013-03-05 17:47:11 -08003518 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003519 if (layer == nullptr) {
3520 return 0;
3521 }
3522
chaviw8b3871a2017-11-01 17:41:01 -07003523 uint32_t flags = 0;
3524
Garfield Tan8a3083e2018-12-03 13:21:07 -08003525 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003526 bool geometryAppliesWithResize =
3527 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003528
3529 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3530 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003531 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003532 layer->pushPendingState();
3533 }
3534
chaviw8b3871a2017-11-01 17:41:01 -07003535 if (what & layer_state_t::ePositionChanged) {
3536 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3537 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003538 }
chaviw8b3871a2017-11-01 17:41:01 -07003539 }
3540 if (what & layer_state_t::eLayerChanged) {
3541 // NOTE: index needs to be calculated before we update the state
3542 const auto& p = layer->getParent();
3543 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003544 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003545 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003546 mCurrentState.layersSortedByZ.removeAt(idx);
3547 mCurrentState.layersSortedByZ.add(layer);
3548 // we need traversal (state changed)
3549 // AND transaction (list changed)
3550 flags |= eTransactionNeeded|eTraversalNeeded;
3551 }
chaviw8b3871a2017-11-01 17:41:01 -07003552 } else {
3553 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003554 flags |= eTransactionNeeded|eTraversalNeeded;
3555 }
3556 }
chaviw8b3871a2017-11-01 17:41:01 -07003557 }
3558 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003559 // NOTE: index needs to be calculated before we update the state
3560 const auto& p = layer->getParent();
3561 if (p == nullptr) {
3562 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3563 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3564 mCurrentState.layersSortedByZ.removeAt(idx);
3565 mCurrentState.layersSortedByZ.add(layer);
3566 // we need traversal (state changed)
3567 // AND transaction (list changed)
3568 flags |= eTransactionNeeded|eTraversalNeeded;
3569 }
3570 } else {
3571 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3572 flags |= eTransactionNeeded|eTraversalNeeded;
3573 }
chaviw8b3871a2017-11-01 17:41:01 -07003574 }
3575 }
3576 if (what & layer_state_t::eSizeChanged) {
3577 if (layer->setSize(s.w, s.h)) {
3578 flags |= eTraversalNeeded;
3579 }
3580 }
3581 if (what & layer_state_t::eAlphaChanged) {
3582 if (layer->setAlpha(s.alpha))
3583 flags |= eTraversalNeeded;
3584 }
3585 if (what & layer_state_t::eColorChanged) {
3586 if (layer->setColor(s.color))
3587 flags |= eTraversalNeeded;
3588 }
Peiyong Lind3788632018-09-18 16:01:31 -07003589 if (what & layer_state_t::eColorTransformChanged) {
3590 if (layer->setColorTransform(s.colorTransform)) {
3591 flags |= eTraversalNeeded;
3592 }
3593 }
chaviw8b3871a2017-11-01 17:41:01 -07003594 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003595 // TODO: b/109894387
3596 //
3597 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3598 // rotation. To see the problem observe that if we have a square parent, and a child
3599 // of the same size, then we rotate the child 45 degrees around it's center, the child
3600 // must now be cropped to a non rectangular 8 sided region.
3601 //
3602 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3603 // private API, and the WindowManager only uses rotation in one case, which is on a top
3604 // level layer in which cropping is not an issue.
3605 //
3606 // However given that abuse of rotation matrices could lead to surfaces extending outside
3607 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3608 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3609 // transformations.
3610 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003611 flags |= eTraversalNeeded;
3612 }
3613 if (what & layer_state_t::eTransparentRegionChanged) {
3614 if (layer->setTransparentRegionHint(s.transparentRegion))
3615 flags |= eTraversalNeeded;
3616 }
3617 if (what & layer_state_t::eFlagsChanged) {
3618 if (layer->setFlags(s.flags, s.mask))
3619 flags |= eTraversalNeeded;
3620 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003621 if (what & layer_state_t::eCropChanged_legacy) {
3622 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003623 flags |= eTraversalNeeded;
3624 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003625 if (what & layer_state_t::eCornerRadiusChanged) {
3626 if (layer->setCornerRadius(s.cornerRadius))
3627 flags |= eTraversalNeeded;
3628 }
chaviw8b3871a2017-11-01 17:41:01 -07003629 if (what & layer_state_t::eLayerStackChanged) {
3630 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3631 // We only allow setting layer stacks for top level layers,
3632 // everything else inherits layer stack from its parent.
3633 if (layer->hasParent()) {
3634 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3635 layer->getName().string());
3636 } else if (idx < 0) {
3637 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3638 "that also does not appear in the top level layer list. Something"
3639 " has gone wrong.", layer->getName().string());
3640 } else if (layer->setLayerStack(s.layerStack)) {
3641 mCurrentState.layersSortedByZ.removeAt(idx);
3642 mCurrentState.layersSortedByZ.add(layer);
3643 // we need traversal (state changed)
3644 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003645 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003646 }
3647 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003648 if (what & layer_state_t::eDeferTransaction_legacy) {
3649 if (s.barrierHandle_legacy != nullptr) {
3650 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3651 } else if (s.barrierGbp_legacy != nullptr) {
3652 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003653 if (authenticateSurfaceTextureLocked(gbp)) {
3654 const auto& otherLayer =
3655 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003656 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003657 } else {
3658 ALOGE("Attempt to defer transaction to to an"
3659 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003660 }
3661 }
chaviw8b3871a2017-11-01 17:41:01 -07003662 // We don't trigger a traversal here because if no other state is
3663 // changed, we don't want this to cause any more work
3664 }
3665 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003666 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003667 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003668 if (!hadParent) {
3669 mCurrentState.layersSortedByZ.remove(layer);
3670 }
chaviw8b3871a2017-11-01 17:41:01 -07003671 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003672 }
chaviw8b3871a2017-11-01 17:41:01 -07003673 }
3674 if (what & layer_state_t::eReparentChildren) {
3675 if (layer->reparentChildren(s.reparentHandle)) {
3676 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003677 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003678 }
chaviw8b3871a2017-11-01 17:41:01 -07003679 if (what & layer_state_t::eDetachChildren) {
3680 layer->detachChildren();
3681 }
3682 if (what & layer_state_t::eOverrideScalingModeChanged) {
3683 layer->setOverrideScalingMode(s.overrideScalingMode);
3684 // We don't trigger a traversal here because if no other state is
3685 // changed, we don't want this to cause any more work
3686 }
Marissa Wall61c58622018-07-18 10:12:20 -07003687 if (what & layer_state_t::eTransformChanged) {
3688 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3689 }
3690 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3691 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3692 flags |= eTraversalNeeded;
3693 }
3694 if (what & layer_state_t::eCropChanged) {
3695 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3696 }
Marissa Wall861616d2018-10-22 12:52:23 -07003697 if (what & layer_state_t::eFrameChanged) {
3698 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3699 }
Marissa Wall61c58622018-07-18 10:12:20 -07003700 if (what & layer_state_t::eBufferChanged) {
3701 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3702 }
3703 if (what & layer_state_t::eAcquireFenceChanged) {
3704 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3705 }
3706 if (what & layer_state_t::eDataspaceChanged) {
3707 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3708 }
3709 if (what & layer_state_t::eHdrMetadataChanged) {
3710 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3711 }
3712 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3713 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3714 }
3715 if (what & layer_state_t::eApiChanged) {
3716 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3717 }
3718 if (what & layer_state_t::eSidebandStreamChanged) {
3719 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3720 }
Robert Carr720e5062018-07-30 17:45:14 -07003721 if (what & layer_state_t::eInputInfoChanged) {
3722 layer->setInputInfo(s.inputInfo);
3723 flags |= eTraversalNeeded;
3724 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003725 std::vector<sp<CallbackHandle>> callbackHandles;
3726 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3727 mTransactionCompletedThread.run();
3728 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3729 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3730 }
3731 }
3732 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3733 // Do not put anything that updates layer state or modifies flags after
3734 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003735 return flags;
3736}
3737
chaviwca27f252018-02-06 16:46:39 -08003738void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3739 const layer_state_t& state = composerState.state;
3740 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3741
3742 sp<Layer> layer(client->getLayerUser(state.surface));
3743 if (layer == nullptr) {
3744 return;
3745 }
3746
chaviwca27f252018-02-06 16:46:39 -08003747 if (state.what & layer_state_t::eDestroySurface) {
3748 removeLayerLocked(mStateLock, layer);
3749 }
3750}
3751
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003752status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003753 const String8& name,
3754 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003755 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003756 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003757 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003758{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003759 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003760 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003761 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003762 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003763 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003764
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003765 status_t result = NO_ERROR;
3766
3767 sp<Layer> layer;
3768
Cody Northropbc755282017-03-31 12:00:08 -06003769 String8 uniqueName = getUniqueLayerName(name);
3770
Mathias Agopian3165cc22012-08-08 19:42:09 -07003771 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003772 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003773 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3774 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003775
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003776 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003777 case ISurfaceComposerClient::eFXSurfaceBufferState:
3778 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3779 break;
chaviw13fdc492017-06-27 12:40:18 -07003780 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003781 // check if buffer size is set for color layer.
3782 if (w > 0 || h > 0) {
3783 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3784 int(w), int(h));
3785 return BAD_VALUE;
3786 }
3787
chaviw13fdc492017-06-27 12:40:18 -07003788 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003789 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003790 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003791 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003792 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003793 // check if buffer size is set for container layer.
3794 if (w > 0 || h > 0) {
3795 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3796 int(w), int(h));
3797 return BAD_VALUE;
3798 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07003799 result = createContainerLayer(client,
3800 uniqueName, w, h, flags,
3801 handle, &layer);
3802 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003803 default:
3804 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003805 break;
3806 }
3807
Dan Stoza7d89d062015-04-30 13:29:25 -07003808 if (result != NO_ERROR) {
3809 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003810 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003811
Chia-I Wuab0c3192017-08-01 11:29:00 -07003812 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3813 // TODO b/64227542
3814 if (windowType == 441731) {
3815 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3816 layer->setPrimaryDisplayOnly();
3817 }
3818
Albert Chaulk479c60c2017-01-27 14:21:34 -05003819 layer->setInfo(windowType, ownerUid);
3820
Robert Carr1f0a16a2016-10-24 16:27:39 -07003821 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003822 if (result != NO_ERROR) {
3823 return result;
3824 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003825 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003826
3827 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003828 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003829}
3830
Cody Northropbc755282017-03-31 12:00:08 -06003831String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3832{
3833 bool matchFound = true;
3834 uint32_t dupeCounter = 0;
3835
3836 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3837 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3838
Dan Stoza436ccf32018-06-21 12:10:12 -07003839 // Grab the state lock since we're accessing mCurrentState
3840 Mutex::Autolock lock(mStateLock);
3841
Cody Northropbc755282017-03-31 12:00:08 -06003842 // Loop over layers until we're sure there is no matching name
3843 while (matchFound) {
3844 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003845 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003846 if (layer->getName() == uniqueName) {
3847 matchFound = true;
3848 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3849 }
3850 });
3851 }
3852
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003853 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3854 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003855
3856 return uniqueName;
3857}
3858
Marissa Wallfd668622018-05-10 10:21:13 -07003859status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3860 uint32_t w, uint32_t h, uint32_t flags,
3861 PixelFormat& format, sp<IBinder>* handle,
3862 sp<IGraphicBufferProducer>* gbp,
3863 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003864 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003865 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003866 case PIXEL_FORMAT_TRANSPARENT:
3867 case PIXEL_FORMAT_TRANSLUCENT:
3868 format = PIXEL_FORMAT_RGBA_8888;
3869 break;
3870 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003871 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003872 break;
3873 }
3874
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003875 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003876 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003877 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003878 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003879 *handle = layer->getHandle();
3880 *gbp = layer->getProducer();
3881 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003882 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003883
Marissa Wallfd668622018-05-10 10:21:13 -07003884 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003885 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003886}
3887
Marissa Wall61c58622018-07-18 10:12:20 -07003888status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3889 uint32_t w, uint32_t h, uint32_t flags,
3890 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003891 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003892 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003893 *handle = layer->getHandle();
3894 *outLayer = layer;
3895
3896 return NO_ERROR;
3897}
3898
chaviw13fdc492017-06-27 12:40:18 -07003899status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003900 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003901 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003902{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003903 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003904 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003905 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003906}
3907
Robert Carr6b3f6c52018-08-13 13:05:17 -07003908status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3909 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3910 sp<IBinder>* handle, sp<Layer>* outLayer)
3911{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003912 *outLayer =
3913 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003914 *handle = (*outLayer)->getHandle();
3915 return NO_ERROR;
3916}
3917
3918
Mathias Agopianac9fa422013-02-11 16:40:36 -08003919status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003920{
Robert Carr9524cb32017-02-13 11:32:32 -08003921 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003922 status_t err = NO_ERROR;
3923 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003924 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003925 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003926 err = removeLayer(l);
3927 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3928 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003929 }
3930 return err;
3931}
3932
Robert Carr2e102c92018-10-23 12:11:15 -07003933void SurfaceFlinger::markLayerPendingRemovalLocked(const Mutex&, const sp<Layer>& layer) {
3934 mLayersPendingRemoval.add(layer);
3935 mLayersRemoved = true;
3936 setTransactionFlags(eTransactionNeeded);
3937}
3938
3939void SurfaceFlinger::onHandleDestroyed(const sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003940{
Robert Carr2e102c92018-10-23 12:11:15 -07003941 Mutex::Autolock lock(mStateLock);
3942 markLayerPendingRemovalLocked(mStateLock, layer);
Rob Carr4bba3702018-10-08 21:53:30 +00003943}
3944
Mathias Agopianb60314a2012-04-10 22:09:54 -07003945// ---------------------------------------------------------------------------
3946
Andy McFadden13a082e2012-08-24 10:16:42 -07003947void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003948 const auto displayToken = getInternalDisplayToken();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003949 if (!displayToken) return;
3950
Jesse Hall01e29052013-02-19 16:13:35 -08003951 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003952 Vector<ComposerState> state;
3953 Vector<DisplayState> displays;
3954 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003955 d.what = DisplayState::eDisplayProjectionChanged |
3956 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003957 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003958 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003959 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003960 d.frame.makeInvalid();
3961 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003962 d.width = 0;
3963 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003964 displays.add(d);
3965 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003966
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003967 const auto display = getDisplayDevice(displayToken);
3968 if (!display) return;
3969
3970 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3971
Dominik Laskowski075d3172018-05-24 15:50:06 -07003972 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003973 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003974 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003975
Brian Andersond0010582017-03-07 13:20:31 -08003976 // Use phase of 0 since phase is not known.
3977 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07003978 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
3979 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003980}
3981
3982void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003983 // Async since we may be called from the main thread.
3984 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003985}
3986
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003987void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3988 bool stateLockHeld) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003989 if (display->isVirtual()) {
3990 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003991 return;
3992 }
3993
Dominik Laskowski075d3172018-05-24 15:50:06 -07003994 const auto displayId = display->getId();
3995 LOG_ALWAYS_FATAL_IF(!displayId);
3996
Dominik Laskowski34157762018-10-31 13:07:19 -07003997 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003998
3999 int currentMode = display->getPowerMode();
4000 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004001 return;
4002 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004003
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004004 display->setPowerMode(mode);
4005
Lloyd Pique4dccc412018-01-22 17:21:36 -08004006 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07004007 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004008 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07004009 if (idx < 0) {
4010 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
4011 return;
4012 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07004013 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07004014 }
4015
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004016 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004017 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004018 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004019 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004020 if (mUseScheduler) {
4021 mScheduler->onScreenAcquired(mAppConnectionHandle);
4022 } else {
4023 mEventThread->onScreenAcquired();
4024 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004025 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004026 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004027
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004028 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004029 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004030 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004031
4032 struct sched_param param = {0};
4033 param.sched_priority = 1;
4034 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4035 ALOGW("Couldn't set SCHED_FIFO on display on");
4036 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004037 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004038 // Turn off the display
4039 struct sched_param param = {0};
4040 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4041 ALOGW("Couldn't set SCHED_OTHER on display off");
4042 }
4043
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004044 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004045 if (mUseScheduler) {
4046 mScheduler->disableHardwareVsync(true);
4047 } else {
4048 disableHardwareVsync(true); // also cancels any in-progress resync
4049 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004050 if (mUseScheduler) {
4051 mScheduler->onScreenReleased(mAppConnectionHandle);
4052 } else {
4053 mEventThread->onScreenReleased();
4054 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004055 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004056
Dominik Laskowski075d3172018-05-24 15:50:06 -07004057 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004058 mVisibleRegionsDirty = true;
4059 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004060 } else if (mode == HWC_POWER_MODE_DOZE ||
4061 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004062 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004063 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004064 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004065 if (mUseScheduler) {
4066 mScheduler->onScreenAcquired(mAppConnectionHandle);
4067 } else {
4068 mEventThread->onScreenAcquired();
4069 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004070 resyncToHardwareVsync(true);
4071 }
4072 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4073 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004074 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004075 if (mUseScheduler) {
4076 mScheduler->disableHardwareVsync(true);
4077 } else {
4078 disableHardwareVsync(true); // also cancels any in-progress resync
4079 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004080 if (mUseScheduler) {
4081 mScheduler->onScreenReleased(mAppConnectionHandle);
4082 } else {
4083 mEventThread->onScreenReleased();
4084 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004085 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004086 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004087 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004088 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004089 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004090 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004091
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004092 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004093 mTimeStats->setPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004094 }
4095
Dominik Laskowski34157762018-10-31 13:07:19 -07004096 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004097}
4098
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004099void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004100 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004101 const auto display = getDisplayDevice(displayToken);
4102 if (!display) {
4103 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4104 displayToken.get());
4105 } else if (display->isVirtual()) {
4106 ALOGW("Attempt to set power mode %d for virtual display", mode);
4107 } else {
4108 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004109 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004110 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004111}
4112
4113// ---------------------------------------------------------------------------
4114
Lloyd Pique755e3192018-01-31 16:46:15 -08004115status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4116 NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004117 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004118
Mathias Agopianbd115332013-04-18 16:41:04 -07004119 IPCThreadState* ipc = IPCThreadState::self();
4120 const int pid = ipc->getCallingPid();
4121 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004122
Mathias Agopianbd115332013-04-18 16:41:04 -07004123 if ((uid != AID_SHELL) &&
4124 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004125 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4126 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004127 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004128 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004129 // (this would indicate SF is stuck, but we want to be able to
4130 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004131 status_t err = mStateLock.timedLock(s2ns(1));
4132 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004133 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004134 StringAppendF(&result,
4135 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4136 "(no locks held)\n",
4137 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004138 }
4139
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004140 bool dumpAll = true;
4141 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004142 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004143
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004144 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004145 if ((index < numArgs) &&
4146 (args[index] == String16("--list"))) {
4147 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004148 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004149 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004150 }
4151
4152 if ((index < numArgs) &&
4153 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004154 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004155 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004156 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004157 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004158
4159 if ((index < numArgs) &&
4160 (args[index] == String16("--latency-clear"))) {
4161 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004162 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004163 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004164 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004165
4166 if ((index < numArgs) &&
4167 (args[index] == String16("--dispsync"))) {
4168 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004169 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004170 dumpAll = false;
4171 }
Dan Stozab90cf072015-03-05 11:05:59 -08004172
4173 if ((index < numArgs) &&
4174 (args[index] == String16("--static-screen"))) {
4175 index++;
4176 dumpStaticScreenStats(result);
4177 dumpAll = false;
4178 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004179
4180 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004181 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004182 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004183 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004184 dumpAll = false;
4185 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004186
4187 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4188 index++;
4189 dumpWideColorInfo(result);
4190 dumpAll = false;
4191 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004192
4193 if ((index < numArgs) &&
4194 (args[index] == String16("--enable-layer-stats"))) {
4195 index++;
4196 mLayerStats.enable();
4197 dumpAll = false;
4198 }
4199
4200 if ((index < numArgs) &&
4201 (args[index] == String16("--disable-layer-stats"))) {
4202 index++;
4203 mLayerStats.disable();
4204 dumpAll = false;
4205 }
4206
4207 if ((index < numArgs) &&
4208 (args[index] == String16("--clear-layer-stats"))) {
4209 index++;
4210 mLayerStats.clear();
4211 dumpAll = false;
4212 }
4213
4214 if ((index < numArgs) &&
4215 (args[index] == String16("--dump-layer-stats"))) {
4216 index++;
4217 mLayerStats.dump(result);
4218 dumpAll = false;
4219 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004220
4221 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004222 (args[index] == String16("--frame-composition"))) {
4223 index++;
4224 dumpFrameCompositionInfo(result);
4225 dumpAll = false;
4226 }
4227
4228 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004229 (args[index] == String16("--display-identification"))) {
4230 index++;
4231 dumpDisplayIdentificationData(result);
4232 dumpAll = false;
4233 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004234
4235 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4236 index++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004237 mTimeStats->parseArgs(asProto, args, index, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004238 dumpAll = false;
4239 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004240 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004241
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004242 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004243 if (asProto) {
4244 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4245 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4246 } else {
4247 dumpAllLocked(args, index, result);
4248 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004249 }
4250
Mathias Agopian9795c422009-08-26 16:36:26 -07004251 if (locked) {
4252 mStateLock.unlock();
4253 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004254 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004255 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004256 return NO_ERROR;
4257}
4258
Yiwei Zhang5434a782018-12-05 18:06:32 -08004259void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */, size_t& /* index */,
4260 std::string& result) const {
4261 mCurrentState.traverseInZOrder(
4262 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004263}
4264
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004265void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004266 std::string& result) const {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004267 String8 name;
4268 if (index < args.size()) {
4269 name = String8(args[index]);
4270 index++;
4271 }
4272
Dominik Laskowski075d3172018-05-24 15:50:06 -07004273 if (const auto displayId = getInternalDisplayId();
4274 displayId && getHwComposer().isConnected(*displayId)) {
4275 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004276 const nsecs_t period = activeConfig->getVsyncPeriod();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004277 StringAppendF(&result, "%" PRId64 "\n", period);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004278 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004279
4280 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004281 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004282 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004283 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004284 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004285 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004286 }
Robert Carr2047fae2016-11-28 14:09:09 -08004287 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004288 }
4289}
4290
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004291void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004292 std::string& /* result */) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004293 String8 name;
4294 if (index < args.size()) {
4295 name = String8(args[index]);
4296 index++;
4297 }
4298
Robert Carr2047fae2016-11-28 14:09:09 -08004299 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004300 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004301 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004302 }
Robert Carr2047fae2016-11-28 14:09:09 -08004303 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004304
Svetoslavd85084b2014-03-20 10:28:31 -07004305 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004306}
4307
Jamie Gennis6547ff42013-07-16 20:12:42 -07004308// This should only be called from the main thread. Otherwise it would need
4309// the lock and should use mCurrentState rather than mDrawingState.
4310void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004311 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004312 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004313 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004314
4315 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4316}
4317
Yiwei Zhang5434a782018-12-05 18:06:32 -08004318void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004319 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004320
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004321 if (isLayerTripleBufferingDisabled())
4322 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004323
Yiwei Zhang5434a782018-12-05 18:06:32 -08004324 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4325 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4326 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4327 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4328 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4329 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004330 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004331}
4332
Yiwei Zhang5434a782018-12-05 18:06:32 -08004333void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4334 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004335 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4336 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004337 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004338 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004339 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004340 }
David Sodman4a36e932017-11-07 14:29:47 -08004341 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004342 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004343 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004344 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4345 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004346}
4347
Dan Stozae77c7662016-05-13 11:37:28 -07004348void SurfaceFlinger::recordBufferingStats(const char* layerName,
4349 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004350 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4351 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004352 for (const auto& segment : history) {
4353 if (!segment.usedThirdBuffer) {
4354 stats.twoBufferTime += segment.totalTime;
4355 }
4356 if (segment.occupancyAverage < 1.0f) {
4357 stats.doubleBufferedTime += segment.totalTime;
4358 } else if (segment.occupancyAverage < 2.0f) {
4359 stats.tripleBufferedTime += segment.totalTime;
4360 }
4361 ++stats.numSegments;
4362 stats.totalTime += segment.totalTime;
4363 }
4364}
4365
Yiwei Zhang5434a782018-12-05 18:06:32 -08004366void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4367 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004368
4369 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4370 const size_t count = currentLayers.size();
4371 for (size_t i=0 ; i<count ; i++) {
4372 currentLayers[i]->dumpFrameEvents(result);
4373 }
4374}
4375
Yiwei Zhang5434a782018-12-05 18:06:32 -08004376void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004377 result.append("Buffering stats:\n");
4378 result.append(" [Layer name] <Active time> <Two buffer> "
4379 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004380 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004381 typedef std::tuple<std::string, float, float, float> BufferTuple;
4382 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004383 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004384 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004385 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004386 if (stats.numSegments == 0) {
4387 continue;
4388 }
4389 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4390 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4391 stats.totalTime;
4392 float doubleBufferRatio = static_cast<float>(
4393 stats.doubleBufferedTime) / stats.totalTime;
4394 float tripleBufferRatio = static_cast<float>(
4395 stats.tripleBufferedTime) / stats.totalTime;
4396 sorted.insert({activeTime, {name, twoBufferRatio,
4397 doubleBufferRatio, tripleBufferRatio}});
4398 }
4399 for (const auto& sortedPair : sorted) {
4400 float activeTime = sortedPair.first;
4401 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004402 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4403 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004404 }
4405 result.append("\n");
4406}
4407
Yiwei Zhang5434a782018-12-05 18:06:32 -08004408void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004409 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004410 const auto displayId = display->getId();
4411 if (!displayId) {
4412 continue;
4413 }
4414 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004415 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004416 continue;
4417 }
4418
Yiwei Zhang5434a782018-12-05 18:06:32 -08004419 StringAppendF(&result,
4420 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4421 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004422 uint8_t port;
4423 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004424 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004425 result.append("no identification data\n");
4426 continue;
4427 }
4428
4429 if (!isEdid(data)) {
4430 result.append("unknown identification data: ");
4431 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004432 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004433 }
4434 result.append("\n");
4435 continue;
4436 }
4437
4438 const auto edid = parseEdid(data);
4439 if (!edid) {
4440 result.append("invalid EDID: ");
4441 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004442 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004443 }
4444 result.append("\n");
4445 continue;
4446 }
4447
Yiwei Zhang5434a782018-12-05 18:06:32 -08004448 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004449 result.append(edid->displayName.data(), edid->displayName.length());
4450 result.append("\"\n");
4451 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004452}
4453
Yiwei Zhang5434a782018-12-05 18:06:32 -08004454void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4455 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4456 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4457 StringAppendF(&result, "DisplayColorSetting: %s\n",
4458 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004459
4460 // TODO: print out if wide-color mode is active or not
4461
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004462 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004463 const auto displayId = display->getId();
4464 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004465 continue;
4466 }
4467
Yiwei Zhang5434a782018-12-05 18:06:32 -08004468 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004469 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004470 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004471 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004472 }
4473
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004474 ColorMode currentMode = display->getActiveColorMode();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004475 StringAppendF(&result, " Current color mode: %s (%d)\n",
4476 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004477 }
4478 result.append("\n");
4479}
4480
Yiwei Zhang5434a782018-12-05 18:06:32 -08004481void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004482 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004483 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4484 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004485 continue;
4486 }
4487
Dominik Laskowski05275f12018-11-01 15:03:24 -07004488 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004489 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4490 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004491 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004492 compositionInfo.dump(result, nullptr);
4493 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004494 }
4495 }
David Sodman7e4ae112018-02-09 15:02:28 -08004496}
4497
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004498LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004499 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004500 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4501 const State& state = useDrawing ? mDrawingState : mCurrentState;
4502 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004503 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004504 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004505 });
4506
4507 return layersProto;
4508}
4509
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004510LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004511 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004512
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004513 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004514 resolution->set_w(display.getWidth());
4515 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004516
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004517 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4518 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4519 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004520
Dominik Laskowski075d3172018-05-24 15:50:06 -07004521 const auto displayId = display.getId();
4522 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004523 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004524 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004525 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004526 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004527 }
4528 });
4529
4530 return layersProto;
4531}
4532
Mathias Agopian74d211a2013-04-22 16:55:35 +02004533void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004534 std::string& result) const {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004535 bool colorize = false;
4536 if (index < args.size()
4537 && (args[index] == String16("--color"))) {
4538 colorize = true;
4539 index++;
4540 }
4541
4542 Colorizer colorizer(colorize);
4543
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004544 // figure out if we're stuck somewhere
4545 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004546 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004547 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4548
4549 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004550 * Dump library configuration.
4551 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004552
4553 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004554 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004555 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004556 appendSfConfigString(result);
4557 appendUiConfigString(result);
4558 appendGuiConfigString(result);
4559 result.append("\n");
4560
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004561 result.append("\nDisplay identification data:\n");
4562 dumpDisplayIdentificationData(result);
4563
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004564 result.append("\nWide-Color information:\n");
4565 dumpWideColorInfo(result);
4566
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004567 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004568 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004569 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004570 result.append(SyncFeatures::getInstance().toString());
4571 result.append("\n");
4572
Andy McFadden41d67d72014-04-25 16:58:34 -07004573 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004574 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004575 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004576
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004577 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4578 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004579 if (const auto displayId = getInternalDisplayId();
4580 displayId && getHwComposer().isConnected(*displayId)) {
4581 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004582 StringAppendF(&result,
4583 "Display %s: app phase %" PRId64 " ns, "
4584 "sf phase %" PRId64 " ns, "
4585 "early app phase %" PRId64 " ns, "
4586 "early sf phase %" PRId64 " ns, "
4587 "early app gl phase %" PRId64 " ns, "
4588 "early sf gl phase %" PRId64 " ns, "
4589 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4590 to_string(*displayId).c_str(), vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
4591 appEarlyOffset, sfEarlyOffset, appEarlyGlOffset, sfEarlyGlOffset,
4592 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004593 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004594 result.append("\n");
4595
Dan Stozab90cf072015-03-05 11:05:59 -08004596 // Dump static screen stats
4597 result.append("\n");
4598 dumpStaticScreenStats(result);
4599 result.append("\n");
4600
Yiwei Zhang5434a782018-12-05 18:06:32 -08004601 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004602
Dan Stozae77c7662016-05-13 11:37:28 -07004603 dumpBufferingStats(result);
4604
Andy McFadden4803b742012-09-24 19:07:20 -07004605 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004606 * Dump the visible layer list
4607 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004608 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004609 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4610 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4611 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004612 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004613
Chia-I Wu2f884132018-09-13 15:17:58 -07004614 {
4615 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4616 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004617 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004618 result.append("\n");
4619 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004620
David Sodman7e4ae112018-02-09 15:02:28 -08004621 result.append("\nFrame-Composition information:\n");
4622 dumpFrameCompositionInfo(result);
4623 result.append("\n");
4624
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004625 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004626 * Dump Display state
4627 */
4628
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004629 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004630 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004631 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004632 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004633 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004634 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004635 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004636
4637 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004638 * Dump SurfaceFlinger global state
4639 */
4640
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004641 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004642 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004643 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004644
David Sodmanbc815282017-11-05 18:57:52 -08004645 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004646
Dominik Laskowski075d3172018-05-24 15:50:06 -07004647 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004648 display->undefinedRegion.dump(result, "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004649 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4650 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004651 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004652 StringAppendF(&result,
4653 " transaction-flags : %08x\n"
4654 " gpu_to_cpu_unsupported : %d\n",
4655 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004656
Dominik Laskowski075d3172018-05-24 15:50:06 -07004657 if (const auto displayId = getInternalDisplayId();
4658 displayId && getHwComposer().isConnected(*displayId)) {
4659 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004660 StringAppendF(&result,
4661 " refresh-rate : %f fps\n"
4662 " x-dpi : %f\n"
4663 " y-dpi : %f\n",
4664 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4665 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004666 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004667
Yiwei Zhang5434a782018-12-05 18:06:32 -08004668 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004669
Yiwei Zhang5434a782018-12-05 18:06:32 -08004670 StringAppendF(&result, " use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004671 /*
4672 * VSYNC state
4673 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004674 if (mUseScheduler) {
4675 mScheduler->dump(mAppConnectionHandle, result);
4676 } else {
4677 mEventThread->dump(result);
4678 }
Dan Stozae22aec72016-08-01 13:20:59 -07004679 result.append("\n");
4680
4681 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004682 * Tracing state
4683 */
4684 mTracing.dump(result);
4685 result.append("\n");
4686
4687 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004688 * HWC layer minidump
4689 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004690 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004691 const auto displayId = display->getId();
4692 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004693 continue;
4694 }
4695
Yiwei Zhang5434a782018-12-05 18:06:32 -08004696 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004697 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004698 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004699 result.append("\n");
4700 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004701
4702 /*
4703 * Dump HWComposer state
4704 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004705 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004706 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004707 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004708 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004709 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004710 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004711
4712 /*
4713 * Dump gralloc state
4714 */
4715 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4716 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004717
4718 /*
4719 * Dump VrFlinger state if in use.
4720 */
4721 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4722 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004723 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004724 result.append("\n");
4725 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004726}
4727
Dominik Laskowski075d3172018-05-24 15:50:06 -07004728const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004729 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004730 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004731 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004732 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004733 }
4734 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004735
Dominik Laskowski34157762018-10-31 13:07:19 -07004736 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004737 static const Vector<sp<Layer>> empty;
4738 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004739}
4740
Keun young Park63f165f2012-08-31 10:53:36 -07004741bool SurfaceFlinger::startDdmConnection()
4742{
4743 void* libddmconnection_dso =
4744 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4745 if (!libddmconnection_dso) {
4746 return false;
4747 }
4748 void (*DdmConnection_start)(const char* name);
4749 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004750 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004751 if (!DdmConnection_start) {
4752 dlclose(libddmconnection_dso);
4753 return false;
4754 }
4755 (*DdmConnection_start)(getServiceName());
4756 return true;
4757}
4758
Chia-I Wu28f320b2018-05-03 11:02:56 -07004759void SurfaceFlinger::updateColorMatrixLocked() {
4760 mat4 colorMatrix;
4761 if (mGlobalSaturationFactor != 1.0f) {
4762 // Rec.709 luma coefficients
4763 float3 luminance{0.213f, 0.715f, 0.072f};
4764 luminance *= 1.0f - mGlobalSaturationFactor;
4765 mat4 saturationMatrix = mat4(
4766 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4767 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4768 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4769 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4770 );
4771 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4772 } else {
4773 colorMatrix = mClientColorMatrix * mDaltonizer();
4774 }
4775
4776 if (mCurrentState.colorMatrix != colorMatrix) {
4777 mCurrentState.colorMatrix = colorMatrix;
4778 mCurrentState.colorMatrixChanged = true;
4779 setTransactionFlags(eTransactionNeeded);
4780 }
4781}
4782
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004783status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004784#pragma clang diagnostic push
4785#pragma clang diagnostic error "-Wswitch-enum"
4786 switch (static_cast<ISurfaceComposerTag>(code)) {
4787 // These methods should at minimum make sure that the client requested
4788 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004789 case BOOT_FINISHED:
4790 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004791 case CREATE_CONNECTION:
4792 case CREATE_DISPLAY:
4793 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004794 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004795 case GET_ACTIVE_COLOR_MODE:
4796 case GET_ANIMATION_FRAME_STATS:
4797 case GET_HDR_CAPABILITIES:
4798 case SET_ACTIVE_CONFIG:
4799 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004800 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004801 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004802 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004803 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4804 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004805 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4806 IPCThreadState* ipc = IPCThreadState::self();
4807 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4808 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004809 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004810 }
Robert Carr1db73f62016-12-21 12:58:51 -08004811 return OK;
4812 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004813 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004814 IPCThreadState* ipc = IPCThreadState::self();
4815 const int pid = ipc->getCallingPid();
4816 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004817 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4818 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004819 return PERMISSION_DENIED;
4820 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004821 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004822 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004823 // Used by apps to hook Choreographer to SurfaceFlinger.
4824 case CREATE_DISPLAY_EVENT_CONNECTION:
4825 // The following calls are currently used by clients that do not
4826 // request necessary permissions. However, they do not expose any secret
4827 // information, so it is OK to pass them.
4828 case AUTHENTICATE_SURFACE:
4829 case GET_ACTIVE_CONFIG:
4830 case GET_BUILT_IN_DISPLAY:
4831 case GET_DISPLAY_COLOR_MODES:
4832 case GET_DISPLAY_CONFIGS:
4833 case GET_DISPLAY_STATS:
4834 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4835 // Calling setTransactionState is safe, because you need to have been
4836 // granted a reference to Client* and Handle* to do anything with it.
4837 case SET_TRANSACTION_STATE:
4838 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004839 case CREATE_SCOPED_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004840 case GET_COLOR_MANAGEMENT:
Peiyong Lin0256f722018-08-31 15:45:10 -07004841 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004842 return OK;
4843 }
4844 case CAPTURE_LAYERS:
4845 case CAPTURE_SCREEN: {
4846 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004847 IPCThreadState* ipc = IPCThreadState::self();
4848 const int pid = ipc->getCallingPid();
4849 const int uid = ipc->getCallingUid();
4850 if ((uid != AID_GRAPHICS) &&
4851 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4852 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4853 return PERMISSION_DENIED;
4854 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004855 return OK;
4856 }
4857 // The following codes are deprecated and should never be allowed to access SF.
4858 case CONNECT_DISPLAY_UNUSED:
4859 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4860 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4861 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004862 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004863 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004864
4865 // These codes are used for the IBinder protocol to either interrogate the recipient
4866 // side of the transaction for its canonical interface descriptor or to dump its state.
4867 // We let them pass by default.
4868 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4869 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4870 code == IBinder::SYSPROPS_TRANSACTION) {
4871 return OK;
4872 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004873 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004874 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004875 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004876 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4877 return OK;
4878 }
4879 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4880 return PERMISSION_DENIED;
4881#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004882}
4883
Ana Krulec13be8ad2018-08-21 02:43:56 +00004884status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4885 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004886 status_t credentialCheck = CheckTransactCodeCredentials(code);
4887 if (credentialCheck != OK) {
4888 return credentialCheck;
4889 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004890
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004891 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4892 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004893 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004894 IPCThreadState* ipc = IPCThreadState::self();
4895 const int uid = ipc->getCallingUid();
4896 if (CC_UNLIKELY(uid != AID_SYSTEM
4897 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004898 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004899 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004900 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004901 return PERMISSION_DENIED;
4902 }
4903 int n;
4904 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004905 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004906 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004907 return NO_ERROR;
4908 case 1002: // SHOW_UPDATES
4909 n = data.readInt32();
4910 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004911 invalidateHwcGeometry();
4912 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004913 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004914 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004915 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004916 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004917 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004918 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004919 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004920 setTransactionFlags(
4921 eTransactionNeeded|
4922 eDisplayTransactionNeeded|
4923 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004924 return NO_ERROR;
4925 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004926 case 1006:{ // send empty update
4927 signalRefresh();
4928 return NO_ERROR;
4929 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004930 case 1008: // toggle use of hw composer
4931 n = data.readInt32();
4932 mDebugDisableHWC = n ? 1 : 0;
4933 invalidateHwcGeometry();
4934 repaintEverything();
4935 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004936 case 1009: // toggle use of transform hint
4937 n = data.readInt32();
4938 mDebugDisableTransformHint = n ? 1 : 0;
4939 invalidateHwcGeometry();
4940 repaintEverything();
4941 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004942 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004943 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004944 reply->writeInt32(0);
4945 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004946 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004947 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004948 return NO_ERROR;
4949 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004950 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004951 if (!display) {
4952 return NAME_NOT_FOUND;
4953 }
4954
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004955 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004956 return NO_ERROR;
4957 }
4958 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004959 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004960 // daltonize
4961 n = data.readInt32();
4962 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004963 case 1:
4964 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4965 break;
4966 case 2:
4967 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4968 break;
4969 case 3:
4970 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4971 break;
4972 default:
4973 mDaltonizer.setType(ColorBlindnessType::None);
4974 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004975 }
4976 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004977 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004978 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004979 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004980 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004981
4982 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004983 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004984 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004985 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004986 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004987 // apply a color matrix
4988 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004989 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004990 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004991 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004992 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004993 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004994 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004995 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004996 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004997 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004998 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004999
5000 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5001 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005002 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005003 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5004 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5005 }
5006
Chia-I Wu28f320b2018-05-03 11:02:56 -07005007 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005008 return NO_ERROR;
5009 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005010 // This is an experimental interface
5011 // Needs to be shifted to proper binder interface when we productize
5012 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005013 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005014 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005015 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005016 return NO_ERROR;
5017 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005018 case 1017: {
5019 n = data.readInt32();
5020 mForceFullDamage = static_cast<bool>(n);
5021 return NO_ERROR;
5022 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005023 case 1018: { // Modify Choreographer's phase offset
5024 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005025 if (mUseScheduler) {
5026 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5027 } else {
5028 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5029 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005030 return NO_ERROR;
5031 }
5032 case 1019: { // Modify SurfaceFlinger's phase offset
5033 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005034 if (mUseScheduler) {
5035 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5036 } else {
5037 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5038 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005039 return NO_ERROR;
5040 }
Irvel468051e2016-06-13 16:44:44 -07005041 case 1020: { // Layer updates interceptor
5042 n = data.readInt32();
5043 if (n) {
5044 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005045 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005046 }
5047 else{
5048 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005049 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005050 }
5051 return NO_ERROR;
5052 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005053 case 1021: { // Disable HWC virtual displays
5054 n = data.readInt32();
5055 mUseHwcVirtualDisplays = !n;
5056 return NO_ERROR;
5057 }
Romain Guy0147a172017-06-01 13:53:56 -07005058 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005059 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005060 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005061
Chia-I Wu28f320b2018-05-03 11:02:56 -07005062 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005063 return NO_ERROR;
5064 }
Romain Guy54f154a2017-10-24 21:40:32 +01005065 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005066 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005067 invalidateHwcGeometry();
5068 repaintEverything();
5069 return NO_ERROR;
5070 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005071 // Deprecate, use 1030 to check whether the device is color managed.
5072 case 1024: {
5073 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005074 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005075 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005076 n = data.readInt32();
5077 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005078 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005079 mTracing.enable();
5080 doTracing("tracing.enable");
5081 reply->writeInt32(NO_ERROR);
5082 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005083 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005084 status_t err = mTracing.disable();
5085 reply->writeInt32(err);
5086 }
5087 return NO_ERROR;
5088 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005089 case 1026: { // Get layer tracing status
5090 reply->writeBool(mTracing.isEnabled());
5091 return NO_ERROR;
5092 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005093 // Is a DisplayColorSetting supported?
5094 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005095 const auto display = getDefaultDisplayDevice();
5096 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005097 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005098 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005099
5100 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5101 switch (setting) {
5102 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005103 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005104 break;
5105 case DisplayColorSetting::UNMANAGED:
5106 reply->writeBool(true);
5107 break;
5108 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005109 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005110 break;
5111 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005112 reply->writeBool(
5113 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005114 break;
5115 }
5116 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005117 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005118 // Is VrFlinger active?
5119 case 1028: {
5120 Mutex::Autolock _l(mStateLock);
5121 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5122 return NO_ERROR;
5123 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005124 // Is device color managed?
5125 case 1030: {
5126 reply->writeBool(useColorManagement);
5127 return NO_ERROR;
5128 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005129 // Override default composition data space
5130 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5131 // && adb shell stop zygote && adb shell start zygote
5132 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5133 // adb shell stop zygote && adb shell start zygote
5134 case 1031: {
5135 Mutex::Autolock _l(mStateLock);
5136 n = data.readInt32();
5137 if (n) {
5138 n = data.readInt32();
5139 if (n) {
5140 Dataspace dataspace = static_cast<Dataspace>(n);
5141 if (!validateCompositionDataspace(dataspace)) {
5142 return BAD_VALUE;
5143 }
5144 mDefaultCompositionDataspace = dataspace;
5145 }
5146 n = data.readInt32();
5147 if (n) {
5148 Dataspace dataspace = static_cast<Dataspace>(n);
5149 if (!validateCompositionDataspace(dataspace)) {
5150 return BAD_VALUE;
5151 }
5152 mWideColorGamutCompositionDataspace = dataspace;
5153 }
5154 } else {
5155 // restore composition data space.
5156 mDefaultCompositionDataspace = defaultCompositionDataspace;
5157 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5158 }
5159 return NO_ERROR;
5160 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005161 }
5162 }
5163 return err;
5164}
5165
Steven Thomas6d8110b2017-08-31 18:24:21 -07005166void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005167 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005168 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005169}
5170
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005171// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5172class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005173public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005174 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5175 ~WindowDisconnector() {
5176 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005177 }
5178
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005179private:
5180 ANativeWindow* mWindow;
5181 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005182};
5183
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005184status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005185 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5186 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005187 uint32_t reqWidth, uint32_t reqHeight,
5188 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005189 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005190 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005191
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005192 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005193
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005194 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5195
Chia-I Wu20261cb2018-08-23 12:55:44 -07005196 sp<DisplayDevice> display;
5197 {
5198 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005199
Chia-I Wu20261cb2018-08-23 12:55:44 -07005200 display = getDisplayDeviceLocked(displayToken);
5201 if (!display) return BAD_VALUE;
5202
Chia-I Wucb023152018-08-28 12:57:23 -07005203 // set the requested width/height to the logical display viewport size
5204 // by default
5205 if (reqWidth == 0 || reqHeight == 0) {
5206 reqWidth = uint32_t(display->getViewport().width());
5207 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005208 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005209 }
5210
Peiyong Lin0e003c92018-09-17 11:09:51 -07005211 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5212 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005213
5214 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005215 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005216 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5217 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005218}
5219
5220status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005221 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5222 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005223 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005224 ATRACE_CALL();
5225
5226 class LayerRenderArea : public RenderArea {
5227 public:
Robert Carr578038f2018-03-09 12:25:24 -08005228 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005229 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5230 bool childrenOnly)
5231 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005232 mLayer(layer),
5233 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005234 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005235 mFlinger(flinger),
5236 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005237 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005238 Rect getBounds() const override {
5239 const Layer::State& layerState(mLayer->getDrawingState());
Vishnu Nair88a11f22018-11-28 18:30:57 -08005240 return mLayer->getBufferSize(layerState);
chaviwa76b2712017-09-20 12:02:26 -07005241 }
Marissa Wall61c58622018-07-18 10:12:20 -07005242 int getHeight() const override {
Vishnu Nair88a11f22018-11-28 18:30:57 -08005243 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005244 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005245 int getWidth() const override {
5246 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
5247 }
chaviwa76b2712017-09-20 12:02:26 -07005248 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005249 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005250 Rect getSourceCrop() const override {
5251 if (mCrop.isEmpty()) {
5252 return getBounds();
5253 } else {
5254 return mCrop;
5255 }
5256 }
Robert Carr578038f2018-03-09 12:25:24 -08005257 class ReparentForDrawing {
5258 public:
5259 const sp<Layer>& oldParent;
5260 const sp<Layer>& newParent;
5261
5262 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5263 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005264 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005265 }
Robert Carr15eae092018-03-23 13:43:53 -07005266 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005267 };
5268
5269 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005270 const Rect sourceCrop = getSourceCrop();
5271 // no need to check rotation because there is none
5272 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5273 sourceCrop.height() != getReqHeight();
5274
Robert Carr578038f2018-03-09 12:25:24 -08005275 if (!mChildrenOnly) {
5276 mTransform = mLayer->getTransform().inverse();
5277 drawLayers();
5278 } else {
5279 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005280 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005281 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5282 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005283
5284 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5285 drawLayers();
5286 }
5287 }
chaviwa76b2712017-09-20 12:02:26 -07005288
chaviwa76b2712017-09-20 12:02:26 -07005289 private:
chaviw7206d492017-11-10 16:16:12 -08005290 const sp<Layer> mLayer;
5291 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005292
5293 // In the "childrenOnly" case we reparent the children to a screenshot
5294 // layer which has no properties set and which does not draw.
5295 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005296 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005297 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005298
5299 SurfaceFlinger* mFlinger;
5300 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005301 };
5302
5303 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5304 auto parent = layerHandle->owner.promote();
5305
Robert Carr2e102c92018-10-23 12:11:15 -07005306 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005307 ALOGE("captureLayers called with a removed parent");
5308 return NAME_NOT_FOUND;
5309 }
5310
Robert Carr578038f2018-03-09 12:25:24 -08005311 const int uid = IPCThreadState::self()->getCallingUid();
5312 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5313 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5314 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5315 return PERMISSION_DENIED;
5316 }
5317
chaviw7206d492017-11-10 16:16:12 -08005318 Rect crop(sourceCrop);
5319 if (sourceCrop.width() <= 0) {
5320 crop.left = 0;
Vishnu Nair88a11f22018-11-28 18:30:57 -08005321 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005322 }
5323
5324 if (sourceCrop.height() <= 0) {
5325 crop.top = 0;
Vishnu Nair88a11f22018-11-28 18:30:57 -08005326 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005327 }
5328
5329 int32_t reqWidth = crop.width() * frameScale;
5330 int32_t reqHeight = crop.height() * frameScale;
5331
Chia-I Wu20261cb2018-08-23 12:55:44 -07005332 // really small crop or frameScale
5333 if (reqWidth <= 0) {
5334 reqWidth = 1;
5335 }
5336 if (reqHeight <= 0) {
5337 reqHeight = 1;
5338 }
5339
Peiyong Lin0e003c92018-09-17 11:09:51 -07005340 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005341
Robert Carr578038f2018-03-09 12:25:24 -08005342 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005343 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5344 if (!layer->isVisible()) {
5345 return;
Robert Carr578038f2018-03-09 12:25:24 -08005346 } else if (childrenOnly && layer == parent.get()) {
5347 return;
chaviwa76b2712017-09-20 12:02:26 -07005348 }
5349 visitor(layer);
5350 });
5351 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005352 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005353}
5354
5355status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5356 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005357 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005358 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005359 bool useIdentityTransform) {
5360 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005361
Peiyong Lin0e003c92018-09-17 11:09:51 -07005362 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005363 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5364 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005365 *outBuffer =
5366 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5367 static_cast<android_pixel_format>(reqPixelFormat), 1,
5368 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005369
5370 // This mutex protects syncFd and captureResult for communication of the return values from the
5371 // main thread back to this Binder thread
5372 std::mutex captureMutex;
5373 std::condition_variable captureCondition;
5374 std::unique_lock<std::mutex> captureLock(captureMutex);
5375 int syncFd = -1;
5376 std::optional<status_t> captureResult;
5377
Robert Carr03480e22018-01-04 16:02:06 -08005378 const int uid = IPCThreadState::self()->getCallingUid();
5379 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5380
Dominik Laskowski8c001672018-05-30 16:52:06 -07005381 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005382 // If there is a refresh pending, bug out early and tell the binder thread to try again
5383 // after the refresh.
5384 if (mRefreshPending) {
5385 ATRACE_NAME("Skipping screenshot for now");
5386 std::unique_lock<std::mutex> captureLock(captureMutex);
5387 captureResult = std::make_optional<status_t>(EAGAIN);
5388 captureCondition.notify_one();
5389 return;
5390 }
5391
5392 status_t result = NO_ERROR;
5393 int fd = -1;
5394 {
5395 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005396 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005397 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5398 useIdentityTransform, forSystem, &fd);
5399 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005400 }
5401
5402 {
5403 std::unique_lock<std::mutex> captureLock(captureMutex);
5404 syncFd = fd;
5405 captureResult = std::make_optional<status_t>(result);
5406 captureCondition.notify_one();
5407 }
5408 });
5409
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005410 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005411 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005412 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005413 while (*captureResult == EAGAIN) {
5414 captureResult.reset();
5415 result = postMessageAsync(message);
5416 if (result != NO_ERROR) {
5417 return result;
5418 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005419 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005420 }
5421 result = *captureResult;
5422 }
5423
5424 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005425 sync_wait(syncFd, -1);
5426 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005427 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005428
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005429 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005430}
5431
chaviwa76b2712017-09-20 12:02:26 -07005432void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005433 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005434 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005435 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005436
Lloyd Pique144e1162017-12-20 16:44:52 -08005437 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005438
chaviwa76b2712017-09-20 12:02:26 -07005439 const auto reqWidth = renderArea.getReqWidth();
5440 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005441 const auto sourceCrop = renderArea.getSourceCrop();
5442 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005443
Peiyong Lin0e003c92018-09-17 11:09:51 -07005444 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005445 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005446
Mathias Agopian180f10d2013-04-10 22:55:41 -07005447 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005448 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005449
5450 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005451 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005452 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005453
chaviw50da5042018-04-09 13:49:37 -07005454 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005455 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005456 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005457
chaviwa76b2712017-09-20 12:02:26 -07005458 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005459 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005460 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005461 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005462 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005463}
5464
chaviwa76b2712017-09-20 12:02:26 -07005465status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5466 TraverseLayersFunction traverseLayers,
5467 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005468 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005469 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005470 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005471 ATRACE_CALL();
5472
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005473 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005474
5475 traverseLayers([&](Layer* layer) {
5476 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5477 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005478
Robert Carr03480e22018-01-04 16:02:06 -08005479 // We allow the system server to take screenshots of secure layers for
5480 // use in situations like the Screen-rotation animation and place
5481 // the impetus on WindowManager to not persist them.
5482 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005483 ALOGW("FB is protected: PERMISSION_DENIED");
5484 return PERMISSION_DENIED;
5485 }
5486
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005487 // this binds the given EGLImage as a framebuffer for the
5488 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005489 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005490 if (bufferBond.getStatus() != NO_ERROR) {
5491 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005492 return INVALID_OPERATION;
5493 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005494
Dan Stozaabcda352017-06-01 14:37:39 -07005495 // this will in fact render into our dequeued buffer
5496 // via an FBO, which means we didn't have to create
5497 // an EGLSurface and therefore we're not
5498 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005499 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005500
Alec Mouri492bc572018-09-11 21:40:04 +00005501 base::unique_fd syncFd = getRenderEngine().flush();
5502 if (syncFd < 0) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005503 getRenderEngine().finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005504 }
Alec Mouri492bc572018-09-11 21:40:04 +00005505 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005506
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005507 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005508}
5509
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005510// ---------------------------------------------------------------------------
5511
Dan Stoza412903f2017-04-27 13:42:17 -07005512void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5513 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005514}
5515
Dan Stoza412903f2017-04-27 13:42:17 -07005516void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5517 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005518}
5519
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005520void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005521 const LayerVector::Visitor& visitor) {
5522 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005523 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005524 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005525 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005526 continue;
5527 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005528 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005529 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005530 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005531 return;
5532 }
chaviwa76b2712017-09-20 12:02:26 -07005533 if (!layer->isVisible()) {
5534 return;
5535 }
5536 visitor(layer);
5537 });
5538 }
5539}
5540
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005541}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005542
Lloyd Pique074e8122018-07-26 12:57:23 -07005543
Mathias Agopian3f844832013-08-07 21:24:32 -07005544#if defined(__gl_h_)
5545#error "don't include gl/gl.h in this file"
5546#endif
5547
5548#if defined(__gl2_h_)
5549#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005550#endif