blob: fa6ef254042c5f15eb02fd1ec99ac913f6d1efec [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
Chia-I Wud49d6692018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070050#include <renderengine/RenderEngine.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070051#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070066#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070067#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020070#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080072#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080073#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070077#include "NativeWindowSurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070081#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070082#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070083#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070084#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070086#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070087#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070088#include "Scheduler/EventControlThread.h"
89#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070090#include "Scheduler/InjectVSyncSource.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070091#include "Scheduler/Scheduler.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070092
Mathias Agopianff2ed702013-09-01 21:36:12 -070093#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070094
David Sodman7e4ae112018-02-09 15:02:28 -080095#include "android-base/stringprintf.h"
96
Jiyong Park4b20c2e2017-01-14 19:45:11 +090097#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080098#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -070099#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800100#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900101#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900102
chaviw1d044282017-09-27 12:19:28 -0700103#include <layerproto/LayerProtoParser.h>
104
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800105#define DISPLAY_COUNT 1
106
107namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700108
Jaesoo Lee43518572017-01-23 19:03:16 +0900109using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900110using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700111using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700112using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700113using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700114using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900115
Steven Thomasb02664d2017-07-26 18:48:28 -0700116namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700117
118#pragma clang diagnostic push
119#pragma clang diagnostic error "-Wswitch-enum"
120
121bool isWideColorMode(const ColorMode colorMode) {
122 switch (colorMode) {
123 case ColorMode::DISPLAY_P3:
124 case ColorMode::ADOBE_RGB:
125 case ColorMode::DCI_P3:
126 case ColorMode::BT2020:
127 case ColorMode::BT2100_PQ:
128 case ColorMode::BT2100_HLG:
129 return true;
130 case ColorMode::NATIVE:
131 case ColorMode::STANDARD_BT601_625:
132 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
133 case ColorMode::STANDARD_BT601_525:
134 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
135 case ColorMode::STANDARD_BT709:
136 case ColorMode::SRGB:
137 return false;
138 }
139 return false;
140}
141
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700142ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
143 switch (rotation) {
144 case ISurfaceComposer::eRotateNone:
145 return ui::Transform::ROT_0;
146 case ISurfaceComposer::eRotate90:
147 return ui::Transform::ROT_90;
148 case ISurfaceComposer::eRotate180:
149 return ui::Transform::ROT_180;
150 case ISurfaceComposer::eRotate270:
151 return ui::Transform::ROT_270;
152 }
153 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
154 return ui::Transform::ROT_0;
155}
156
Peiyong Linfca547f2018-07-09 13:03:33 -0700157#pragma clang diagnostic pop
158
Steven Thomasb02664d2017-07-26 18:48:28 -0700159class ConditionalLock {
160public:
161 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
162 if (lock) {
163 mMutex.lock();
164 }
165 }
166 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
167private:
168 Mutex& mMutex;
169 bool mLocked;
170};
Peiyong Linfca547f2018-07-09 13:03:33 -0700171
Steven Thomasb02664d2017-07-26 18:48:28 -0700172} // namespace anonymous
173
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800174// ---------------------------------------------------------------------------
175
Mathias Agopian99b49842011-06-27 16:05:52 -0700176const String16 sHardwareTest("android.permission.HARDWARE_TEST");
177const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
178const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
179const String16 sDump("android.permission.DUMP");
180
181// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800182int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
183int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700184int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700185bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800186uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800187bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800188bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800189int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800190// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600191bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700192int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700193bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700194bool SurfaceFlinger::useContextPriority;
Peiyong Lin0256f722018-08-31 15:45:10 -0700195Dataspace SurfaceFlinger::compositionDataSpace = Dataspace::V0_SRGB;
196ui::PixelFormat SurfaceFlinger::compositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700197
Kalle Raitaa099a242017-01-11 11:17:29 -0800198std::string getHwcServiceName() {
199 char value[PROPERTY_VALUE_MAX] = {};
200 property_get("debug.sf.hwc_service_name", value, "default");
201 ALOGI("Using HWComposer service: '%s'", value);
202 return std::string(value);
203}
204
205bool useTrebleTestingOverride() {
206 char value[PROPERTY_VALUE_MAX] = {};
207 property_get("debug.sf.treble_testing_override", value, "false");
208 ALOGI("Treble testing override: '%s'", value);
209 return std::string(value) == "true";
210}
211
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800212std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
213 switch(displayColorSetting) {
214 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700215 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800216 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700217 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800218 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700219 return std::string("Enhanced");
220 default:
221 return std::string("Unknown ") +
222 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800223 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800224}
225
David Sodmanbc815282017-11-05 18:57:52 -0800226SurfaceFlingerBE::SurfaceFlingerBE()
227 : mHwcServiceName(getHwcServiceName()),
228 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800229 mFrameBuckets(),
230 mTotalTime(0),
231 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800232 mComposerSequenceId(0) {
233}
234
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800235SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800236 : BnSurfaceComposer(),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700237 mTransactionPending(false),
238 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700239 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700240 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800241 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700242 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800243 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800244 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800245 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800246 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800247 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700248 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700249 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700250 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700251 mDebugInTransaction(0),
252 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700253 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700254 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700255 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800256 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800257 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800258 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700259 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800260 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800261 mCreateBufferQueue(&BufferQueue::createBufferQueue),
Lloyd Pique22098362018-09-13 11:46:49 -0700262 mCreateNativeWindowSurface(&surfaceflinger::impl::createNativeWindowSurface) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800263
264SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800265 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800266
267 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
268 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
269
270 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
271 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
272
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800273 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
274 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800275
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700276 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
277 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
278
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700279 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
280 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
281
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800282 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
283 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
284
Steven Thomas050b2c82017-03-06 11:45:16 -0800285 // Vr flinger is only enabled on Daydream ready devices.
286 useVrFlinger = getBool< ISurfaceFlingerConfigs,
287 &ISurfaceFlingerConfigs::useVrFlinger>(false);
288
Fabien Sanglard1971b632017-03-10 14:50:03 -0800289 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
290 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
291
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600292 hasWideColorDisplay =
293 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700294 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700295 getBool<V1_2::ISurfaceFlingerConfigs,
296 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
297
298 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
299 if (surfaceFlingerConfigsServiceV1_2) {
300 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
301 [&](Dataspace tmpDataSpace, ui::PixelFormat tmpPixelFormat) {
302 compositionDataSpace = tmpDataSpace;
303 compositionPixelFormat = tmpPixelFormat;
304 });
305 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600306
Peiyong Linb3839ad2018-09-05 15:37:19 -0700307 useContextPriority = getBool<ISurfaceFlingerConfigs,
308 &ISurfaceFlingerConfigs::useContextPriority>(true);
309
Iris Chang7501ed62018-04-30 14:45:42 +0800310 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700311 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
312 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800313 V1_1::DisplayOrientation::ORIENTATION_0);
314
315 switch (primaryDisplayOrientation) {
316 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700317 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800318 break;
319 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700320 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800321 break;
322 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700323 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800324 break;
325 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700326 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800327 break;
328 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700329 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800330
Lloyd Pique41be5d22018-06-21 13:11:48 -0700331 // Note: We create a local temporary with the real DispSync implementation
332 // type temporarily so we can initialize it with the configured values,
333 // before storing it for more generic use using the interface type.
334 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
335 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
336 SurfaceFlinger::dispSyncPresentTimeOffset);
337 mPrimaryDispSync = std::move(primaryDispSync);
Saurabh Shahf4174532017-07-13 10:45:07 -0700338
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800339 // debugging stuff...
340 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700341
Mathias Agopianb4b17302013-03-20 18:36:41 -0700342 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700343 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700344
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800345 property_get("debug.sf.showupdates", value, "0");
346 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700347
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700348 property_get("debug.sf.ddms", value, "0");
349 mDebugDDMS = atoi(value);
350 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700351 if (!startDdmConnection()) {
352 // start failed, and DDMS debugging not enabled
353 mDebugDDMS = 0;
354 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700355 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700356 ALOGI_IF(mDebugRegion, "showupdates enabled");
357 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700358
359 property_get("debug.sf.disable_backpressure", value, "0");
360 mPropagateBackpressure = !atoi(value);
361 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700362
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800363 property_get("debug.sf.enable_hwc_vds", value, "0");
364 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800365 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800366
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800367 property_get("ro.sf.disable_triple_buffer", value, "1");
368 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800369 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700370
Yiwei Zhang243b3782018-05-15 17:40:04 -0700371 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700372 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
373 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
374
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200375 property_get("debug.sf.early_phase_offset_ns", value, "-1");
376 const int earlySfOffsetNs = atoi(value);
377
378 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
379 const int earlyGlSfOffsetNs = atoi(value);
380
381 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
382 const int earlyAppOffsetNs = atoi(value);
383
384 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
385 const int earlyGlAppOffsetNs = atoi(value);
386
Ana Krulec98b5b242018-08-10 15:03:23 -0700387 property_get("debug.sf.use_scheduler", value, "0");
388 mUseScheduler = atoi(value);
389
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200390 const VSyncModulator::Offsets earlyOffsets =
391 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
392 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
393 const VSyncModulator::Offsets earlyGlOffsets =
394 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
395 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
396 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
397 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700398
Romain Guy11d63f42017-07-20 12:47:14 -0700399 // We should be reading 'persist.sys.sf.color_saturation' here
400 // but since /data may be encrypted, we need to wait until after vold
401 // comes online to attempt to read the property. The property is
402 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800403
404 if (useTrebleTestingOverride()) {
405 // Without the override SurfaceFlinger cannot connect to HIDL
406 // services that are not listed in the manifests. Considered
407 // deriving the setting from the set service name, but it
408 // would be brittle if the name that's not 'default' is used
409 // for production purposes later on.
410 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
411 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800412}
413
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800414void SurfaceFlinger::onFirstRef()
415{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800416 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800417}
418
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800419SurfaceFlinger::~SurfaceFlinger()
420{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800421}
422
Dan Stozac7014012014-02-14 15:03:43 -0800423void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800424{
425 // the window manager died on us. prepare its eulogy.
426
Andy McFadden13a082e2012-08-24 10:16:42 -0700427 // restore initial conditions (default device unblank, etc)
428 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800429
430 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700431 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800432}
433
Robert Carr1db73f62016-12-21 12:58:51 -0800434static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700435 status_t err = client->initCheck();
436 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800437 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800438 }
Robert Carr1db73f62016-12-21 12:58:51 -0800439 return nullptr;
440}
441
442sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
443 return initClient(new Client(this));
444}
445
446sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
447 const sp<IGraphicBufferProducer>& gbp) {
448 if (authenticateSurfaceTexture(gbp) == false) {
449 return nullptr;
450 }
451 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
452 if (layer == nullptr) {
453 return nullptr;
454 }
455
456 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800457}
458
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700459sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
460 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700461{
462 class DisplayToken : public BBinder {
463 sp<SurfaceFlinger> flinger;
464 virtual ~DisplayToken() {
465 // no more references, this display must be terminated
466 Mutex::Autolock _l(flinger->mStateLock);
467 flinger->mCurrentState.displays.removeItem(this);
468 flinger->setTransactionFlags(eDisplayTransactionNeeded);
469 }
470 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700471 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700472 : flinger(flinger) {
473 }
474 };
475
476 sp<BBinder> token = new DisplayToken(this);
477
478 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700479 DisplayDeviceState info;
480 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700481 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700482 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700483 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800484 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700485 return token;
486}
487
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700488void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700489 Mutex::Autolock _l(mStateLock);
490
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700491 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700492 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700493 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700494 return;
495 }
496
497 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700498 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700499 ALOGE("destroyDisplay called for non-virtual display");
500 return;
501 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700502 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700503 mCurrentState.displays.removeItemsAt(idx);
504 setTransactionFlags(eDisplayTransactionNeeded);
505}
506
Mathias Agopiane57f2922012-08-09 16:29:12 -0700507sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700508 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700509 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800510 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700511 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700512 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700513}
514
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800515void SurfaceFlinger::bootFinished()
516{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700517 if (mStartPropertySetThread->join() != NO_ERROR) {
518 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800519 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800520 const nsecs_t now = systemTime();
521 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000522 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700523
524 // wait patiently for the window manager death
525 const String16 name("window");
526 sp<IBinder> window(defaultServiceManager()->getService(name));
527 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700528 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700529 }
530
Steven Thomas050b2c82017-03-06 11:45:16 -0800531 if (mVrFlinger) {
532 mVrFlinger->OnBootFinished();
533 }
534
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700535 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700536 // formerly we would just kill the process, but we now ask it to exit so it
537 // can choose where to stop the animation.
538 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700539
540 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
541 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
542 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700543
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800544 postMessageAsync(new LambdaMessage([this] {
545 readPersistentProperties();
546 mBootStage = BootStage::FINISHED;
547 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800548}
549
Dan Stoza436ccf32018-06-21 12:10:12 -0700550uint32_t SurfaceFlinger::getNewTexture() {
551 {
552 std::lock_guard lock(mTexturePoolMutex);
553 if (!mTexturePool.empty()) {
554 uint32_t name = mTexturePool.back();
555 mTexturePool.pop_back();
556 ATRACE_INT("TexturePoolSize", mTexturePool.size());
557 return name;
558 }
559
560 // The pool was too small, so increase it for the future
561 ++mTexturePoolSize;
562 }
563
564 // The pool was empty, so we need to get a new texture name directly using a
565 // blocking call to the main thread
566 uint32_t name = 0;
567 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
568 return name;
569}
570
Mathias Agopian3f844832013-08-07 21:24:32 -0700571void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700572 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700573}
574
Wei Wangf9b05ee2017-07-19 20:59:39 -0700575// Do not call property_set on main thread which will be blocked by init
576// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700577void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700578 ALOGI( "SurfaceFlinger's main thread ready to run. "
579 "Initializing graphics H/W...");
580
Thierry Strudel2924d012017-08-14 15:19:37 -0700581 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900582
Steven Thomasb02664d2017-07-26 18:48:28 -0700583 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800584
Steven Thomasb02664d2017-07-26 18:48:28 -0700585 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700586 if (mUseScheduler) {
Ana Krulece588e312018-09-18 12:32:24 -0700587 mScheduler = std::make_unique<Scheduler>(
588 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Ana Krulec98b5b242018-08-10 15:03:23 -0700589 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700590 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700591 [this] { resyncWithRateLimit(); },
592 impl::EventThread::InterceptVSyncsCallback());
593 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700594 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700595 [this] { resyncWithRateLimit(); },
596 [this](nsecs_t timestamp) {
597 mInterceptor->saveVSyncEvent(timestamp);
598 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800599
Ana Krulec98b5b242018-08-10 15:03:23 -0700600 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700601 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
602 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700603 } else {
604 mEventThreadSource =
605 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
606 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
607 mEventThread =
608 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
609 [this] { resyncWithRateLimit(); },
610 impl::EventThread::InterceptVSyncsCallback(),
611 "appEventThread");
612 mSfEventThreadSource =
613 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
614 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
615
616 mSFEventThread =
617 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
618 [this] { resyncWithRateLimit(); },
619 [this](nsecs_t timestamp) {
620 mInterceptor->saveVSyncEvent(timestamp);
621 },
622 "sfEventThread");
623 mEventQueue->setEventThread(mSFEventThread.get());
624 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
625 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800626
Steven Thomasb02664d2017-07-26 18:48:28 -0700627 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700628 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700629 renderEngineFeature |= (useColorManagement ?
630 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700631 renderEngineFeature |= (useContextPriority ?
632 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700633
634 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
635 getBE().mRenderEngine =
Peiyong Linf11f39b2018-09-05 14:37:41 -0700636 renderengine::RenderEngine::create(static_cast<int32_t>(compositionPixelFormat),
637 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800638 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700639
640 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
641 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800642 getBE().mHwc.reset(
643 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700644 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800645 // Process any initial hotplug and resulting display changes.
646 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700647 const auto display = getDefaultDisplayDeviceLocked();
648 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
649 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
650 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800651
Lloyd Piquefcd86612017-12-14 17:15:36 -0800652 // make the default display GLContext current so that we can create textures
653 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700654 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800655
Steven Thomas050b2c82017-03-06 11:45:16 -0800656 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700657 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700658 // This callback is called from the vr flinger dispatch thread. We
659 // need to call signalTransaction(), which requires holding
660 // mStateLock when we're not on the main thread. Acquiring
661 // mStateLock from the vr flinger dispatch thread might trigger a
662 // deadlock in surface flinger (see b/66916578), so post a message
663 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700664 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700665 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
666 mVrFlingerRequestsDisplay = requestDisplay;
667 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700668 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800669 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700670 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
671 getHwComposer()
672 .getHwcDisplayId(display->getId())
673 .value_or(0),
674 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800675 if (!mVrFlinger) {
676 ALOGE("Failed to start vrflinger");
677 }
678 }
679
Lloyd Pique379adc12018-01-22 17:31:47 -0800680 mEventControlThread = std::make_unique<impl::EventControlThread>(
681 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700682
Mathias Agopian92a979a2012-08-02 18:32:23 -0700683 // initialize our drawing state
684 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700685
Andy McFadden13a082e2012-08-24 10:16:42 -0700686 // set initial conditions (e.g. unblank default device)
687 initializeDisplays();
688
David Sodmanbc815282017-11-05 18:57:52 -0800689 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700690
Wei Wangf9b05ee2017-07-19 20:59:39 -0700691 // Inform native graphics APIs whether the present timestamp is supported:
692 if (getHwComposer().hasCapability(
693 HWC2::Capability::PresentFenceIsNotReliable)) {
694 mStartPropertySetThread = new StartPropertySetThread(false);
695 } else {
696 mStartPropertySetThread = new StartPropertySetThread(true);
697 }
698
699 if (mStartPropertySetThread->Start() != NO_ERROR) {
700 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800701 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800702
Chia-I Wud49d6692018-06-27 07:17:41 +0800703 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
704 // is used to saturate legacy sRGB content. However, to make sure the same color under
705 // Display P3 will be saturated to the same color, we intentionally break the API spec
706 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
707 // such saturation matrix on Display P3 is understood fully, the API should always return
708 // identify matrix.
709 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
710 Dataspace::SRGB_LINEAR);
711
712 // we will apply this on Display P3.
713 if (mEnhancedSaturationMatrix != mat4()) {
714 ColorSpace srgb(ColorSpace::sRGB());
715 ColorSpace displayP3(ColorSpace::DisplayP3());
716 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
717 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
718 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
719 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800720
Dan Stoza9e56aa02015-11-02 13:00:03 -0800721 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700722}
723
Romain Guy11d63f42017-07-20 12:47:14 -0700724void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700725 Mutex::Autolock _l(mStateLock);
726
Romain Guy11d63f42017-07-20 12:47:14 -0700727 char value[PROPERTY_VALUE_MAX];
728
729 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800730 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700731 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800732 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100733
734 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700735 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700736}
737
Mathias Agopiana67e4182012-06-19 17:26:12 -0700738void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800739 // Start boot animation service by setting a property mailbox
740 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700741 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800742 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700743 if (mStartPropertySetThread->join() != NO_ERROR) {
744 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800745 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700746}
747
Mathias Agopian875d8e12013-06-07 15:35:48 -0700748size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800749 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700750}
751
Mathias Agopian875d8e12013-06-07 15:35:48 -0700752size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800753 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700754}
755
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800756// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800757
Jamie Gennis582270d2011-08-17 18:19:00 -0700758bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800759 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800760 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800761 return authenticateSurfaceTextureLocked(bufferProducer);
762}
763
764bool SurfaceFlinger::authenticateSurfaceTextureLocked(
765 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800766 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800767 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800768}
769
Brian Anderson6b376712017-04-04 10:51:39 -0700770status_t SurfaceFlinger::getSupportedFrameTimestamps(
771 std::vector<FrameEvent>* outSupported) const {
772 *outSupported = {
773 FrameEvent::REQUESTED_PRESENT,
774 FrameEvent::ACQUIRE,
775 FrameEvent::LATCH,
776 FrameEvent::FIRST_REFRESH_START,
777 FrameEvent::LAST_REFRESH_START,
778 FrameEvent::GPU_COMPOSITION_DONE,
779 FrameEvent::DEQUEUE_READY,
780 FrameEvent::RELEASE,
781 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700782 ConditionalLock _l(mStateLock,
783 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700784 if (!getHwComposer().hasCapability(
785 HWC2::Capability::PresentFenceIsNotReliable)) {
786 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
787 }
788 return NO_ERROR;
789}
790
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700791status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
792 Vector<DisplayInfo>* configs) {
793 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700794 return BAD_VALUE;
795 }
796
Jesse Hall692c7232012-11-08 15:41:56 -0800797 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700798 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
799 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700800 type = i;
801 break;
802 }
803 }
804
805 if (type < 0) {
806 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700807 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700808
Mathias Agopian8b736f12012-08-13 17:54:26 -0700809 // TODO: Not sure if display density should handled by SF any longer
810 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700811 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700812 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700813 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800814 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700815 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700816 }
817 return density;
818 }
819 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700820 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700821 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700822 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700823 return getDensityFromProperty("ro.sf.lcd_density"); }
824 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700825
Dan Stoza7f7da322014-05-02 15:26:25 -0700826 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700827
Steven Thomas6d8110b2017-08-31 18:24:21 -0700828 ConditionalLock _l(mStateLock,
829 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800830 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700831 DisplayInfo info = DisplayInfo();
832
Dan Stoza9e56aa02015-11-02 13:00:03 -0800833 float xdpi = hwConfig->getDpiX();
834 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700835
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700836 info.w = hwConfig->getWidth();
837 info.h = hwConfig->getHeight();
838 // Default display viewport to display width and height
839 info.viewportW = info.w;
840 info.viewportH = info.h;
841
Dan Stoza7f7da322014-05-02 15:26:25 -0700842 if (type == DisplayDevice::DISPLAY_PRIMARY) {
843 // The density of the device is provided by a build property
844 float density = Density::getBuildDensity() / 160.0f;
845 if (density == 0) {
846 // the build doesn't provide a density -- this is wrong!
847 // use xdpi instead
848 ALOGE("ro.sf.lcd_density must be defined as a build property");
849 density = xdpi / 160.0f;
850 }
851 if (Density::getEmuDensity()) {
852 // if "qemu.sf.lcd_density" is specified, it overrides everything
853 xdpi = ydpi = density = Density::getEmuDensity();
854 density /= 160.0f;
855 }
856 info.density = density;
857
858 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700859 const auto display = getDefaultDisplayDeviceLocked();
860 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700861
862 // This is for screenrecord
863 const Rect viewport = display->getViewport();
864 if (viewport.isValid()) {
865 info.viewportW = uint32_t(viewport.getWidth());
866 info.viewportH = uint32_t(viewport.getHeight());
867 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700868 } else {
869 // TODO: where should this value come from?
870 static const int TV_DENSITY = 213;
871 info.density = TV_DENSITY / 160.0f;
872 info.orientation = 0;
873 }
874
Dan Stoza7f7da322014-05-02 15:26:25 -0700875 info.xdpi = xdpi;
876 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800877 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900878 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800879
Andy McFadden91b2ca82014-06-13 14:04:23 -0700880 // This is how far in advance a buffer must be queued for
881 // presentation at a given time. If you want a buffer to appear
882 // on the screen at time N, you must submit the buffer before
883 // (N - presentationDeadline).
884 //
885 // Normally it's one full refresh period (to give SF a chance to
886 // latch the buffer), but this can be reduced by configuring a
887 // DispSync offset. Any additional delays introduced by the hardware
888 // composer or panel must be accounted for here.
889 //
890 // We add an additional 1ms to allow for processing time and
891 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800892 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800893 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700894
895 // All non-virtual displays are currently considered secure.
896 info.secure = true;
897
Iris Chang7501ed62018-04-30 14:45:42 +0800898 if (type == DisplayDevice::DISPLAY_PRIMARY &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700899 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800900 std::swap(info.w, info.h);
901 }
902
Michael Wright28f24d02016-07-12 13:30:53 -0700903 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700904 }
905
Dan Stoza7f7da322014-05-02 15:26:25 -0700906 return NO_ERROR;
907}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700908
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700909status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
910 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700911 return BAD_VALUE;
912 }
913
Ana Krulece588e312018-09-18 12:32:24 -0700914 // FIXME for now we always return stats for the primary display.
915 if (mUseScheduler) {
916 mScheduler->getDisplayStatInfo(stats);
917 } else {
918 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
919 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
920 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700921 return NO_ERROR;
922}
923
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700924int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
925 const auto display = getDisplayDevice(displayToken);
926 if (!display) {
927 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800928 return BAD_VALUE;
929 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700930
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700931 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700932}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700933
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700934void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
935 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700936 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700937 return;
938 }
939
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700940 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700941 ALOGW("Trying to set config for virtual display");
942 return;
943 }
944
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700945 display->setActiveConfig(mode);
946 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700947}
948
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700949status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700950 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700951 Vector<DisplayInfo> configs;
952 getDisplayConfigs(displayToken, &configs);
953 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
954 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
955 configs.size());
956 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700957 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700958 const auto display = getDisplayDevice(displayToken);
959 if (!display) {
960 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
961 displayToken.get());
962 } else if (display->isVirtual()) {
963 ALOGW("Attempt to set active config %d for virtual display", mode);
964 } else {
965 setActiveConfigInternal(display, mode);
966 }
967 }));
968
Mathias Agopian888c8222012-08-04 21:10:38 -0700969 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700970}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700971status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
972 Vector<ColorMode>* outColorModes) {
973 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700974 return BAD_VALUE;
975 }
976
Michael Wright28f24d02016-07-12 13:30:53 -0700977 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700978 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
979 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700980 type = i;
981 break;
982 }
983 }
984
985 if (type < 0) {
986 return type;
987 }
988
Peiyong Lina52f0292018-03-14 17:26:31 -0700989 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700990 {
991 ConditionalLock _l(mStateLock,
992 std::this_thread::get_id() != mMainThreadId);
993 modes = getHwComposer().getColorModes(type);
994 }
Michael Wright28f24d02016-07-12 13:30:53 -0700995 outColorModes->clear();
996 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
997
998 return NO_ERROR;
999}
1000
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001001ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1002 if (const auto display = getDisplayDevice(displayToken)) {
1003 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001004 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001005 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001006}
1007
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001008void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1009 Dataspace dataSpace, RenderIntent renderIntent) {
1010 ColorMode currentMode = display->getActiveColorMode();
1011 Dataspace currentDataSpace = display->getCompositionDataSpace();
1012 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001013
Peiyong Lin38e9a562018-04-10 16:24:20 -07001014 if (mode == currentMode && dataSpace == currentDataSpace &&
1015 renderIntent == currentRenderIntent) {
1016 return;
1017 }
1018
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001019 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001020 ALOGW("Trying to set config for virtual display");
1021 return;
1022 }
1023
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001024 display->setActiveColorMode(mode);
1025 display->setCompositionDataSpace(dataSpace);
1026 display->setActiveRenderIntent(renderIntent);
1027 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001028
1029 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001030 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1031 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001032}
1033
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001034status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001035 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001036 Vector<ColorMode> modes;
1037 getDisplayColorModes(displayToken, &modes);
1038 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1039 if (mode < ColorMode::NATIVE || !exists) {
1040 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1041 decodeColorMode(mode).c_str(), mode, displayToken.get());
1042 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001043 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001044 const auto display = getDisplayDevice(displayToken);
1045 if (!display) {
1046 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1047 decodeColorMode(mode).c_str(), mode, displayToken.get());
1048 } else if (display->isVirtual()) {
1049 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1050 decodeColorMode(mode).c_str(), mode);
1051 } else {
1052 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1053 RenderIntent::COLORIMETRIC);
1054 }
1055 }));
1056
Michael Wright28f24d02016-07-12 13:30:53 -07001057 return NO_ERROR;
1058}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001059
Svetoslavd85084b2014-03-20 10:28:31 -07001060status_t SurfaceFlinger::clearAnimationFrameStats() {
1061 Mutex::Autolock _l(mStateLock);
1062 mAnimFrameTracker.clearStats();
1063 return NO_ERROR;
1064}
1065
1066status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1067 Mutex::Autolock _l(mStateLock);
1068 mAnimFrameTracker.getStats(outStats);
1069 return NO_ERROR;
1070}
1071
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001072status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1073 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001074 Mutex::Autolock _l(mStateLock);
1075
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001076 const auto display = getDisplayDeviceLocked(displayToken);
1077 if (!display) {
1078 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001079 return BAD_VALUE;
1080 }
1081
Peiyong Linfb069302018-04-25 14:34:31 -07001082 // At this point the DisplayDeivce should already be set up,
1083 // meaning the luminance information is already queried from
1084 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001085 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001086 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1087 capabilities.getDesiredMaxLuminance(),
1088 capabilities.getDesiredMaxAverageLuminance(),
1089 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001090
1091 return NO_ERROR;
1092}
1093
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001094status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001095 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001096 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001097
Chia-I Wu90f669f2017-10-05 14:24:41 -07001098 if (mInjectVSyncs == enable) {
1099 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001100 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001101
Ana Krulec98b5b242018-08-10 15:03:23 -07001102 // TODO(akrulec): Part of the Injector should be refactored, so that it
1103 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001104 if (enable) {
1105 ALOGV("VSync Injections enabled");
1106 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001107 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001108 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001109 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001110 impl::EventThread::InterceptVSyncsCallback(),
1111 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001112 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001113 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001114 } else {
1115 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001116 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001117 }
1118
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001119 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001120 }));
1121
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001122 return NO_ERROR;
1123}
1124
1125status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001126 Mutex::Autolock _l(mStateLock);
1127
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001128 if (!mInjectVSyncs) {
1129 ALOGE("VSync Injections not enabled");
1130 return BAD_VALUE;
1131 }
1132 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1133 ALOGV("Injecting VSync inside SurfaceFlinger");
1134 mVSyncInjector->onInjectSyncEvent(when);
1135 }
1136 return NO_ERROR;
1137}
1138
Lloyd Pique755e3192018-01-31 16:46:15 -08001139status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1140 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001141 // Try to acquire a lock for 1s, fail gracefully
1142 const status_t err = mStateLock.timedLock(s2ns(1));
1143 const bool locked = (err == NO_ERROR);
1144 if (!locked) {
1145 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1146 return TIMED_OUT;
1147 }
1148
1149 outLayers->clear();
1150 mCurrentState.traverseInZOrder([&](Layer* layer) {
1151 outLayers->push_back(layer->getLayerDebugInfo());
1152 });
1153
1154 mStateLock.unlock();
1155 return NO_ERROR;
1156}
1157
Peiyong Lin0256f722018-08-31 15:45:10 -07001158status_t SurfaceFlinger::getCompositionPreference(Dataspace* outDataSpace,
1159 ui::PixelFormat* outPixelFormat) const {
1160 *outDataSpace = compositionDataSpace;
1161 *outPixelFormat = compositionPixelFormat;
1162 return NO_ERROR;
1163}
1164
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001165// ----------------------------------------------------------------------------
1166
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001167sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1168 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001169 if (mUseScheduler) {
1170 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1171 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1172 } else {
1173 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1174 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001175 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001176 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1177 return mSFEventThread->createEventConnection();
1178 } else {
1179 return mEventThread->createEventConnection();
1180 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001181 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001182}
1183
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001184// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001185
1186void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001187 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001188}
1189
1190void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001191 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001192}
1193
1194void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001195 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001196}
1197
1198void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001199 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001200 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001201}
1202
1203status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001204 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001205 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001206}
1207
1208status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001209 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001210 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001211 if (res == NO_ERROR) {
1212 msg->wait();
1213 }
1214 return res;
1215}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001216
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001217void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001218 do {
1219 waitForEvent();
1220 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001221}
1222
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001223void SurfaceFlinger::enableHardwareVsync() {
1224 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001225 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001226 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001227 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001228 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001229 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001230}
1231
Jesse Hall948fe0c2013-10-14 12:56:09 -07001232void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001233 Mutex::Autolock _l(mHWVsyncLock);
1234
Jesse Hall948fe0c2013-10-14 12:56:09 -07001235 if (makeAvailable) {
1236 mHWVsyncAvailable = true;
1237 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001238 // Hardware vsync is not currently available, so abort the resync
1239 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001240 return;
1241 }
1242
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001243 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1244 if (!getHwComposer().isConnected(displayId)) {
1245 return;
1246 }
1247
1248 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001249 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001250
Ana Krulece588e312018-09-18 12:32:24 -07001251 if (mUseScheduler) {
1252 mScheduler->setVsyncPeriod(period);
1253 } else {
1254 mPrimaryDispSync->reset();
1255 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001256
Ana Krulece588e312018-09-18 12:32:24 -07001257 if (!mPrimaryHWVsyncEnabled) {
1258 mPrimaryDispSync->beginResync();
1259 mEventControlThread->setVsyncEnabled(true);
1260 mPrimaryHWVsyncEnabled = true;
1261 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001262 }
1263}
1264
Jesse Hall948fe0c2013-10-14 12:56:09 -07001265void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001266 Mutex::Autolock _l(mHWVsyncLock);
1267 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001268 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001269 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001270 mPrimaryHWVsyncEnabled = false;
1271 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001272 if (makeUnavailable) {
1273 mHWVsyncAvailable = false;
1274 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001275}
1276
Tim Murray4a4e4a22016-04-19 16:29:23 +00001277void SurfaceFlinger::resyncWithRateLimit() {
1278 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001279
1280 // No explicit locking is needed here since EventThread holds a lock while calling this method
1281 static nsecs_t sLastResyncAttempted = 0;
1282 const nsecs_t now = systemTime();
1283 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001284 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001285 }
Dan Stoza57164302017-05-08 14:03:54 -07001286 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001287}
1288
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001289void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1290 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001291 ATRACE_NAME("SF onVsync");
1292
Steven Thomas3cfac282017-02-06 12:29:30 -08001293 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001294 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001295 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001296 return;
1297 }
1298
1299 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001300 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001301 return;
1302 }
1303
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001304 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1305 // For now, we don't do anything with external display vsyncs.
1306 return;
1307 }
1308
Ana Krulece588e312018-09-18 12:32:24 -07001309 if (mUseScheduler) {
1310 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001311 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001312 bool needsHwVsync = false;
1313 { // Scope for the lock
1314 Mutex::Autolock _l(mHWVsyncLock);
1315 if (mPrimaryHWVsyncEnabled) {
1316 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1317 }
1318 }
1319
1320 if (needsHwVsync) {
1321 enableHardwareVsync();
1322 } else {
1323 disableHardwareVsync(false);
1324 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001325 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001326}
1327
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001328void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001329 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1330 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001331}
1332
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001333void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001334 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001335 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001336 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001337
Lloyd Piqueba04e622017-12-14 17:11:26 -08001338 // Ignore events that do not have the right sequenceId.
1339 if (sequenceId != getBE().mComposerSequenceId) {
1340 return;
1341 }
1342
Steven Thomasb02664d2017-07-26 18:48:28 -07001343 // Only lock if we're not on the main thread. This function is normally
1344 // called on a hwbinder thread, but for the primary display it's called on
1345 // the main thread with the state lock already held, so don't attempt to
1346 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001347 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001348
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001349 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001350
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001351 if (std::this_thread::get_id() == mMainThreadId) {
1352 // Process all pending hot plug events immediately if we are on the main thread.
1353 processDisplayHotplugEventsLocked();
1354 }
1355
Lloyd Piqueba04e622017-12-14 17:11:26 -08001356 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001357}
1358
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001359void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001360 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001361 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001362 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001363 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001364 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001365}
1366
Dan Stoza9e56aa02015-11-02 13:00:03 -08001367void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001368 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001369 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001370 getHwComposer().setVsyncEnabled(disp,
1371 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001372}
1373
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001374// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001375void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001376 if (mUseScheduler) {
1377 mScheduler->disableHardwareVsync(true);
1378 } else {
1379 disableHardwareVsync(true);
1380 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001381 // Clear the drawing state so that the logic inside of
1382 // handleTransactionLocked will fire. It will determine the delta between
1383 // mCurrentState and mDrawingState and re-apply all changes when we make the
1384 // transition.
1385 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001386 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001387 mDisplays.clear();
1388}
1389
Steven Thomas050b2c82017-03-06 11:45:16 -08001390void SurfaceFlinger::updateVrFlinger() {
1391 if (!mVrFlinger)
1392 return;
1393 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001394 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001395 return;
1396 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001397
David Sodman105b7dc2017-11-04 20:28:14 -07001398 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001399 ALOGE("Vr flinger is only supported for remote hardware composer"
1400 " service connections. Ignoring request to transition to vr"
1401 " flinger.");
1402 mVrFlingerRequestsDisplay = false;
1403 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001404 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001405
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001406 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001407
Steven Thomas0123ac62018-07-12 11:32:34 -07001408 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001409 LOG_ALWAYS_FATAL_IF(!display);
1410 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001411 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1412 // called below. Clear the reference now so we don't accidentally use it
1413 // later.
1414 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001415
Steven Thomasb02664d2017-07-26 18:48:28 -07001416 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001417 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001418 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001419
Steven Thomasb02664d2017-07-26 18:48:28 -07001420 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001421 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001422 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1423 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001424 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001425
David Sodman105b7dc2017-11-04 20:28:14 -07001426 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1427 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001428
1429 if (vrFlingerRequestsDisplay) {
1430 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001431 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001432
1433 mVisibleRegionsDirty = true;
1434 invalidateHwcGeometry();
1435
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001436 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001437 display = getDefaultDisplayDeviceLocked();
1438 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001439 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001440
Steven Thomasb02664d2017-07-26 18:48:28 -07001441 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001442 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001443 const nsecs_t period = activeConfig->getVsyncPeriod();
1444 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001445
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001446 // The present fences returned from vr_hwc are not an accurate
1447 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001448 if (mUseScheduler) {
1449 mScheduler->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() || !hasSyncFramework);
1450 } else {
1451 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1452 !hasSyncFramework);
1453 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001454
Steven Thomasb02664d2017-07-26 18:48:28 -07001455 // Use phase of 0 since phase is not known.
1456 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001457 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1458 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001459
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001460 resyncToHardwareVsync(false);
1461
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001462 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001463 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001464}
1465
Mathias Agopian4fec8732012-06-29 14:12:52 -07001466void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001467 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001468 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001469 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001470 bool frameMissed = !mHadClientComposition &&
1471 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001472 (mPreviousPresentFence->getSignalTime() ==
1473 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001474 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001475 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001476 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001477 mTimeStats.incrementMissedFrames();
1478 if (mPropagateBackpressure) {
1479 signalLayerUpdate();
1480 break;
1481 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001482 }
Dan Stoza50182882016-07-08 12:02:20 -07001483
Steven Thomas050b2c82017-03-06 11:45:16 -08001484 // Now that we're going to make it to the handleMessageTransaction()
1485 // call below it's safe to call updateVrFlinger(), which will
1486 // potentially trigger a display handoff.
1487 updateVrFlinger();
1488
Dan Stoza6b9454d2014-11-07 16:00:59 -08001489 bool refreshNeeded = handleMessageTransaction();
1490 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001491 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001492 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001493 // Signal a refresh if a transaction modified the window state,
1494 // a new buffer was latched, or if HWC has requested a full
1495 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001496 signalRefresh();
1497 }
1498 break;
1499 }
1500 case MessageQueue::REFRESH: {
1501 handleMessageRefresh();
1502 break;
1503 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001504 }
1505}
1506
Dan Stoza6b9454d2014-11-07 16:00:59 -08001507bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001508 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001509 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001510 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001511 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001512 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001513 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001514}
1515
Mathias Agopian4fec8732012-06-29 14:12:52 -07001516void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001517 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001518
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001519 mRefreshPending = false;
1520
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001521 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001522 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001523 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001524 calculateWorkingSet();
David Sodman10a41ff2018-08-05 12:14:17 -07001525
David Sodmanfa9b2af2017-12-24 13:28:59 -08001526 for (const auto& [token, display] : mDisplays) {
David Sodman10a41ff2018-08-05 12:14:17 -07001527 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001528 beginFrame(display);
David Sodman10a41ff2018-08-05 12:14:17 -07001529 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
1530 setUpHWComposer(compositionInfo);
1531 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001532 prepareFrame(display);
1533 doDebugFlashRegions(display, repaintEverything);
1534 doComposition(display, repaintEverything);
1535 }
1536
Adrian Roos1e1a1282017-11-01 19:05:31 +01001537 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001538 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001539
1540 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001541 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001542
Dan Stozabfbffeb2016-07-21 14:49:33 -07001543 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001544 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001545 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001546 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001547 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001548
Alec Mouri86770e52018-09-24 22:40:58 +00001549 // Setup RenderEngine sync fences if native sync is supported.
1550 if (getBE().mRenderEngine->useNativeFenceSync()) {
1551 if (mHadClientComposition) {
1552 base::unique_fd flushFence(getRenderEngine().flush());
1553 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1554 getBE().flushFence = new Fence(std::move(flushFence));
1555 } else {
1556 // Cleanup for hygiene.
1557 getBE().flushFence = Fence::NO_FENCE;
1558 }
1559 }
1560
Jorim Jaggi90535212018-05-23 23:44:06 +02001561 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001562
David Sodman7e4ae112018-02-09 15:02:28 -08001563 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001564 for (const auto& [token, display] : mDisplays) {
1565 const auto displayId = display->getId();
David Sodman7e4ae112018-02-09 15:02:28 -08001566 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[displayId]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001567 compositionInfo.hwc.hwcLayer = nullptr;
1568 }
David Sodmanba340492018-08-05 21:51:33 -07001569 }
David Sodman7e4ae112018-02-09 15:02:28 -08001570
1571 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001572}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001573
David Sodmanfa9b2af2017-12-24 13:28:59 -08001574
1575bool SurfaceFlinger::handleMessageInvalidate() {
1576 ATRACE_CALL();
1577 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001578}
1579
David Sodman79bba0e2018-08-05 18:07:49 -07001580void SurfaceFlinger::calculateWorkingSet() {
1581 ATRACE_CALL();
1582 ALOGV(__FUNCTION__);
1583
David Sodman79bba0e2018-08-05 18:07:49 -07001584 // build the h/w work list
1585 if (CC_UNLIKELY(mGeometryInvalid)) {
1586 mGeometryInvalid = false;
1587 for (const auto& [token, display] : mDisplays) {
1588 const auto displayId = display->getId();
1589 if (displayId >= 0) {
1590 const Vector<sp<Layer>>& currentLayers(
1591 display->getVisibleLayersSortedByZ());
1592 for (size_t i = 0; i < currentLayers.size(); i++) {
1593 const auto& layer = currentLayers[i];
1594
1595 if (!layer->hasHwcLayer(displayId)) {
1596 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1597 layer->forceClientComposition(displayId);
1598 continue;
1599 }
1600 }
1601
1602 layer->setGeometry(display, i);
1603 if (mDebugDisableHWC || mDebugRegion) {
1604 layer->forceClientComposition(displayId);
1605 }
1606 }
1607 }
1608 }
1609 }
1610
1611 // Set the per-frame data
1612 for (const auto& [token, display] : mDisplays) {
1613 const auto displayId = display->getId();
1614 if (displayId < 0) {
1615 continue;
1616 }
1617
1618 if (mDrawingState.colorMatrixChanged) {
1619 display->setColorTransform(mDrawingState.colorMatrix);
1620 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1621 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1622 "display %d: %d", displayId, result);
1623 }
1624 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1625 if (layer->isHdrY410()) {
1626 layer->forceClientComposition(displayId);
1627 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1628 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1629 !display->hasHDR10Support()) {
1630 layer->forceClientComposition(displayId);
1631 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1632 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1633 !display->hasHLGSupport()) {
1634 layer->forceClientComposition(displayId);
1635 }
1636
Peiyong Lind3788632018-09-18 16:01:31 -07001637 // TODO(b/111562338) remove when composer 2.3 is shipped.
1638 if (layer->hasColorTransform()) {
1639 layer->forceClientComposition(displayId);
1640 }
1641
David Sodman79bba0e2018-08-05 18:07:49 -07001642 if (layer->getForceClientComposition(displayId)) {
1643 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1644 layer->setCompositionType(displayId, HWC2::Composition::Client);
1645 continue;
1646 }
1647
1648 layer->setPerFrameData(display);
1649 }
1650
Peiyong Lin13effd12018-07-24 17:01:47 -07001651 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001652 ColorMode colorMode;
1653 Dataspace dataSpace;
1654 RenderIntent renderIntent;
1655 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1656 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1657 }
1658 }
1659
1660 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001661
1662 for (const auto& [token, display] : mDisplays) {
David Sodman15fb96e2018-01-07 10:23:24 -08001663 const auto displayId = display->getId();
1664 getBE().mCompositionInfo[displayId].clear();
David Sodmanba340492018-08-05 21:51:33 -07001665 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1666 auto displayId = display->getId();
1667 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1668 if (!layer->setHwcLayer(displayId)) {
1669 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1670 }
David Sodman15fb96e2018-01-07 10:23:24 -08001671 layer->getBE().compositionInfo.hwc.displayId = displayId;
1672 getBE().mCompositionInfo[displayId].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001673 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1674 }
1675 }
David Sodman79bba0e2018-08-05 18:07:49 -07001676}
1677
David Sodmanfa9b2af2017-12-24 13:28:59 -08001678void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001679{
David Sodmanfb95bcc2017-12-22 15:45:30 -08001680 const auto displayId = display->getId();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001681 // is debugging enabled
1682 if (CC_LIKELY(!mDebugRegion))
1683 return;
1684
David Sodmanfa9b2af2017-12-24 13:28:59 -08001685 if (display->isPoweredOn()) {
1686 // transform the dirty region into this screen's coordinate space
1687 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1688 if (!dirtyRegion.isEmpty()) {
1689 // redraw the whole screen
1690 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001691
David Sodmanfa9b2af2017-12-24 13:28:59 -08001692 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001693 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001694 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001695
David Sodmanfa9b2af2017-12-24 13:28:59 -08001696 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001697 }
1698 }
1699
David Sodmanfa9b2af2017-12-24 13:28:59 -08001700 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001701
1702 if (mDebugRegion > 1) {
1703 usleep(mDebugRegion * 1000);
1704 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001705
David Sodmanfa9b2af2017-12-24 13:28:59 -08001706 if (display->isPoweredOn()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08001707 status_t result = display->prepareFrame(
1708 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001709 ALOGE_IF(result != NO_ERROR,
1710 "prepareFrame for display %d failed:"
1711 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001712 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001713 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001714}
1715
Adrian Roos1e1a1282017-11-01 19:05:31 +01001716void SurfaceFlinger::doTracing(const char* where) {
1717 ATRACE_CALL();
1718 ATRACE_NAME(where);
1719 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001720 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001721 }
1722}
1723
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001724void SurfaceFlinger::logLayerStats() {
1725 ATRACE_CALL();
1726 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001727 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001728 if (display->isPrimary()) {
1729 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001730 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001731 }
1732 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001733
1734 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001735 }
1736}
1737
David Sodman2b406362017-12-15 13:33:47 -08001738void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001739{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001740 ATRACE_CALL();
1741 ALOGV("preComposition");
1742
David Sodman2b406362017-12-15 13:33:47 -08001743 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1744
Mathias Agopiancd60f992012-08-16 16:28:27 -07001745 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001746 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001747 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001748 needExtraInvalidate = true;
1749 }
Robert Carr2047fae2016-11-28 14:09:09 -08001750 });
1751
Mathias Agopiancd60f992012-08-16 16:28:27 -07001752 if (needExtraInvalidate) {
1753 signalLayerUpdate();
1754 }
1755}
1756
Ana Krulece588e312018-09-18 12:32:24 -07001757void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1758 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001759 // Update queue of past composite+present times and determine the
1760 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001761 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001762 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001763 while (!getBE().mCompositePresentTimes.empty()) {
1764 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001765 // Cached values should have been updated before calling this method,
1766 // which helps avoid duplicate syscalls.
1767 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1768 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1769 break;
1770 }
1771 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001772 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001773 }
1774
1775 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001776 while (getBE().mCompositePresentTimes.size() > 16) {
1777 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001778 }
1779
Ana Krulece588e312018-09-18 12:32:24 -07001780 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001781}
1782
Ana Krulece588e312018-09-18 12:32:24 -07001783void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1784 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001785 // Integer division and modulo round toward 0 not -inf, so we need to
1786 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001787 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1788 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1789 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001790
Brian Andersond0010582017-03-07 13:20:31 -08001791 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1792 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001793 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001794 }
1795
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001796 // Snap the latency to a value that removes scheduling jitter from the
1797 // composition and present times, which often have >1ms of jitter.
1798 // Reducing jitter is important if an app attempts to extrapolate
1799 // something (such as user input) to an accurate diasplay time.
1800 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1801 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001802 nsecs_t bias = stats.vsyncPeriod / 2;
1803 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1804 nsecs_t snappedCompositeToPresentLatency =
1805 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001806
David Sodman99974d22017-11-28 12:04:33 -08001807 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001808 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1809 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001810 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001811}
1812
David Sodman2b406362017-12-15 13:33:47 -08001813void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001814{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001815 ATRACE_CALL();
1816 ALOGV("postComposition");
1817
Brian Anderson3546a3f2016-07-14 11:51:14 -07001818 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001819 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001820 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001821 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001822 }
1823
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001824 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001825 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001826
David Sodman73beded2017-11-15 11:56:06 -08001827 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001828 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001829 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001830 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001831 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001832 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001833 } else {
1834 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1835 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001836
David Sodman73beded2017-11-15 11:56:06 -08001837 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001838 mPreviousPresentFence =
1839 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1840 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001841 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001842
Ana Krulece588e312018-09-18 12:32:24 -07001843 DisplayStatInfo stats;
1844 if (mUseScheduler) {
1845 mScheduler->getDisplayStatInfo(&stats);
1846 } else {
1847 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1848 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
1849 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001850
David Sodman2b406362017-12-15 13:33:47 -08001851 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001852 // when we started doing work for this frame, but that should be okay
1853 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07001854 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001855 CompositorTiming compositorTiming;
1856 {
David Sodman99974d22017-11-28 12:04:33 -08001857 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1858 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001859 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001860
Robert Carr2047fae2016-11-28 14:09:09 -08001861 mDrawingState.traverseInZOrder([&](Layer* layer) {
1862 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001863 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001864 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001865 recordBufferingStats(layer->getName().string(),
1866 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001867 }
Robert Carr2047fae2016-11-28 14:09:09 -08001868 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001869
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001870 if (presentFenceTime->isValid()) {
Ana Krulece588e312018-09-18 12:32:24 -07001871 if (mUseScheduler) {
1872 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001873 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001874 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
1875 enableHardwareVsync();
1876 } else {
1877 disableHardwareVsync(false);
1878 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001879 }
1880 }
1881
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001882 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001883 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07001884 if (mUseScheduler) {
1885 mScheduler->enableHardwareVsync();
1886 } else {
1887 enableHardwareVsync();
1888 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001889 }
1890 }
1891
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001892 if (mAnimCompositionPending) {
1893 mAnimCompositionPending = false;
1894
Brian Anderson4e606e32017-03-16 15:34:57 -07001895 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001896 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001897 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001898 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001899 // The HWC doesn't support present fences, so use the refresh
1900 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001901 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001902 mAnimFrameTracker.setActualPresentTime(presentTime);
1903 }
1904 mAnimFrameTracker.advanceFrame();
1905 }
Dan Stozab90cf072015-03-05 11:05:59 -08001906
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001907 mTimeStats.incrementTotalFrames();
1908 if (mHadClientComposition) {
1909 mTimeStats.incrementClientCompositionFrames();
1910 }
1911
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001912 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001913 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001914 return;
1915 }
1916
1917 nsecs_t currentTime = systemTime();
1918 if (mHasPoweredOff) {
1919 mHasPoweredOff = false;
1920 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001921 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001922 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001923 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1924 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001925 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001926 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001927 }
David Sodman4a36e932017-11-07 14:29:47 -08001928 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001929 }
David Sodman4a36e932017-11-07 14:29:47 -08001930 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001931
1932 {
1933 std::lock_guard lock(mTexturePoolMutex);
1934 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1935 if (refillCount > 0) {
1936 const size_t offset = mTexturePool.size();
1937 mTexturePool.resize(mTexturePoolSize);
1938 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1939 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1940 }
1941 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001942}
1943
1944void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001945 ATRACE_CALL();
1946 ALOGV("rebuildLayerStacks");
1947
Mathias Agopiancd60f992012-08-16 16:28:27 -07001948 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001949 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001950 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001951 mVisibleRegionsDirty = false;
1952 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001953
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001954 for (const auto& pair : mDisplays) {
1955 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001956 Region opaqueRegion;
1957 Region dirtyRegion;
1958 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001959 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001960 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001961 const Rect bounds = display->getBounds();
1962 if (display->isPoweredOn()) {
1963 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001964
Jeff Sharkey76488112017-02-27 14:15:18 -07001965 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001966 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001967 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001968 Region drawRegion(tr.transform(
1969 layer->visibleNonTransparentRegion));
1970 drawRegion.andSelf(bounds);
1971 if (!drawRegion.isEmpty()) {
1972 layersSortedByZ.add(layer);
1973 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001974 // Clear out the HWC layer if this layer was
1975 // previously visible, but no longer is
1976 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001977 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001978 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001979 // WM changes display->layerStack upon sleep/awake.
1980 // Here we make sure we delete the HWC layers even if
1981 // WM changed their layer stack.
1982 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001983 }
1984
1985 // If a layer is not going to get a release fence because
1986 // it is invisible, but it is also going to release its
1987 // old buffer, add it to the list of layers needing
1988 // fences.
1989 if (hwcLayerDestroyed) {
1990 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1991 mLayersWithQueuedFrames.cend(), layer);
1992 if (found != mLayersWithQueuedFrames.cend()) {
1993 layersNeedingFences.add(layer);
1994 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001995 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001996 });
1997 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001998 display->setVisibleLayersSortedByZ(layersSortedByZ);
1999 display->setLayersNeedingFences(layersNeedingFences);
2000 display->undefinedRegion.set(bounds);
2001 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2002 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002003 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002004 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002005}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002006
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002007// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002008// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002009// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002010// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002011// The returned HDR data space is one of
2012// - Dataspace::UNKNOWN
2013// - Dataspace::BT2020_HLG
2014// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002015Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2016 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07002017 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002018 *outHdrDataSpace = Dataspace::UNKNOWN;
2019
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002020 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002021 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002022 case Dataspace::V0_SCRGB:
2023 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002024 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002025 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002026 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002027 case Dataspace::BT2020_PQ:
2028 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002029 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002030 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002031 case Dataspace::BT2020_HLG:
2032 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002033 // When there's mixed PQ content and HLG content, we set the HDR
2034 // data space to be BT2020_PQ and convert HLG to PQ.
2035 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2036 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002037 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002038 break;
2039 default:
2040 break;
2041 }
Romain Guy54f154a2017-10-24 21:40:32 +01002042 }
2043
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002044 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002045}
2046
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002047// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002048void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2049 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002050 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2051 *outMode = ColorMode::NATIVE;
2052 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002053 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002054 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002055 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002056
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002057 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002058 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002059
Peiyong Lindfde5112018-06-05 10:58:41 -07002060 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002061 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002062 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002063 if (isHdr) {
2064 bestDataSpace = hdrDataSpace;
2065 }
2066
Chia-I Wu0d711262018-05-21 15:19:35 -07002067 RenderIntent intent;
2068 switch (mDisplayColorSetting) {
2069 case DisplayColorSetting::MANAGED:
2070 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002071 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002072 break;
2073 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002074 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002075 break;
2076 default: // vendor display color setting
2077 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2078 break;
2079 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002080
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002081 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002082}
2083
David Sodman10a41ff2018-08-05 12:14:17 -07002084void SurfaceFlinger::configureSidebandComposition(const CompositionInfo& compositionInfo) const
2085{
2086 HWC2::Error error;
2087 LOG_ALWAYS_FATAL_IF(compositionInfo.hwc.sidebandStream == nullptr,
2088 "CompositionType is sideband, but sideband stream is nullptr");
2089 error = (compositionInfo.hwc.hwcLayer)
2090 ->setSidebandStream(compositionInfo.hwc.sidebandStream->handle());
2091 if (error != HWC2::Error::None) {
2092 ALOGE("[SF] Failed to set sideband stream %p: %s (%d)",
2093 compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
2094 static_cast<int32_t>(error));
2095 }
2096}
2097
2098void SurfaceFlinger::configureHwcCommonData(const CompositionInfo& compositionInfo) const
2099{
2100 HWC2::Error error;
2101
2102 if (!compositionInfo.hwc.skipGeometry) {
2103 error = (compositionInfo.hwc.hwcLayer)->setBlendMode(compositionInfo.hwc.blendMode);
2104 ALOGE_IF(error != HWC2::Error::None,
2105 "[SF] Failed to set blend mode %s:"
2106 " %s (%d)",
2107 to_string(compositionInfo.hwc.blendMode).c_str(), to_string(error).c_str(),
2108 static_cast<int32_t>(error));
2109
2110 error = (compositionInfo.hwc.hwcLayer)->setDisplayFrame(compositionInfo.hwc.displayFrame);
2111 ALOGE_IF(error != HWC2::Error::None,
2112 "[SF] Failed to set the display frame [%d, %d, %d, %d] %s (%d)",
2113 compositionInfo.hwc.displayFrame.left,
2114 compositionInfo.hwc.displayFrame.right,
2115 compositionInfo.hwc.displayFrame.top,
2116 compositionInfo.hwc.displayFrame.bottom,
2117 to_string(error).c_str(), static_cast<int32_t>(error));
2118
2119 error = (compositionInfo.hwc.hwcLayer)->setSourceCrop(compositionInfo.hwc.sourceCrop);
2120 ALOGE_IF(error != HWC2::Error::None,
2121 "[SF] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: %s (%d)",
2122 compositionInfo.hwc.sourceCrop.left,
2123 compositionInfo.hwc.sourceCrop.right,
2124 compositionInfo.hwc.sourceCrop.top,
2125 compositionInfo.hwc.sourceCrop.bottom,
2126 to_string(error).c_str(), static_cast<int32_t>(error));
2127
2128 error = (compositionInfo.hwc.hwcLayer)->setPlaneAlpha(compositionInfo.hwc.alpha);
2129 ALOGE_IF(error != HWC2::Error::None,
2130 "[SF] Failed to set plane alpha %.3f: "
2131 "%s (%d)",
2132 compositionInfo.hwc.alpha,
2133 to_string(error).c_str(), static_cast<int32_t>(error));
2134
2135
2136 error = (compositionInfo.hwc.hwcLayer)->setZOrder(compositionInfo.hwc.z);
2137 ALOGE_IF(error != HWC2::Error::None,
2138 "[SF] Failed to set Z %u: %s (%d)",
2139 compositionInfo.hwc.z,
2140 to_string(error).c_str(), static_cast<int32_t>(error));
2141
2142 error = (compositionInfo.hwc.hwcLayer)
2143 ->setInfo(compositionInfo.hwc.type, compositionInfo.hwc.appId);
2144 ALOGE_IF(error != HWC2::Error::None,
2145 "[SF] Failed to set info (%d)",
2146 static_cast<int32_t>(error));
2147
2148 error = (compositionInfo.hwc.hwcLayer)->setTransform(compositionInfo.hwc.transform);
2149 ALOGE_IF(error != HWC2::Error::None,
2150 "[SF] Failed to set transform %s: "
2151 "%s (%d)",
2152 to_string(compositionInfo.hwc.transform).c_str(), to_string(error).c_str(),
2153 static_cast<int32_t>(error));
2154 }
2155
2156 error = (compositionInfo.hwc.hwcLayer)->setCompositionType(compositionInfo.compositionType);
2157 ALOGE_IF(error != HWC2::Error::None,
2158 "[SF] Failed to set composition type: %s (%d)",
2159 to_string(error).c_str(), static_cast<int32_t>(error));
2160
2161 error = (compositionInfo.hwc.hwcLayer)->setDataspace(compositionInfo.hwc.dataspace);
2162 ALOGE_IF(error != HWC2::Error::None,
2163 "[SF] Failed to set dataspace: %s (%d)",
2164 to_string(error).c_str(), static_cast<int32_t>(error));
2165
2166 error = (compositionInfo.hwc.hwcLayer)->setPerFrameMetadata(
2167 compositionInfo.hwc.supportedPerFrameMetadata, compositionInfo.hwc.hdrMetadata);
2168 ALOGE_IF(error != HWC2::Error::None && error != HWC2::Error::Unsupported,
2169 "[SF] Failed to set hdrMetadata: %s (%d)",
2170 to_string(error).c_str(), static_cast<int32_t>(error));
2171
2172 if (compositionInfo.compositionType == HWC2::Composition::SolidColor) {
2173 error = (compositionInfo.hwc.hwcLayer)->setColor(compositionInfo.hwc.color);
2174 ALOGE_IF(error != HWC2::Error::None,
2175 "[SF] Failed to set color: %s (%d)",
2176 to_string(error).c_str(), static_cast<int32_t>(error));
2177 }
2178
2179 error = (compositionInfo.hwc.hwcLayer)->setVisibleRegion(compositionInfo.hwc.visibleRegion);
2180 ALOGE_IF(error != HWC2::Error::None,
2181 "[SF] Failed to set visible region: %s (%d)",
2182 to_string(error).c_str(), static_cast<int32_t>(error));
2183
2184 error = (compositionInfo.hwc.hwcLayer)->setSurfaceDamage(compositionInfo.hwc.surfaceDamage);
2185 ALOGE_IF(error != HWC2::Error::None,
2186 "[SF] Failed to set surface damage: %s (%d)",
2187 to_string(error).c_str(), static_cast<int32_t>(error));
Peiyong Lind3788632018-09-18 16:01:31 -07002188
2189 error = (compositionInfo.hwc.hwcLayer)->setColorTransform(compositionInfo.hwc.colorTransform);
David Sodman10a41ff2018-08-05 12:14:17 -07002190}
2191
2192void SurfaceFlinger::configureDeviceComposition(const CompositionInfo& compositionInfo) const
2193{
2194 HWC2::Error error;
2195
2196 if (compositionInfo.hwc.fence) {
2197 error = (compositionInfo.hwc.hwcLayer)->setBuffer(compositionInfo.mBufferSlot,
2198 compositionInfo.mBuffer, compositionInfo.hwc.fence);
2199 ALOGE_IF(error != HWC2::Error::None,
2200 "[SF] Failed to set buffer: %s (%d)",
2201 to_string(error).c_str(), static_cast<int32_t>(error));
2202 }
2203}
2204
David Sodmanfa9b2af2017-12-24 13:28:59 -08002205void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002206{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002207 bool dirty = !display->getDirtyRegion(false).isEmpty();
2208 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2209 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002210
David Sodmanfa9b2af2017-12-24 13:28:59 -08002211 // If nothing has changed (!dirty), don't recompose.
2212 // If something changed, but we don't currently have any visible layers,
2213 // and didn't when we last did a composition, then skip it this time.
2214 // The second rule does two things:
2215 // - When all layers are removed from a display, we'll emit one black
2216 // frame, then nothing more until we get new layers.
2217 // - When a display is created with a private layer stack, we won't
2218 // emit any black frames until a layer is added to the layer stack.
2219 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002220
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002221 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2222 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002223 mustRecompose ? "doing" : "skipping",
2224 dirty ? "+" : "-",
2225 empty ? "+" : "-",
2226 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002227
David Sodmanfa9b2af2017-12-24 13:28:59 -08002228 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002229
David Sodmanfa9b2af2017-12-24 13:28:59 -08002230 if (mustRecompose) {
2231 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002232 }
2233}
2234
David Sodmanfa9b2af2017-12-24 13:28:59 -08002235void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002236{
David Sodmanfb95bcc2017-12-22 15:45:30 -08002237 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002238 if (!display->isPoweredOn()) {
2239 return;
David Sodman2b406362017-12-15 13:33:47 -08002240 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002241
David Sodmanfb95bcc2017-12-22 15:45:30 -08002242 status_t result = display->prepareFrame(
2243 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08002244 ALOGE_IF(result != NO_ERROR,
2245 "prepareFrame for display %d failed:"
2246 " %d (%s)",
2247 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002248}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002249
David Sodman10a41ff2018-08-05 12:14:17 -07002250void SurfaceFlinger::setUpHWComposer(const CompositionInfo& compositionInfo) {
2251 ATRACE_CALL();
2252 ALOGV("setUpHWComposer");
2253
2254 switch (compositionInfo.compositionType)
2255 {
2256 case HWC2::Composition::Invalid:
David Sodmana6d42332018-08-29 14:07:04 -07002257 break;
2258
David Sodman10a41ff2018-08-05 12:14:17 -07002259 case HWC2::Composition::Client:
David Sodmana6d42332018-08-29 14:07:04 -07002260 if (compositionInfo.hwc.hwcLayer) {
2261 auto error = (compositionInfo.hwc.hwcLayer)->
2262 setCompositionType(compositionInfo.compositionType);
2263 ALOGE_IF(error != HWC2::Error::None,
2264 "[SF] Failed to set composition type: %s (%d)",
2265 to_string(error).c_str(), static_cast<int32_t>(error));
2266 }
David Sodman10a41ff2018-08-05 12:14:17 -07002267 break;
2268
2269 case HWC2::Composition::Sideband:
2270 configureHwcCommonData(compositionInfo);
2271 configureSidebandComposition(compositionInfo);
2272 break;
2273
2274 case HWC2::Composition::SolidColor:
2275 configureHwcCommonData(compositionInfo);
2276 break;
2277
2278 case HWC2::Composition::Device:
2279 case HWC2::Composition::Cursor:
2280 configureHwcCommonData(compositionInfo);
2281 configureDeviceComposition(compositionInfo);
2282 break;
2283 }
2284}
2285
David Sodmanfa9b2af2017-12-24 13:28:59 -08002286void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002287 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002288 ALOGV("doComposition");
2289
David Sodmanfa9b2af2017-12-24 13:28:59 -08002290 if (display->isPoweredOn()) {
2291 // transform the dirty region into this screen's coordinate space
2292 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002293
David Sodmanfa9b2af2017-12-24 13:28:59 -08002294 // repaint the framebuffer (if needed)
2295 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002296
David Sodmanfa9b2af2017-12-24 13:28:59 -08002297 display->dirtyRegion.clear();
2298 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002299 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002300 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002301}
2302
David Sodmanfa9b2af2017-12-24 13:28:59 -08002303void SurfaceFlinger::postFrame()
2304{
2305 // |mStateLock| not needed as we are on the main thread
2306 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2307 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2308 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2309 logFrameStats();
2310 }
2311 }
2312}
2313
2314void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002315{
Mathias Agopian841cde52012-03-01 15:44:37 -08002316 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002317 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002318
David Sodmanfa9b2af2017-12-24 13:28:59 -08002319 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002320
David Sodmanfa9b2af2017-12-24 13:28:59 -08002321 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002322 const auto displayId = display->getId();
2323 if (displayId >= 0) {
2324 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002325 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002326 display->onSwapBuffersCompleted();
2327 display->makeCurrent();
David Sodman10a41ff2018-08-05 12:14:17 -07002328 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002329 sp<Fence> releaseFence = Fence::NO_FENCE;
Chia-I Wu7b549592017-11-15 09:14:57 -08002330 // The layer buffer from the previous frame (if any) is released
2331 // by HWC only when the release fence from this frame (if any) is
2332 // signaled. Always get the release fence from HWC first.
David Sodman10a41ff2018-08-05 12:14:17 -07002333 auto hwcLayer = compositionInfo.hwc.hwcLayer;
2334 if ((displayId >= 0) && hwcLayer) {
2335 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer.get());
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002336 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002337
2338 // If the layer was client composited in the previous frame, we
2339 // need to merge with the previous client target acquire fence.
2340 // Since we do not track that, always merge with the current
2341 // client target acquire fence when it is available, even though
2342 // this is suboptimal.
David Sodman10a41ff2018-08-05 12:14:17 -07002343 if (compositionInfo.compositionType == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002344 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002345 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002346 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002347
David Sodman10a41ff2018-08-05 12:14:17 -07002348 if (compositionInfo.layer) {
2349 compositionInfo.layer->onLayerDisplayed(releaseFence);
2350 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002351 }
Chia-I Wu83806892017-11-16 10:50:20 -08002352
2353 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002354 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002355 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002356 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002357 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002358 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002359 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002360 }
2361 }
2362
Dominik Laskowski7e045462018-05-30 13:02:02 -07002363 if (displayId >= 0) {
2364 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002365 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002366 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002367}
2368
Mathias Agopian87baae12012-07-31 12:38:26 -07002369void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002370{
Mathias Agopian841cde52012-03-01 15:44:37 -08002371 ATRACE_CALL();
2372
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002373 // here we keep a copy of the drawing state (that is the state that's
2374 // going to be overwritten by handleTransactionLocked()) outside of
2375 // mStateLock so that the side-effects of the State assignment
2376 // don't happen with mStateLock held (which can cause deadlocks).
2377 State drawingState(mDrawingState);
2378
Mathias Agopianca4d3602011-05-19 15:38:14 -07002379 Mutex::Autolock _l(mStateLock);
2380 const nsecs_t now = systemTime();
2381 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002382
Mathias Agopianca4d3602011-05-19 15:38:14 -07002383 // Here we're guaranteed that some transaction flags are set
2384 // so we can call handleTransactionLocked() unconditionally.
2385 // We call getTransactionFlags(), which will also clear the flags,
2386 // with mStateLock held to guarantee that mCurrentState won't change
2387 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002388
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002389 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002390 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002391 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002392
Mathias Agopianca4d3602011-05-19 15:38:14 -07002393 mLastTransactionTime = systemTime() - now;
2394 mDebugInTransaction = 0;
2395 invalidateHwcGeometry();
2396 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002397}
2398
Dominik Laskowski7e045462018-05-30 13:02:02 -07002399DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002400 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002401 // Figure out whether the event is for the primary display or an
2402 // external display by matching the Hwc display id against one for a
2403 // connected display. If we did not find a match, we then check what
2404 // displays are not already connected to determine the type. If we don't
2405 // have a connected primary display, we assume the new display is meant to
2406 // be the primary display, and then if we don't have an external display,
2407 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002408 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2409 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002410 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002411 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002412 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002413 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002414 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002415 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002416 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002417 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002418 return DisplayDevice::DISPLAY_EXTERNAL;
2419 }
2420
2421 return DisplayDevice::DISPLAY_ID_INVALID;
2422}
2423
Lloyd Piqueba04e622017-12-14 17:11:26 -08002424void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2425 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002426 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002427 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002428 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002429 continue;
2430 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002431
2432 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2433 ALOGE("External displays are not supported by the vr hardware composer.");
2434 continue;
2435 }
2436
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002437 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002438 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002439 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002440 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002441 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002442
2443 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002444 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002445 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002446 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002447 DisplayDeviceState info;
2448 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002449 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2450 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002451 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002452 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002453 mInterceptor->saveDisplayCreation(info);
2454 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002455 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002456 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002457
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002458 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002459 if (idx >= 0) {
2460 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002461 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002462 mCurrentState.displays.removeItemsAt(idx);
2463 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002464 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002465 }
2466
2467 processDisplayChangesLocked();
2468 }
2469
2470 mPendingHotplugEvents.clear();
2471}
2472
Lloyd Pique99d3da52018-01-22 17:48:03 -08002473sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002474 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002475 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002476 DisplayDeviceCreationArgs creationArgs(this, displayToken, state.type, displayId);
2477 creationArgs.isSecure = state.isSecure;
2478 creationArgs.displaySurface = dispSurface;
2479 creationArgs.hasWideColorGamut = false;
2480 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002481
Peiyong Lin13effd12018-07-24 17:01:47 -07002482 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002483 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002484 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002485 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002486 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002487 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002488
Dominik Laskowski7e045462018-05-30 13:02:02 -07002489 std::vector<RenderIntent> renderIntents =
2490 getHwComposer().getRenderIntents(displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002491 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002492 }
tangrobin6753a022018-08-10 10:58:54 +08002493 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002494
tangrobin6753a022018-08-10 10:58:54 +08002495 if (displayId >= 0) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002496 getHwComposer().getHdrCapabilities(displayId, &creationArgs.hdrCapabilities);
2497 creationArgs.supportedPerFrameMetadata =
2498 getHwComposer().getSupportedPerFrameMetadata(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002499 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002500
2501 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2502 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002503 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002504
2505 /*
2506 * Create our display's surface
2507 */
Peiyong Lin833074a2018-08-28 11:53:54 -07002508 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002509 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002510 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002511 renderSurface->setNativeWindow(nativeWindow.get());
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002512 creationArgs.displayWidth = renderSurface->getWidth();
2513 creationArgs.displayHeight = renderSurface->getHeight();
2514 creationArgs.renderSurface = std::move(renderSurface);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002515
2516 // Make sure that composition can never be stalled by a virtual display
2517 // consumer that isn't processing buffers fast enough. We have to do this
2518 // in two places:
2519 // * Here, in case the display is composed entirely by HWC.
2520 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2521 // window's swap interval in eglMakeCurrent, so they'll override the
2522 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002523 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002524 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2525 }
2526
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002527 creationArgs.displayInstallOrientation = state.type == DisplayDevice::DISPLAY_PRIMARY
2528 ? primaryDisplayOrientation
2529 : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002530
Lloyd Pique99d3da52018-01-22 17:48:03 -08002531 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002532 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002533
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002534 sp<DisplayDevice> display = new DisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002535
2536 if (maxFrameBufferAcquiredBuffers >= 3) {
2537 nativeWindowSurface->preallocateBuffers();
2538 }
2539
2540 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002541 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002542 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002543 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002544 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002545 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002546 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002547 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002548 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002549 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002550 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002551 display->setLayerStack(state.layerStack);
2552 display->setProjection(state.orientation, state.viewport, state.frame);
2553 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002554
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002555 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002556}
2557
Lloyd Pique347200f2017-12-14 17:00:15 -08002558void SurfaceFlinger::processDisplayChangesLocked() {
2559 // here we take advantage of Vector's copy-on-write semantics to
2560 // improve performance by skipping the transaction entirely when
2561 // know that the lists are identical
2562 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2563 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2564 if (!curr.isIdenticalTo(draw)) {
2565 mVisibleRegionsDirty = true;
2566 const size_t cc = curr.size();
2567 size_t dc = draw.size();
2568
2569 // find the displays that were removed
2570 // (ie: in drawing state but not in current state)
2571 // also handle displays that changed
2572 // (ie: displays that are in both lists)
2573 for (size_t i = 0; i < dc;) {
2574 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2575 if (j < 0) {
2576 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002577 // Call makeCurrent() on the primary display so we can
2578 // be sure that nothing associated with this display
2579 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002580 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2581 defaultDisplay->makeCurrent();
2582 }
2583 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2584 display->disconnect(getHwComposer());
2585 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002586 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002587 if (mUseScheduler) {
2588 mScheduler->hotplugReceived(mAppConnectionHandle,
2589 EventThread::DisplayType::Primary, false);
2590 } else {
2591 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2592 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002593 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002594 if (mUseScheduler) {
2595 mScheduler->hotplugReceived(mAppConnectionHandle,
2596 EventThread::DisplayType::External, false);
2597 } else {
2598 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2599 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002600 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002601 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002602 } else {
2603 // this display is in both lists. see if something changed.
2604 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002605 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002606 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2607 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2608 if (state_binder != draw_binder) {
2609 // changing the surface is like destroying and
2610 // recreating the DisplayDevice, so we just remove it
2611 // from the drawing state, so that it get re-added
2612 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002613 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2614 display->disconnect(getHwComposer());
2615 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002616 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002617 mDrawingState.displays.removeItemsAt(i);
2618 dc--;
2619 // at this point we must loop to the next item
2620 continue;
2621 }
2622
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002623 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002624 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002625 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002626 }
2627 if ((state.orientation != draw[i].orientation) ||
2628 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002629 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002630 }
2631 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002632 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002633 }
2634 }
2635 }
2636 ++i;
2637 }
2638
2639 // find displays that were added
2640 // (ie: in current state but not in drawing state)
2641 for (size_t i = 0; i < cc; i++) {
2642 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2643 const DisplayDeviceState& state(curr[i]);
2644
2645 sp<DisplaySurface> dispSurface;
2646 sp<IGraphicBufferProducer> producer;
2647 sp<IGraphicBufferProducer> bqProducer;
2648 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002649 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002650
Dominik Laskowski7e045462018-05-30 13:02:02 -07002651 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002652 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002653 // Virtual displays without a surface are dormant:
2654 // they have external state (layer stack, projection,
2655 // etc.) but no internal state (i.e. a DisplayDevice).
2656 if (state.surface != nullptr) {
2657 // Allow VR composer to use virtual displays.
2658 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2659 int width = 0;
2660 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2661 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2662 int height = 0;
2663 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2664 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2665 int intFormat = 0;
2666 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2667 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002668 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002669
Dominik Laskowski7e045462018-05-30 13:02:02 -07002670 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2671 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002672 }
2673
2674 // TODO: Plumb requested format back up to consumer
2675
2676 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002677 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002678 bqProducer, bqConsumer,
2679 state.displayName);
2680
2681 dispSurface = vds;
2682 producer = vds;
2683 }
2684 } else {
2685 ALOGE_IF(state.surface != nullptr,
2686 "adding a supported display, but rendering "
2687 "surface is provided (%p), ignoring it",
2688 state.surface.get());
2689
Dominik Laskowski7e045462018-05-30 13:02:02 -07002690 displayId = state.type;
2691 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002692 producer = bqProducer;
2693 }
2694
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002695 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002696 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002697 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002698 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002699 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002700 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002701 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002702 if (mUseScheduler) {
2703 mScheduler->hotplugReceived(mAppConnectionHandle,
2704 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002705 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002706 } else {
2707 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2708 true);
2709 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002710 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002711 if (mUseScheduler) {
2712 mScheduler->hotplugReceived(mAppConnectionHandle,
2713 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002714 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002715 } else {
2716 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2717 true);
2718 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002719 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002720 }
2721 }
2722 }
2723 }
2724 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002725
2726 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002727}
2728
Mathias Agopian87baae12012-07-31 12:38:26 -07002729void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002730{
Dan Stoza7dde5992015-05-22 09:51:44 -07002731 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002732 mCurrentState.traverseInZOrder([](Layer* layer) {
2733 layer->notifyAvailableFrames();
2734 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002735
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002736 /*
2737 * Traversal of the children
2738 * (perform the transaction for each of them if needed)
2739 */
2740
Mathias Agopian3559b072012-08-15 13:46:03 -07002741 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002742 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002743 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002744 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002745
2746 const uint32_t flags = layer->doTransaction(0);
2747 if (flags & Layer::eVisibleRegion)
2748 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002749 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002750 }
2751
2752 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002753 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002754 */
2755
Mathias Agopiane57f2922012-08-09 16:29:12 -07002756 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002757 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002758 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002759 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002760
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002761 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002762 // The transform hint might have changed for some layers
2763 // (either because a display has changed, or because a layer
2764 // as changed).
2765 //
2766 // Walk through all the layers in currentLayers,
2767 // and update their transform hint.
2768 //
2769 // If a layer is visible only on a single display, then that
2770 // display is used to calculate the hint, otherwise we use the
2771 // default display.
2772 //
2773 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2774 // the hint is set before we acquire a buffer from the surface texture.
2775 //
2776 // NOTE: layer transactions have taken place already, so we use their
2777 // drawing state. However, SurfaceFlinger's own transaction has not
2778 // happened yet, so we must use the current state layer list
2779 // (soon to become the drawing state list).
2780 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002781 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002782 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002783 bool first = true;
2784 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002785 // NOTE: we rely on the fact that layers are sorted by
2786 // layerStack first (so we don't have to traverse the list
2787 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002788 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002789 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002790 currentlayerStack = layerStack;
2791 // figure out if this layerstack is mirrored
2792 // (more than one display) if so, pick the default display,
2793 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002794 hintDisplay = nullptr;
2795 for (const auto& [token, display] : mDisplays) {
2796 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2797 if (hintDisplay) {
2798 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002799 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002800 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002801 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002802 }
2803 }
2804 }
2805 }
Chet Haase91d25932013-04-11 15:24:55 -07002806
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002807 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002808 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2809 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002810
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002811 // could be null when this layer is using a layerStack
2812 // that is not visible on any display. Also can occur at
2813 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002814 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002815 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002816
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002817 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002818 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002819 if (hintDisplay) {
2820 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002821 }
Robert Carr2047fae2016-11-28 14:09:09 -08002822
2823 first = false;
2824 });
Mathias Agopian84300952012-11-21 16:02:13 -08002825 }
2826
2827
Mathias Agopian3559b072012-08-15 13:46:03 -07002828 /*
2829 * Perform our own transaction if needed
2830 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002831
2832 if (mLayersAdded) {
2833 mLayersAdded = false;
2834 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002835 mVisibleRegionsDirty = true;
2836 }
2837
2838 // some layers might have been removed, so
2839 // we need to update the regions they're exposing.
2840 if (mLayersRemoved) {
2841 mLayersRemoved = false;
2842 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002843 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002844 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002845 // this layer is not visible anymore
2846 // TODO: we could traverse the tree from front to back and
2847 // compute the actual visible region
2848 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002849 Region visibleReg;
2850 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002851 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002852 }
Robert Carr2047fae2016-11-28 14:09:09 -08002853 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002854 }
2855
2856 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002857
2858 updateCursorAsync();
2859}
2860
2861void SurfaceFlinger::updateCursorAsync()
2862{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002863 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002864 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002865 continue;
2866 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002867
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002868 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2869 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002870 }
2871 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002872}
2873
2874void SurfaceFlinger::commitTransaction()
2875{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002876 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002877 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002878 for (const auto& l : mLayersPendingRemoval) {
2879 recordBufferingStats(l->getName().string(),
2880 l->getOccupancyHistory(true));
2881 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002882 }
2883 mLayersPendingRemoval.clear();
2884 }
2885
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002886 // If this transaction is part of a window animation then the next frame
2887 // we composite should be considered an animation as well.
2888 mAnimCompositionPending = mAnimTransactionPending;
2889
Mathias Agopian4fec8732012-06-29 14:12:52 -07002890 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002891 // clear the "changed" flags in current state
2892 mCurrentState.colorMatrixChanged = false;
2893
Robert Carr1f0a16a2016-10-24 16:27:39 -07002894 mDrawingState.traverseInZOrder([](Layer* layer) {
2895 layer->commitChildList();
2896 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002897 mTransactionPending = false;
2898 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002899 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002900}
2901
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002902void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2903 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002904 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002905 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002906
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002907 Region aboveOpaqueLayers;
2908 Region aboveCoveredLayers;
2909 Region dirty;
2910
Mathias Agopian87baae12012-07-31 12:38:26 -07002911 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002912
Robert Carr2047fae2016-11-28 14:09:09 -08002913 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002914 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002915 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002916
Jesse Hall01e29052013-02-19 16:13:35 -08002917 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002918 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002919 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002920 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002921
Mathias Agopianab028732010-03-16 16:41:46 -07002922 /*
2923 * opaqueRegion: area of a surface that is fully opaque.
2924 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002925 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002926
2927 /*
2928 * visibleRegion: area of a surface that is visible on screen
2929 * and not fully transparent. This is essentially the layer's
2930 * footprint minus the opaque regions above it.
2931 * Areas covered by a translucent surface are considered visible.
2932 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002933 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002934
2935 /*
2936 * coveredRegion: area of a surface that is covered by all
2937 * visible regions above it (which includes the translucent areas).
2938 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002939 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002940
Jesse Halla8026d22012-09-25 13:25:04 -07002941 /*
2942 * transparentRegion: area of a surface that is hinted to be completely
2943 * transparent. This is only used to tell when the layer has no visible
2944 * non-transparent regions and can be removed from the layer list. It
2945 * does not affect the visibleRegion of this layer or any layers
2946 * beneath it. The hint may not be correct if apps don't respect the
2947 * SurfaceView restrictions (which, sadly, some don't).
2948 */
2949 Region transparentRegion;
2950
Mathias Agopianab028732010-03-16 16:41:46 -07002951
2952 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002953 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002954 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002955 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002956 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002957 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002958 if (!visibleRegion.isEmpty()) {
2959 // Remove the transparent area from the visible region
2960 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002961 if (tr.preserveRects()) {
2962 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002963 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002964 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002965 // transformation too complex, can't do the
2966 // transparent region optimization.
2967 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002968 }
Mathias Agopianab028732010-03-16 16:41:46 -07002969 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002970
Mathias Agopianab028732010-03-16 16:41:46 -07002971 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002972 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002973 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002974 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002975 // the opaque region is the layer's footprint
2976 opaqueRegion = visibleRegion;
2977 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002978 }
2979 }
2980
Robert Carre5f4f692018-01-12 13:12:28 -08002981 if (visibleRegion.isEmpty()) {
2982 layer->clearVisibilityRegions();
2983 return;
2984 }
2985
Mathias Agopianab028732010-03-16 16:41:46 -07002986 // Clip the covered region to the visible region
2987 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2988
2989 // Update aboveCoveredLayers for next (lower) layer
2990 aboveCoveredLayers.orSelf(visibleRegion);
2991
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002992 // subtract the opaque region covered by the layers above us
2993 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002994
2995 // compute this layer's dirty region
2996 if (layer->contentDirty) {
2997 // we need to invalidate the whole region
2998 dirty = visibleRegion;
2999 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003000 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003001 layer->contentDirty = false;
3002 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003003 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003004 * the exposed region consists of two components:
3005 * 1) what's VISIBLE now and was COVERED before
3006 * 2) what's EXPOSED now less what was EXPOSED before
3007 *
3008 * note that (1) is conservative, we start with the whole
3009 * visible region but only keep what used to be covered by
3010 * something -- which mean it may have been exposed.
3011 *
3012 * (2) handles areas that were not covered by anything but got
3013 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003014 */
Mathias Agopianab028732010-03-16 16:41:46 -07003015 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003016 const Region oldVisibleRegion = layer->visibleRegion;
3017 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003018 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3019 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003020 }
3021 dirty.subtractSelf(aboveOpaqueLayers);
3022
3023 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003024 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003025
Mathias Agopianab028732010-03-16 16:41:46 -07003026 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003027 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003028
Jesse Halla8026d22012-09-25 13:25:04 -07003029 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003030 layer->setVisibleRegion(visibleRegion);
3031 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003032 layer->setVisibleNonTransparentRegion(
3033 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003034 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003035
Mathias Agopian87baae12012-07-31 12:38:26 -07003036 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003037}
3038
Chia-I Wuab0c3192017-08-01 11:29:00 -07003039void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003040 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003041 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
3042 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003043 }
3044 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003045}
3046
Dan Stoza6b9454d2014-11-07 16:00:59 -08003047bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003048{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003049 ALOGV("handlePageFlip");
3050
Brian Andersond6927fb2016-07-23 23:37:30 -07003051 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003052
Mathias Agopian4fec8732012-06-29 14:12:52 -07003053 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003054 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003055 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003056
3057 // Store the set of layers that need updates. This set must not change as
3058 // buffers are being latched, as this could result in a deadlock.
3059 // Example: Two producers share the same command stream and:
3060 // 1.) Layer 0 is latched
3061 // 2.) Layer 0 gets a new frame
3062 // 2.) Layer 1 gets a new frame
3063 // 3.) Layer 1 is latched.
3064 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3065 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003066 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003067 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003068 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003069 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3070 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003071 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003072 } else {
3073 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003074 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003075 } else {
3076 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003077 }
Robert Carr2047fae2016-11-28 14:09:09 -08003078 });
3079
Dan Stoza9e56aa02015-11-02 13:00:03 -08003080 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri86770e52018-09-24 22:40:58 +00003081 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
Dan Stozaee44edd2015-03-23 15:50:23 -07003082 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003083 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07003084 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06003085 newDataLatched = true;
3086 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003087 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003088
Alec Mouri86770e52018-09-24 22:40:58 +00003089 // Clear the renderengine fence here...
3090 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3091 // clear instead of sp::clear.
3092 getBE().flushFence = Fence::NO_FENCE;
3093
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003094 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003095
3096 // If we will need to wake up at some time in the future to deal with a
3097 // queued frame that shouldn't be displayed during this vsync period, wake
3098 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003099 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003100 signalLayerUpdate();
3101 }
3102
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003103 // enter boot animation on first buffer latch
3104 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3105 ALOGI("Enter boot animation");
3106 mBootStage = BootStage::BOOTANIMATION;
3107 }
3108
Dan Stoza6b9454d2014-11-07 16:00:59 -08003109 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003110 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003111}
3112
Mathias Agopianad456f92011-01-13 17:53:01 -08003113void SurfaceFlinger::invalidateHwcGeometry()
3114{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003115 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003116}
3117
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003118void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
3119 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003120 // We only need to actually compose the display if:
3121 // 1) It is being handled by hardware composer, which may need this to
3122 // keep its virtual display state machine in sync, or
3123 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07003124 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08003125 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003126 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003127 return;
3128 }
3129
Dan Stoza9e56aa02015-11-02 13:00:03 -08003130 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003131 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003132
3133 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003134 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003135}
3136
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003137bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003138 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003139
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003140 const Region bounds(display->bounds());
3141 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003142 const auto displayId = display->getId();
3143 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003144 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003145
Peiyong Lind3788632018-09-18 16:01:31 -07003146 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003147 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003148 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003149
Dan Stoza9e56aa02015-11-02 13:00:03 -08003150 if (hasClientComposition) {
3151 ALOGV("hasClientComposition");
3152
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003153 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003154 if (display->hasWideColorGamut()) {
3155 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003156 }
3157 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003158 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003159 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003160
Dominik Laskowski7e045462018-05-30 13:02:02 -07003161 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003162 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3163 HWC2::Capability::SkipClientColorTransform);
3164
Peiyong Lind3788632018-09-18 16:01:31 -07003165 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003166 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3167 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003168 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003169 }
3170
Chia-I Wud49d6692018-06-27 07:17:41 +08003171 // The current enhanced saturation matrix is designed to enhance Display P3,
3172 // thus we only apply this matrix when the render intent is not colorimetric
3173 // and the output color space is Display P3.
3174 needsEnhancedColorMatrix =
3175 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3176 outputDataspace == Dataspace::DISPLAY_P3);
3177 if (needsEnhancedColorMatrix) {
3178 colorMatrix *= mEnhancedSaturationMatrix;
3179 }
3180
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003181 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003182 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003183 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003184 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003185
3186 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003187 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3188 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3189 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003190 }
3191 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003192 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003193
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003194 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003195 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003196 // when using overlays, we assume a fully transparent framebuffer
3197 // NOTE: we could reduce how much we need to clear, for instance
3198 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003199 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003200 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003201 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003202 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003203 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003204 // we're left with the letterbox region
3205 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003206 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003207
3208 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003209 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003210
Mathias Agopianb9494d52012-04-18 02:28:45 -07003211 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003212 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003213 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003214 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003215 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003216 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003217
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003218 const Rect& bounds = display->getBounds();
3219 const Rect& scissor = display->getScissor();
3220 if (scissor != bounds) {
3221 // scissor doesn't match the screen's dimensions, so we
3222 // need to clear everything outside of it and enable
3223 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003224
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003225 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003226 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003227 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003228 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003229
Mathias Agopian85d751c2012-08-29 16:59:24 -07003230 /*
3231 * and then, render the layers targeted at the framebuffer
3232 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003233
Dan Stoza9e56aa02015-11-02 13:00:03 -08003234 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003235 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003236 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003237 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003238 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003239 displayTransform.transform(layer->visibleRegion)));
3240 ALOGV("Layer: %s", layer->getName().string());
3241 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003242 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003243 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003244 case HWC2::Composition::Cursor:
3245 case HWC2::Composition::Device:
3246 case HWC2::Composition::Sideband:
3247 case HWC2::Composition::SolidColor: {
David Sodmanc1498e62018-09-12 14:36:26 -07003248 const Layer::State& state(layer->getDrawingState());
3249 if (layer->getClearClientTarget(displayId) && !firstLayer &&
3250 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3251 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003252 // never clear the very first layer since we're
3253 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003254 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003255 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003256 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003257 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003258 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003259 if (layer->hasColorTransform()) {
3260 mat4 tmpMatrix;
3261 if (applyColorMatrix) {
3262 tmpMatrix = mDrawingState.colorMatrix;
3263 }
3264 tmpMatrix *= layer->getColorTransform();
3265 if (needsEnhancedColorMatrix) {
3266 tmpMatrix *= mEnhancedSaturationMatrix;
3267 }
3268 getRenderEngine().setColorTransform(tmpMatrix);
3269 } else {
3270 getRenderEngine().setColorTransform(colorMatrix);
3271 }
David Sodmanc1498e62018-09-12 14:36:26 -07003272 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003273 break;
3274 }
3275 default:
3276 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003277 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003278 } else {
3279 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003280 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003281 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003282 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003283
Peiyong Lind3788632018-09-18 16:01:31 -07003284 // Clear color transform matrix at the end of the frame.
3285 getRenderEngine().setColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003286
Mathias Agopianf45c5102012-10-24 16:29:17 -07003287 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003288 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003289 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003290}
3291
Chia-I Wu28e3a252018-09-07 12:05:02 -07003292void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003293 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003294 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003295}
3296
Dan Stoza7d89d062015-04-30 13:29:25 -07003297status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003298 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003299 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003300 const sp<Layer>& lbc,
3301 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003302{
Dan Stoza7d89d062015-04-30 13:29:25 -07003303 // add this layer to the current state list
3304 {
3305 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003306 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003307 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3308 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003309 return NO_MEMORY;
3310 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003311 if (parent == nullptr) {
3312 mCurrentState.layersSortedByZ.add(lbc);
3313 } else {
Rob Carr4bba3702018-10-08 21:53:30 +00003314 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003315 ALOGE("addClientLayer called with a removed parent");
3316 return NAME_NOT_FOUND;
3317 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003318 parent->addChild(lbc);
3319 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003320
Yiwei Zhang243b3782018-05-15 17:40:04 -07003321 if (gbc != nullptr) {
3322 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3323 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3324 mMaxGraphicBufferProducerListSize,
3325 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3326 mGraphicBufferProducerList.size(),
3327 mMaxGraphicBufferProducerListSize, mNumLayers);
3328 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003329 mLayersAdded = true;
3330 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003331 }
3332
Mathias Agopian96f08192010-06-02 23:28:45 -07003333 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003334 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003335
Dan Stoza7d89d062015-04-30 13:29:25 -07003336 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003337}
3338
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003339status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003340 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003341 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3342}
Robert Carr7f9b8992017-03-10 11:08:39 -08003343
chaviwca27f252018-02-06 16:46:39 -08003344status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3345 bool topLevelOnly) {
Rob Carr4bba3702018-10-08 21:53:30 +00003346 if (layer->isPendingRemoval()) {
chaviw8b3871a2017-11-01 17:41:01 -07003347 return NO_ERROR;
3348 }
3349
Robert Carr1f0a16a2016-10-24 16:27:39 -07003350 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003351 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003352 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003353 if (topLevelOnly) {
3354 return NO_ERROR;
3355 }
Rob Carr4bba3702018-10-08 21:53:30 +00003356
3357 sp<Layer> ancestor = p;
3358 while (ancestor->getParent() != nullptr) {
3359 ancestor = ancestor->getParent();
3360 }
3361 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3362 ALOGE("removeLayer called with a layer whose parent has been removed");
3363 return NAME_NOT_FOUND;
3364 }
3365
Chia-I Wufae51c42017-06-15 12:53:59 -07003366 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003367 } else {
3368 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003369 }
3370
Rob Carr4bba3702018-10-08 21:53:30 +00003371 // As a matter of normal operation, the LayerCleaner will produce a second
3372 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3373 // so we will succeed in promoting it, but it's already been removed
3374 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3375 // otherwise something has gone wrong and we are leaking the layer.
3376 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
3377 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3378 layer->getName().string(),
3379 (p != nullptr) ? p->getName().string() : "no-parent");
3380 return BAD_VALUE;
3381 } else if (index < 0) {
3382 return NO_ERROR;
3383 }
3384
Chia-I Wuc6657022017-08-15 11:18:17 -07003385 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003386 mLayersPendingRemoval.add(layer);
3387 mLayersRemoved = true;
Rob Carr4bba3702018-10-08 21:53:30 +00003388 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003389 setTransactionFlags(eTransactionNeeded);
3390 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003391}
3392
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003393uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003394 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003395}
3396
Mathias Agopian3f844832013-08-07 21:24:32 -07003397uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003398 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003399}
3400
Mathias Agopian3f844832013-08-07 21:24:32 -07003401uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003402 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003403}
3404
3405uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003406 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003407 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003408 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003409 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003410 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003411 }
3412 return old;
3413}
3414
chaviwca27f252018-02-06 16:46:39 -08003415bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3416 for (const ComposerState& state : states) {
3417 // Here we need to check that the interface we're given is indeed
3418 // one of our own. A malicious client could give us a nullptr
3419 // IInterface, or one of its own or even one of our own but a
3420 // different type. All these situations would cause us to crash.
3421 if (state.client == nullptr) {
3422 return true;
3423 }
3424
3425 sp<IBinder> binder = IInterface::asBinder(state.client);
3426 if (binder == nullptr) {
3427 return true;
3428 }
3429
3430 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3431 return true;
3432 }
3433 }
3434 return false;
3435}
3436
Mathias Agopian8b33f032012-07-24 20:43:54 -07003437void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003438 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003439 const Vector<DisplayState>& displays,
3440 uint32_t flags)
3441{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003442 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003443 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003444 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003445
chaviwca27f252018-02-06 16:46:39 -08003446 if (containsAnyInvalidClientState(states)) {
3447 return;
3448 }
3449
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003450 if (flags & eAnimation) {
3451 // For window updates that are part of an animation we must wait for
3452 // previous animation "frames" to be handled.
3453 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003454 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003455 if (CC_UNLIKELY(err != NO_ERROR)) {
3456 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003457 // caller after a few seconds.
3458 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3459 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003460 mAnimTransactionPending = false;
3461 break;
3462 }
3463 }
3464 }
3465
chaviwca27f252018-02-06 16:46:39 -08003466 for (const DisplayState& display : displays) {
3467 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003468 }
3469
chaviwca27f252018-02-06 16:46:39 -08003470 for (const ComposerState& state : states) {
3471 transactionFlags |= setClientStateLocked(state);
3472 }
3473
3474 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3475 // as destroyed should only occur after setting all other states. This is to allow for a
3476 // child re-parent to happen before marking its original parent as destroyed (which would
3477 // then mark the child as destroyed).
3478 for (const ComposerState& state : states) {
3479 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003480 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003481
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003482 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3483 // anyway. This can be used as a flush mechanism for previous async transactions.
3484 // Empty animation transaction can be used to simulate back-pressure, so also force a
3485 // transaction for empty animation transactions.
3486 if (transactionFlags == 0 &&
3487 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003488 transactionFlags = eTransactionNeeded;
3489 }
3490
Mathias Agopian386aa982011-11-07 21:58:03 -08003491 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003492 if (mInterceptor->isEnabled()) {
3493 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003494 }
Irvel468051e2016-06-13 16:44:44 -07003495
Mathias Agopian386aa982011-11-07 21:58:03 -08003496 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003497 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3498 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003499 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003500
3501 // if this is a synchronous transaction, wait for it to take effect
3502 // before returning.
3503 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003504 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003505 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003506 if (flags & eAnimation) {
3507 mAnimTransactionPending = true;
3508 }
3509 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003510 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3511 if (CC_UNLIKELY(err != NO_ERROR)) {
3512 // just in case something goes wrong in SF, return to the
3513 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003514 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3515 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003516 break;
3517 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003518 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003519 }
3520}
3521
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003522uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3523 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3524 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003525
Mathias Agopiane57f2922012-08-09 16:29:12 -07003526 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003527 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3528
3529 const uint32_t what = s.what;
3530 if (what & DisplayState::eSurfaceChanged) {
3531 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3532 state.surface = s.surface;
3533 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003534 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003535 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003536 if (what & DisplayState::eLayerStackChanged) {
3537 if (state.layerStack != s.layerStack) {
3538 state.layerStack = s.layerStack;
3539 flags |= eDisplayTransactionNeeded;
3540 }
3541 }
3542 if (what & DisplayState::eDisplayProjectionChanged) {
3543 if (state.orientation != s.orientation) {
3544 state.orientation = s.orientation;
3545 flags |= eDisplayTransactionNeeded;
3546 }
3547 if (state.frame != s.frame) {
3548 state.frame = s.frame;
3549 flags |= eDisplayTransactionNeeded;
3550 }
3551 if (state.viewport != s.viewport) {
3552 state.viewport = s.viewport;
3553 flags |= eDisplayTransactionNeeded;
3554 }
3555 }
3556 if (what & DisplayState::eDisplaySizeChanged) {
3557 if (state.width != s.width) {
3558 state.width = s.width;
3559 flags |= eDisplayTransactionNeeded;
3560 }
3561 if (state.height != s.height) {
3562 state.height = s.height;
3563 flags |= eDisplayTransactionNeeded;
3564 }
3565 }
3566
Mathias Agopiane57f2922012-08-09 16:29:12 -07003567 return flags;
3568}
3569
Robert Carrd4ae7f32018-06-07 16:10:57 -07003570bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3571 IPCThreadState* ipc = IPCThreadState::self();
3572 const int pid = ipc->getCallingPid();
3573 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003574 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003575 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003576 return false;
3577 }
3578 return true;
3579}
3580
chaviwca27f252018-02-06 16:46:39 -08003581uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3582 const layer_state_t& s = composerState.state;
3583 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3584
Mathias Agopian13127d82013-03-05 17:47:11 -08003585 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003586 if (layer == nullptr) {
3587 return 0;
3588 }
3589
Rob Carr4bba3702018-10-08 21:53:30 +00003590 if (layer->isPendingRemoval()) {
chaviw8b3871a2017-11-01 17:41:01 -07003591 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3592 return 0;
3593 }
3594
3595 uint32_t flags = 0;
3596
3597 const uint32_t what = s.what;
3598 bool geometryAppliesWithResize =
3599 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003600
3601 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3602 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003603 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003604 layer->pushPendingState();
3605 }
3606
chaviw8b3871a2017-11-01 17:41:01 -07003607 if (what & layer_state_t::ePositionChanged) {
3608 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3609 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003610 }
chaviw8b3871a2017-11-01 17:41:01 -07003611 }
3612 if (what & layer_state_t::eLayerChanged) {
3613 // NOTE: index needs to be calculated before we update the state
3614 const auto& p = layer->getParent();
3615 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003616 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003617 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003618 mCurrentState.layersSortedByZ.removeAt(idx);
3619 mCurrentState.layersSortedByZ.add(layer);
3620 // we need traversal (state changed)
3621 // AND transaction (list changed)
3622 flags |= eTransactionNeeded|eTraversalNeeded;
3623 }
chaviw8b3871a2017-11-01 17:41:01 -07003624 } else {
3625 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003626 flags |= eTransactionNeeded|eTraversalNeeded;
3627 }
3628 }
chaviw8b3871a2017-11-01 17:41:01 -07003629 }
3630 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003631 // NOTE: index needs to be calculated before we update the state
3632 const auto& p = layer->getParent();
3633 if (p == nullptr) {
3634 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3635 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3636 mCurrentState.layersSortedByZ.removeAt(idx);
3637 mCurrentState.layersSortedByZ.add(layer);
3638 // we need traversal (state changed)
3639 // AND transaction (list changed)
3640 flags |= eTransactionNeeded|eTraversalNeeded;
3641 }
3642 } else {
3643 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3644 flags |= eTransactionNeeded|eTraversalNeeded;
3645 }
chaviw8b3871a2017-11-01 17:41:01 -07003646 }
3647 }
3648 if (what & layer_state_t::eSizeChanged) {
3649 if (layer->setSize(s.w, s.h)) {
3650 flags |= eTraversalNeeded;
3651 }
3652 }
3653 if (what & layer_state_t::eAlphaChanged) {
3654 if (layer->setAlpha(s.alpha))
3655 flags |= eTraversalNeeded;
3656 }
3657 if (what & layer_state_t::eColorChanged) {
3658 if (layer->setColor(s.color))
3659 flags |= eTraversalNeeded;
3660 }
Peiyong Lind3788632018-09-18 16:01:31 -07003661 if (what & layer_state_t::eColorTransformChanged) {
3662 if (layer->setColorTransform(s.colorTransform)) {
3663 flags |= eTraversalNeeded;
3664 }
3665 }
chaviw8b3871a2017-11-01 17:41:01 -07003666 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003667 // TODO: b/109894387
3668 //
3669 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3670 // rotation. To see the problem observe that if we have a square parent, and a child
3671 // of the same size, then we rotate the child 45 degrees around it's center, the child
3672 // must now be cropped to a non rectangular 8 sided region.
3673 //
3674 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3675 // private API, and the WindowManager only uses rotation in one case, which is on a top
3676 // level layer in which cropping is not an issue.
3677 //
3678 // However given that abuse of rotation matrices could lead to surfaces extending outside
3679 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3680 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3681 // transformations.
3682 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003683 flags |= eTraversalNeeded;
3684 }
3685 if (what & layer_state_t::eTransparentRegionChanged) {
3686 if (layer->setTransparentRegionHint(s.transparentRegion))
3687 flags |= eTraversalNeeded;
3688 }
3689 if (what & layer_state_t::eFlagsChanged) {
3690 if (layer->setFlags(s.flags, s.mask))
3691 flags |= eTraversalNeeded;
3692 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003693 if (what & layer_state_t::eCropChanged_legacy) {
3694 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003695 flags |= eTraversalNeeded;
3696 }
chaviw8b3871a2017-11-01 17:41:01 -07003697 if (what & layer_state_t::eLayerStackChanged) {
3698 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3699 // We only allow setting layer stacks for top level layers,
3700 // everything else inherits layer stack from its parent.
3701 if (layer->hasParent()) {
3702 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3703 layer->getName().string());
3704 } else if (idx < 0) {
3705 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3706 "that also does not appear in the top level layer list. Something"
3707 " has gone wrong.", layer->getName().string());
3708 } else if (layer->setLayerStack(s.layerStack)) {
3709 mCurrentState.layersSortedByZ.removeAt(idx);
3710 mCurrentState.layersSortedByZ.add(layer);
3711 // we need traversal (state changed)
3712 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003713 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003714 }
3715 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003716 if (what & layer_state_t::eDeferTransaction_legacy) {
3717 if (s.barrierHandle_legacy != nullptr) {
3718 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3719 } else if (s.barrierGbp_legacy != nullptr) {
3720 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003721 if (authenticateSurfaceTextureLocked(gbp)) {
3722 const auto& otherLayer =
3723 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003724 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003725 } else {
3726 ALOGE("Attempt to defer transaction to to an"
3727 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003728 }
3729 }
chaviw8b3871a2017-11-01 17:41:01 -07003730 // We don't trigger a traversal here because if no other state is
3731 // changed, we don't want this to cause any more work
3732 }
3733 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003734 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003735 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003736 if (!hadParent) {
3737 mCurrentState.layersSortedByZ.remove(layer);
3738 }
chaviw8b3871a2017-11-01 17:41:01 -07003739 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003740 }
chaviw8b3871a2017-11-01 17:41:01 -07003741 }
3742 if (what & layer_state_t::eReparentChildren) {
3743 if (layer->reparentChildren(s.reparentHandle)) {
3744 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003745 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003746 }
chaviw8b3871a2017-11-01 17:41:01 -07003747 if (what & layer_state_t::eDetachChildren) {
3748 layer->detachChildren();
3749 }
3750 if (what & layer_state_t::eOverrideScalingModeChanged) {
3751 layer->setOverrideScalingMode(s.overrideScalingMode);
3752 // We don't trigger a traversal here because if no other state is
3753 // changed, we don't want this to cause any more work
3754 }
Marissa Wall61c58622018-07-18 10:12:20 -07003755 if (what & layer_state_t::eTransformChanged) {
3756 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3757 }
3758 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3759 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3760 flags |= eTraversalNeeded;
3761 }
3762 if (what & layer_state_t::eCropChanged) {
3763 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3764 }
3765 if (what & layer_state_t::eBufferChanged) {
3766 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3767 }
3768 if (what & layer_state_t::eAcquireFenceChanged) {
3769 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3770 }
3771 if (what & layer_state_t::eDataspaceChanged) {
3772 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3773 }
3774 if (what & layer_state_t::eHdrMetadataChanged) {
3775 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3776 }
3777 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3778 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3779 }
3780 if (what & layer_state_t::eApiChanged) {
3781 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3782 }
3783 if (what & layer_state_t::eSidebandStreamChanged) {
3784 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3785 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003786 return flags;
3787}
3788
chaviwca27f252018-02-06 16:46:39 -08003789void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3790 const layer_state_t& state = composerState.state;
3791 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3792
3793 sp<Layer> layer(client->getLayerUser(state.surface));
3794 if (layer == nullptr) {
3795 return;
3796 }
3797
Rob Carr4bba3702018-10-08 21:53:30 +00003798 if (layer->isPendingRemoval()) {
chaviwca27f252018-02-06 16:46:39 -08003799 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3800 return;
3801 }
3802
3803 if (state.what & layer_state_t::eDestroySurface) {
3804 removeLayerLocked(mStateLock, layer);
3805 }
3806}
3807
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003808status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003809 const String8& name,
3810 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003811 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003812 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003813 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003814{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003815 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003816 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003817 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003818 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003819 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003820
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003821 status_t result = NO_ERROR;
3822
3823 sp<Layer> layer;
3824
Cody Northropbc755282017-03-31 12:00:08 -06003825 String8 uniqueName = getUniqueLayerName(name);
3826
Mathias Agopian3165cc22012-08-08 19:42:09 -07003827 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003828 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003829 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3830 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003831
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003832 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003833 case ISurfaceComposerClient::eFXSurfaceBufferState:
3834 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3835 break;
chaviw13fdc492017-06-27 12:40:18 -07003836 case ISurfaceComposerClient::eFXSurfaceColor:
3837 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003838 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003839 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003840 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003841 case ISurfaceComposerClient::eFXSurfaceContainer:
3842 result = createContainerLayer(client,
3843 uniqueName, w, h, flags,
3844 handle, &layer);
3845 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003846 default:
3847 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003848 break;
3849 }
3850
Dan Stoza7d89d062015-04-30 13:29:25 -07003851 if (result != NO_ERROR) {
3852 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003853 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003854
Chia-I Wuab0c3192017-08-01 11:29:00 -07003855 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3856 // TODO b/64227542
3857 if (windowType == 441731) {
3858 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3859 layer->setPrimaryDisplayOnly();
3860 }
3861
Albert Chaulk479c60c2017-01-27 14:21:34 -05003862 layer->setInfo(windowType, ownerUid);
3863
Robert Carr1f0a16a2016-10-24 16:27:39 -07003864 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003865 if (result != NO_ERROR) {
3866 return result;
3867 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003868 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003869
3870 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003871 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003872}
3873
Cody Northropbc755282017-03-31 12:00:08 -06003874String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3875{
3876 bool matchFound = true;
3877 uint32_t dupeCounter = 0;
3878
3879 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3880 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3881
Dan Stoza436ccf32018-06-21 12:10:12 -07003882 // Grab the state lock since we're accessing mCurrentState
3883 Mutex::Autolock lock(mStateLock);
3884
Cody Northropbc755282017-03-31 12:00:08 -06003885 // Loop over layers until we're sure there is no matching name
3886 while (matchFound) {
3887 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003888 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003889 if (layer->getName() == uniqueName) {
3890 matchFound = true;
3891 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3892 }
3893 });
3894 }
3895
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003896 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3897 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003898
3899 return uniqueName;
3900}
3901
Marissa Wallfd668622018-05-10 10:21:13 -07003902status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3903 uint32_t w, uint32_t h, uint32_t flags,
3904 PixelFormat& format, sp<IBinder>* handle,
3905 sp<IGraphicBufferProducer>* gbp,
3906 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003907 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003908 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003909 case PIXEL_FORMAT_TRANSPARENT:
3910 case PIXEL_FORMAT_TRANSLUCENT:
3911 format = PIXEL_FORMAT_RGBA_8888;
3912 break;
3913 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003914 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003915 break;
3916 }
3917
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003918 sp<BufferQueueLayer> layer =
3919 new BufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003920 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003921 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003922 *handle = layer->getHandle();
3923 *gbp = layer->getProducer();
3924 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003925 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003926
Marissa Wallfd668622018-05-10 10:21:13 -07003927 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003928 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003929}
3930
Marissa Wall61c58622018-07-18 10:12:20 -07003931status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3932 uint32_t w, uint32_t h, uint32_t flags,
3933 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003934 sp<BufferStateLayer> layer =
3935 new BufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003936 *handle = layer->getHandle();
3937 *outLayer = layer;
3938
3939 return NO_ERROR;
3940}
3941
chaviw13fdc492017-06-27 12:40:18 -07003942status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003943 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003944 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003945{
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003946 *outLayer = new ColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003947 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003948 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003949}
3950
Robert Carr6b3f6c52018-08-13 13:05:17 -07003951status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3952 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3953 sp<IBinder>* handle, sp<Layer>* outLayer)
3954{
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003955 *outLayer = new ContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003956 *handle = (*outLayer)->getHandle();
3957 return NO_ERROR;
3958}
3959
3960
Mathias Agopianac9fa422013-02-11 16:40:36 -08003961status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003962{
Robert Carr9524cb32017-02-13 11:32:32 -08003963 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003964 status_t err = NO_ERROR;
3965 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003966 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003967 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003968 err = removeLayer(l);
3969 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3970 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003971 }
3972 return err;
3973}
3974
Rob Carr4bba3702018-10-08 21:53:30 +00003975status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
3976{
3977 // called by ~LayerCleaner() when all references to the IBinder (handle)
3978 // are gone
3979 sp<Layer> l = layer.promote();
3980 if (l == nullptr) {
3981 // The layer has already been removed, carry on
3982 return NO_ERROR;
3983 }
3984 // If we have a parent, then we can continue to live as long as it does.
3985 return removeLayer(l, true);
3986}
3987
Mathias Agopianb60314a2012-04-10 22:09:54 -07003988// ---------------------------------------------------------------------------
3989
Andy McFadden13a082e2012-08-24 10:16:42 -07003990void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003991 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3992 if (!displayToken) return;
3993
Jesse Hall01e29052013-02-19 16:13:35 -08003994 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003995 Vector<ComposerState> state;
3996 Vector<DisplayState> displays;
3997 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003998 d.what = DisplayState::eDisplayProjectionChanged |
3999 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004000 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08004001 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004002 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004003 d.frame.makeInvalid();
4004 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004005 d.width = 0;
4006 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004007 displays.add(d);
4008 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004009
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004010 const auto display = getDisplayDevice(displayToken);
4011 if (!display) return;
4012
4013 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
4014
4015 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08004016 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07004017 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004018
Brian Andersond0010582017-03-07 13:20:31 -08004019 // Use phase of 0 since phase is not known.
4020 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07004021 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
4022 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004023}
4024
4025void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004026 // Async since we may be called from the main thread.
4027 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004028}
4029
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004030void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
4031 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004032 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004033 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07004034
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004035 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004036 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004037 return;
4038 }
4039
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004040 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004041 ALOGW("Trying to set power mode for virtual display");
4042 return;
4043 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004044
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004045 display->setPowerMode(mode);
4046
Lloyd Pique4dccc412018-01-22 17:21:36 -08004047 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07004048 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004049 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07004050 if (idx < 0) {
4051 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
4052 return;
4053 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07004054 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07004055 }
4056
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004057 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004058 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004059 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004060 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004061 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004062 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004063 if (mUseScheduler) {
4064 mScheduler->onScreenAcquired(mAppConnectionHandle);
4065 } else {
4066 mEventThread->onScreenAcquired();
4067 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004068 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004069 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004070
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004071 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004072 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004073 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004074
4075 struct sched_param param = {0};
4076 param.sched_priority = 1;
4077 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4078 ALOGW("Couldn't set SCHED_FIFO on display on");
4079 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004080 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004081 // Turn off the display
4082 struct sched_param param = {0};
4083 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4084 ALOGW("Couldn't set SCHED_OTHER on display off");
4085 }
4086
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004087 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004088 if (mUseScheduler) {
4089 mScheduler->disableHardwareVsync(true);
4090 } else {
4091 disableHardwareVsync(true); // also cancels any in-progress resync
4092 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004093 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004094 if (mUseScheduler) {
4095 mScheduler->onScreenReleased(mAppConnectionHandle);
4096 } else {
4097 mEventThread->onScreenReleased();
4098 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004099 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004100
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004101 getHwComposer().setPowerMode(type, mode);
4102 mVisibleRegionsDirty = true;
4103 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004104 } else if (mode == HWC_POWER_MODE_DOZE ||
4105 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004106 // Update display while dozing
4107 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004108 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004109 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004110 if (mUseScheduler) {
4111 mScheduler->onScreenAcquired(mAppConnectionHandle);
4112 } else {
4113 mEventThread->onScreenAcquired();
4114 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004115 resyncToHardwareVsync(true);
4116 }
4117 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4118 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004119 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004120 if (mUseScheduler) {
4121 mScheduler->disableHardwareVsync(true);
4122 } else {
4123 disableHardwareVsync(true); // also cancels any in-progress resync
4124 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004125 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004126 if (mUseScheduler) {
4127 mScheduler->onScreenReleased(mAppConnectionHandle);
4128 } else {
4129 mEventThread->onScreenReleased();
4130 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004131 }
4132 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004133 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004134 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004135 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004136 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004137
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004138 if (display->isPrimary()) {
4139 mTimeStats.setPowerMode(mode);
4140 }
4141
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004142 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004143}
4144
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004145void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004146 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004147 const auto display = getDisplayDevice(displayToken);
4148 if (!display) {
4149 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4150 displayToken.get());
4151 } else if (display->isVirtual()) {
4152 ALOGW("Attempt to set power mode %d for virtual display", mode);
4153 } else {
4154 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004155 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004156 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004157}
4158
4159// ---------------------------------------------------------------------------
4160
Lloyd Pique755e3192018-01-31 16:46:15 -08004161status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4162 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004163 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004164
Mathias Agopianbd115332013-04-18 16:41:04 -07004165 IPCThreadState* ipc = IPCThreadState::self();
4166 const int pid = ipc->getCallingPid();
4167 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004168
Mathias Agopianbd115332013-04-18 16:41:04 -07004169 if ((uid != AID_SHELL) &&
4170 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004171 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004172 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004173 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004174 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004175 // (this would indicate SF is stuck, but we want to be able to
4176 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004177 status_t err = mStateLock.timedLock(s2ns(1));
4178 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004179 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004180 result.appendFormat(
4181 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4182 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004183 }
4184
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004185 bool dumpAll = true;
4186 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004187 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004188
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004189 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004190 if ((index < numArgs) &&
4191 (args[index] == String16("--list"))) {
4192 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004193 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004194 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004195 }
4196
4197 if ((index < numArgs) &&
4198 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004199 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004200 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004201 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004202 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004203
4204 if ((index < numArgs) &&
4205 (args[index] == String16("--latency-clear"))) {
4206 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004207 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004208 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004209 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004210
4211 if ((index < numArgs) &&
4212 (args[index] == String16("--dispsync"))) {
4213 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004214 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004215 dumpAll = false;
4216 }
Dan Stozab90cf072015-03-05 11:05:59 -08004217
4218 if ((index < numArgs) &&
4219 (args[index] == String16("--static-screen"))) {
4220 index++;
4221 dumpStaticScreenStats(result);
4222 dumpAll = false;
4223 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004224
4225 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004226 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004227 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004228 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004229 dumpAll = false;
4230 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004231
4232 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4233 index++;
4234 dumpWideColorInfo(result);
4235 dumpAll = false;
4236 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004237
4238 if ((index < numArgs) &&
4239 (args[index] == String16("--enable-layer-stats"))) {
4240 index++;
4241 mLayerStats.enable();
4242 dumpAll = false;
4243 }
4244
4245 if ((index < numArgs) &&
4246 (args[index] == String16("--disable-layer-stats"))) {
4247 index++;
4248 mLayerStats.disable();
4249 dumpAll = false;
4250 }
4251
4252 if ((index < numArgs) &&
4253 (args[index] == String16("--clear-layer-stats"))) {
4254 index++;
4255 mLayerStats.clear();
4256 dumpAll = false;
4257 }
4258
4259 if ((index < numArgs) &&
4260 (args[index] == String16("--dump-layer-stats"))) {
4261 index++;
4262 mLayerStats.dump(result);
4263 dumpAll = false;
4264 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004265
4266 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004267 (args[index] == String16("--frame-composition"))) {
4268 index++;
4269 dumpFrameCompositionInfo(result);
4270 dumpAll = false;
4271 }
4272
4273 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004274 (args[index] == String16("--display-identification"))) {
4275 index++;
4276 dumpDisplayIdentificationData(result);
4277 dumpAll = false;
4278 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004279
4280 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4281 index++;
4282 mTimeStats.parseArgs(asProto, args, index, result);
4283 dumpAll = false;
4284 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004285 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004286
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004287 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004288 if (asProto) {
4289 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4290 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4291 } else {
4292 dumpAllLocked(args, index, result);
4293 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004294 }
4295
Mathias Agopian9795c422009-08-26 16:36:26 -07004296 if (locked) {
4297 mStateLock.unlock();
4298 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004299 }
4300 write(fd, result.string(), result.size());
4301 return NO_ERROR;
4302}
4303
Dan Stozac7014012014-02-14 15:03:43 -08004304void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4305 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004306{
Robert Carr2047fae2016-11-28 14:09:09 -08004307 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004308 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004309 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004310}
4311
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004312void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004313 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004314{
4315 String8 name;
4316 if (index < args.size()) {
4317 name = String8(args[index]);
4318 index++;
4319 }
4320
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004321 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4322 getHwComposer().isConnected(displayId)) {
4323 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4324 const nsecs_t period = activeConfig->getVsyncPeriod();
4325 result.appendFormat("%" PRId64 "\n", period);
4326 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004327
4328 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004329 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004330 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004331 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004332 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004333 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004334 }
Robert Carr2047fae2016-11-28 14:09:09 -08004335 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004336 }
4337}
4338
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004339void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004340 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004341{
4342 String8 name;
4343 if (index < args.size()) {
4344 name = String8(args[index]);
4345 index++;
4346 }
4347
Robert Carr2047fae2016-11-28 14:09:09 -08004348 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004349 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004350 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004351 }
Robert Carr2047fae2016-11-28 14:09:09 -08004352 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004353
Svetoslavd85084b2014-03-20 10:28:31 -07004354 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004355}
4356
Jamie Gennis6547ff42013-07-16 20:12:42 -07004357// This should only be called from the main thread. Otherwise it would need
4358// the lock and should use mCurrentState rather than mDrawingState.
4359void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004360 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004361 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004362 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004363
4364 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4365}
4366
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004367void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004368{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004369 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004370
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004371 if (isLayerTripleBufferingDisabled())
4372 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004373
4374 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004375 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004376 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004377 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004378 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4379 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004380 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004381}
4382
Dan Stozab90cf072015-03-05 11:05:59 -08004383void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4384{
4385 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004386 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4387 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004388 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004389 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004390 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4391 b + 1, bucketTimeSec, percent);
4392 }
David Sodman4a36e932017-11-07 14:29:47 -08004393 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004394 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004395 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004396 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004397 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004398}
4399
Dan Stozae77c7662016-05-13 11:37:28 -07004400void SurfaceFlinger::recordBufferingStats(const char* layerName,
4401 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004402 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4403 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004404 for (const auto& segment : history) {
4405 if (!segment.usedThirdBuffer) {
4406 stats.twoBufferTime += segment.totalTime;
4407 }
4408 if (segment.occupancyAverage < 1.0f) {
4409 stats.doubleBufferedTime += segment.totalTime;
4410 } else if (segment.occupancyAverage < 2.0f) {
4411 stats.tripleBufferedTime += segment.totalTime;
4412 }
4413 ++stats.numSegments;
4414 stats.totalTime += segment.totalTime;
4415 }
4416}
4417
Brian Andersond6927fb2016-07-23 23:37:30 -07004418void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4419 result.appendFormat("Layer frame timestamps:\n");
4420
4421 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4422 const size_t count = currentLayers.size();
4423 for (size_t i=0 ; i<count ; i++) {
4424 currentLayers[i]->dumpFrameEvents(result);
4425 }
4426}
4427
Dan Stozae77c7662016-05-13 11:37:28 -07004428void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4429 result.append("Buffering stats:\n");
4430 result.append(" [Layer name] <Active time> <Two buffer> "
4431 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004432 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004433 typedef std::tuple<std::string, float, float, float> BufferTuple;
4434 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004435 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004436 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004437 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004438 if (stats.numSegments == 0) {
4439 continue;
4440 }
4441 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4442 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4443 stats.totalTime;
4444 float doubleBufferRatio = static_cast<float>(
4445 stats.doubleBufferedTime) / stats.totalTime;
4446 float tripleBufferRatio = static_cast<float>(
4447 stats.tripleBufferedTime) / stats.totalTime;
4448 sorted.insert({activeTime, {name, twoBufferRatio,
4449 doubleBufferRatio, tripleBufferRatio}});
4450 }
4451 for (const auto& sortedPair : sorted) {
4452 float activeTime = sortedPair.first;
4453 const BufferTuple& values = sortedPair.second;
4454 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4455 std::get<0>(values).c_str(), activeTime,
4456 std::get<1>(values), std::get<2>(values),
4457 std::get<3>(values));
4458 }
4459 result.append("\n");
4460}
4461
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004462void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004463 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004464 const int32_t displayId = display->getId();
4465 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4466 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004467 continue;
4468 }
4469
Dominik Laskowski7e045462018-05-30 13:02:02 -07004470 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004471 uint8_t port;
4472 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004473 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004474 result.append("no identification data\n");
4475 continue;
4476 }
4477
4478 if (!isEdid(data)) {
4479 result.append("unknown identification data: ");
4480 for (uint8_t byte : data) {
4481 result.appendFormat("%x ", byte);
4482 }
4483 result.append("\n");
4484 continue;
4485 }
4486
4487 const auto edid = parseEdid(data);
4488 if (!edid) {
4489 result.append("invalid EDID: ");
4490 for (uint8_t byte : data) {
4491 result.appendFormat("%x ", byte);
4492 }
4493 result.append("\n");
4494 continue;
4495 }
4496
4497 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4498 result.append(edid->displayName.data(), edid->displayName.length());
4499 result.append("\"\n");
4500 }
4501 result.append("\n");
4502}
4503
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004504void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004505 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4506 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004507 result.appendFormat("DisplayColorSetting: %s\n",
4508 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004509
4510 // TODO: print out if wide-color mode is active or not
4511
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004512 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004513 const int32_t displayId = display->getId();
4514 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004515 continue;
4516 }
4517
Dominik Laskowski7e045462018-05-30 13:02:02 -07004518 result.appendFormat("Display %d color modes:\n", displayId);
4519 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004520 for (auto&& mode : modes) {
4521 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4522 }
4523
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004524 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004525 result.appendFormat(" Current color mode: %s (%d)\n",
4526 decodeColorMode(currentMode).c_str(), currentMode);
4527 }
4528 result.append("\n");
4529}
4530
David Sodman7e4ae112018-02-09 15:02:28 -08004531void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4532 std::string stringResult;
4533
4534 for (const auto& [token, display] : mDisplays) {
4535 const auto displayId = display->getId();
4536 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
4537 continue;
4538 }
4539
4540 const auto& compositionInfoIt = getBE().mEndOfFrameCompositionInfo.find(displayId);
4541 if (compositionInfoIt == getBE().mEndOfFrameCompositionInfo.end()) {
4542 break;
4543 }
4544 const auto& compositionInfoList = compositionInfoIt->second;
4545 stringResult += base::StringPrintf("Display: %d\n", displayId);
4546 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4547 for (const auto& compositionInfo : compositionInfoList) {
4548 compositionInfo.dump(stringResult, nullptr);
4549 stringResult += base::StringPrintf("\n");
4550 }
4551 }
4552
4553 result.append(stringResult.c_str());
4554}
4555
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004556LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004557 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004558 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4559 const State& state = useDrawing ? mDrawingState : mCurrentState;
4560 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004561 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004562 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004563 });
4564
4565 return layersProto;
4566}
4567
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004568LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004569 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004570
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004571 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004572 resolution->set_w(display.getWidth());
4573 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004574
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004575 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4576 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4577 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004578
Dominik Laskowski7e045462018-05-30 13:02:02 -07004579 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004580 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004581 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004582 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004583 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004584 }
4585 });
4586
4587 return layersProto;
4588}
4589
Mathias Agopian74d211a2013-04-22 16:55:35 +02004590void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4591 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004592{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004593 bool colorize = false;
4594 if (index < args.size()
4595 && (args[index] == String16("--color"))) {
4596 colorize = true;
4597 index++;
4598 }
4599
4600 Colorizer colorizer(colorize);
4601
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004602 // figure out if we're stuck somewhere
4603 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004604 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004605 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4606
4607 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004608 * Dump library configuration.
4609 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004610
4611 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004612 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004613 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004614 appendSfConfigString(result);
4615 appendUiConfigString(result);
4616 appendGuiConfigString(result);
4617 result.append("\n");
4618
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004619 result.append("\nDisplay identification data:\n");
4620 dumpDisplayIdentificationData(result);
4621
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004622 result.append("\nWide-Color information:\n");
4623 dumpWideColorInfo(result);
4624
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004625 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004626 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004627 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004628 result.append(SyncFeatures::getInstance().toString());
4629 result.append("\n");
4630
Andy McFadden41d67d72014-04-25 16:58:34 -07004631 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004632 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004633 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004634
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004635 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4636 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004637 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4638 getHwComposer().isConnected(displayId)) {
4639 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004640 result.appendFormat("Display %d: "
4641 "app phase %" PRId64 " ns, "
4642 "sf phase %" PRId64 " ns, "
4643 "early app phase %" PRId64 " ns, "
4644 "early sf phase %" PRId64 " ns, "
4645 "early app gl phase %" PRId64 " ns, "
4646 "early sf gl phase %" PRId64 " ns, "
4647 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4648 displayId,
4649 vsyncPhaseOffsetNs,
4650 sfVsyncPhaseOffsetNs,
4651 appEarlyOffset,
4652 sfEarlyOffset,
4653 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004654 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004655 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004656 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004657 result.append("\n");
4658
Dan Stozab90cf072015-03-05 11:05:59 -08004659 // Dump static screen stats
4660 result.append("\n");
4661 dumpStaticScreenStats(result);
4662 result.append("\n");
4663
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004664 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4665
Dan Stozae77c7662016-05-13 11:37:28 -07004666 dumpBufferingStats(result);
4667
Andy McFadden4803b742012-09-24 19:07:20 -07004668 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004669 * Dump the visible layer list
4670 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004671 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004672 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004673 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4674 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004675 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004676
Chia-I Wu2f884132018-09-13 15:17:58 -07004677 {
4678 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4679 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4680 result.append(LayerProtoParser::layerTreeToString(layerTree).c_str());
4681 result.append("\n");
4682 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004683
David Sodman7e4ae112018-02-09 15:02:28 -08004684 result.append("\nFrame-Composition information:\n");
4685 dumpFrameCompositionInfo(result);
4686 result.append("\n");
4687
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004688 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004689 * Dump Display state
4690 */
4691
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004692 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004693 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004694 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004695 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004696 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004697 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004698 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004699
4700 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004701 * Dump SurfaceFlinger global state
4702 */
4703
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004704 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004705 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004706 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004707
Mathias Agopian888c8222012-08-04 21:10:38 -07004708 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004709 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004710
David Sodmanbc815282017-11-05 18:57:52 -08004711 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004712
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004713 if (display) {
4714 display->undefinedRegion.dump(result, "undefinedRegion");
4715 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4716 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004717 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004718 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004719 " gpu_to_cpu_unsupported : %d\n",
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004720 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004721
4722 if (display) {
4723 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4724 result.appendFormat(" refresh-rate : %f fps\n"
4725 " x-dpi : %f\n"
4726 " y-dpi : %f\n",
4727 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4728 activeConfig->getDpiY());
4729 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004730
Mathias Agopian74d211a2013-04-22 16:55:35 +02004731 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004732 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004733
Ana Krulec98b5b242018-08-10 15:03:23 -07004734 result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004735 /*
4736 * VSYNC state
4737 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004738 if (mUseScheduler) {
4739 mScheduler->dump(mAppConnectionHandle, result);
4740 } else {
4741 mEventThread->dump(result);
4742 }
Dan Stozae22aec72016-08-01 13:20:59 -07004743 result.append("\n");
4744
4745 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004746 * Tracing state
4747 */
4748 mTracing.dump(result);
4749 result.append("\n");
4750
4751 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004752 * HWC layer minidump
4753 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004754 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004755 const int32_t displayId = display->getId();
4756 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004757 continue;
4758 }
4759
Dominik Laskowski7e045462018-05-30 13:02:02 -07004760 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004761 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004762 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004763 result.append("\n");
4764 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004765
4766 /*
4767 * Dump HWComposer state
4768 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004769 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004770 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004771 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004772 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004773 result.appendFormat(" h/w composer %s\n",
4774 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004775 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004776
4777 /*
4778 * Dump gralloc state
4779 */
4780 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4781 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004782
4783 /*
4784 * Dump VrFlinger state if in use.
4785 */
4786 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4787 result.append("VrFlinger state:\n");
4788 result.append(mVrFlinger->Dump().c_str());
4789 result.append("\n");
4790 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004791}
4792
Dominik Laskowski7e045462018-05-30 13:02:02 -07004793const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004794 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004795 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004796 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004797 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004798 }
4799 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004800
4801 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4802 static const Vector<sp<Layer>> empty;
4803 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004804}
4805
Keun young Park63f165f2012-08-31 10:53:36 -07004806bool SurfaceFlinger::startDdmConnection()
4807{
4808 void* libddmconnection_dso =
4809 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4810 if (!libddmconnection_dso) {
4811 return false;
4812 }
4813 void (*DdmConnection_start)(const char* name);
4814 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004815 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004816 if (!DdmConnection_start) {
4817 dlclose(libddmconnection_dso);
4818 return false;
4819 }
4820 (*DdmConnection_start)(getServiceName());
4821 return true;
4822}
4823
Chia-I Wu28f320b2018-05-03 11:02:56 -07004824void SurfaceFlinger::updateColorMatrixLocked() {
4825 mat4 colorMatrix;
4826 if (mGlobalSaturationFactor != 1.0f) {
4827 // Rec.709 luma coefficients
4828 float3 luminance{0.213f, 0.715f, 0.072f};
4829 luminance *= 1.0f - mGlobalSaturationFactor;
4830 mat4 saturationMatrix = mat4(
4831 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4832 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4833 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4834 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4835 );
4836 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4837 } else {
4838 colorMatrix = mClientColorMatrix * mDaltonizer();
4839 }
4840
4841 if (mCurrentState.colorMatrix != colorMatrix) {
4842 mCurrentState.colorMatrix = colorMatrix;
4843 mCurrentState.colorMatrixChanged = true;
4844 setTransactionFlags(eTransactionNeeded);
4845 }
4846}
4847
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004848status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004849#pragma clang diagnostic push
4850#pragma clang diagnostic error "-Wswitch-enum"
4851 switch (static_cast<ISurfaceComposerTag>(code)) {
4852 // These methods should at minimum make sure that the client requested
4853 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004854 case BOOT_FINISHED:
4855 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004856 case CREATE_CONNECTION:
4857 case CREATE_DISPLAY:
4858 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004859 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004860 case GET_ACTIVE_COLOR_MODE:
4861 case GET_ANIMATION_FRAME_STATS:
4862 case GET_HDR_CAPABILITIES:
4863 case SET_ACTIVE_CONFIG:
4864 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004865 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004866 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004867 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4868 IPCThreadState* ipc = IPCThreadState::self();
4869 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4870 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004871 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004872 }
Robert Carr1db73f62016-12-21 12:58:51 -08004873 return OK;
4874 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004875 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004876 IPCThreadState* ipc = IPCThreadState::self();
4877 const int pid = ipc->getCallingPid();
4878 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004879 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4880 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004881 return PERMISSION_DENIED;
4882 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004883 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004884 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004885 // Used by apps to hook Choreographer to SurfaceFlinger.
4886 case CREATE_DISPLAY_EVENT_CONNECTION:
4887 // The following calls are currently used by clients that do not
4888 // request necessary permissions. However, they do not expose any secret
4889 // information, so it is OK to pass them.
4890 case AUTHENTICATE_SURFACE:
4891 case GET_ACTIVE_CONFIG:
4892 case GET_BUILT_IN_DISPLAY:
4893 case GET_DISPLAY_COLOR_MODES:
4894 case GET_DISPLAY_CONFIGS:
4895 case GET_DISPLAY_STATS:
4896 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4897 // Calling setTransactionState is safe, because you need to have been
4898 // granted a reference to Client* and Handle* to do anything with it.
4899 case SET_TRANSACTION_STATE:
4900 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004901 case CREATE_SCOPED_CONNECTION:
4902 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004903 return OK;
4904 }
4905 case CAPTURE_LAYERS:
4906 case CAPTURE_SCREEN: {
4907 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004908 IPCThreadState* ipc = IPCThreadState::self();
4909 const int pid = ipc->getCallingPid();
4910 const int uid = ipc->getCallingUid();
4911 if ((uid != AID_GRAPHICS) &&
4912 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4913 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4914 return PERMISSION_DENIED;
4915 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004916 return OK;
4917 }
4918 // The following codes are deprecated and should never be allowed to access SF.
4919 case CONNECT_DISPLAY_UNUSED:
4920 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4921 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4922 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004923 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004924 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004925
4926 // These codes are used for the IBinder protocol to either interrogate the recipient
4927 // side of the transaction for its canonical interface descriptor or to dump its state.
4928 // We let them pass by default.
4929 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4930 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4931 code == IBinder::SYSPROPS_TRANSACTION) {
4932 return OK;
4933 }
4934 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4935 // in onTransact verifies that the user is root, and has access to use SF.
4936 if (code >= 1000 && code <= 1029) {
4937 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4938 return OK;
4939 }
4940 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4941 return PERMISSION_DENIED;
4942#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004943}
4944
Ana Krulec13be8ad2018-08-21 02:43:56 +00004945status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4946 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004947 status_t credentialCheck = CheckTransactCodeCredentials(code);
4948 if (credentialCheck != OK) {
4949 return credentialCheck;
4950 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004951
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004952 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4953 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004954 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004955 IPCThreadState* ipc = IPCThreadState::self();
4956 const int uid = ipc->getCallingUid();
4957 if (CC_UNLIKELY(uid != AID_SYSTEM
4958 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004959 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004960 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004961 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004962 return PERMISSION_DENIED;
4963 }
4964 int n;
4965 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004966 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004967 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004968 return NO_ERROR;
4969 case 1002: // SHOW_UPDATES
4970 n = data.readInt32();
4971 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004972 invalidateHwcGeometry();
4973 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004974 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004975 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004976 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004977 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004978 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004979 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004980 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004981 setTransactionFlags(
4982 eTransactionNeeded|
4983 eDisplayTransactionNeeded|
4984 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004985 return NO_ERROR;
4986 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004987 case 1006:{ // send empty update
4988 signalRefresh();
4989 return NO_ERROR;
4990 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004991 case 1008: // toggle use of hw composer
4992 n = data.readInt32();
4993 mDebugDisableHWC = n ? 1 : 0;
4994 invalidateHwcGeometry();
4995 repaintEverything();
4996 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004997 case 1009: // toggle use of transform hint
4998 n = data.readInt32();
4999 mDebugDisableTransformHint = n ? 1 : 0;
5000 invalidateHwcGeometry();
5001 repaintEverything();
5002 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005003 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005004 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005005 reply->writeInt32(0);
5006 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005007 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005008 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005009 return NO_ERROR;
5010 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005011 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005012 if (!display) {
5013 return NAME_NOT_FOUND;
5014 }
5015
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005016 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005017 return NO_ERROR;
5018 }
5019 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005020 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005021 // daltonize
5022 n = data.readInt32();
5023 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005024 case 1:
5025 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5026 break;
5027 case 2:
5028 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5029 break;
5030 case 3:
5031 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5032 break;
5033 default:
5034 mDaltonizer.setType(ColorBlindnessType::None);
5035 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005036 }
5037 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005038 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005039 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005040 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005041 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005042
5043 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005044 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005045 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005046 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005047 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005048 // apply a color matrix
5049 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005050 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005051 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005052 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005053 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005054 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005055 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005056 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005057 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005058 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005059 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005060
5061 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5062 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005063 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005064 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5065 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5066 }
5067
Chia-I Wu28f320b2018-05-03 11:02:56 -07005068 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005069 return NO_ERROR;
5070 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005071 // This is an experimental interface
5072 // Needs to be shifted to proper binder interface when we productize
5073 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005074 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005075 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005076 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005077 return NO_ERROR;
5078 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005079 case 1017: {
5080 n = data.readInt32();
5081 mForceFullDamage = static_cast<bool>(n);
5082 return NO_ERROR;
5083 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005084 case 1018: { // Modify Choreographer's phase offset
5085 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005086 if (mUseScheduler) {
5087 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5088 } else {
5089 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5090 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005091 return NO_ERROR;
5092 }
5093 case 1019: { // Modify SurfaceFlinger's phase offset
5094 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005095 if (mUseScheduler) {
5096 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5097 } else {
5098 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5099 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005100 return NO_ERROR;
5101 }
Irvel468051e2016-06-13 16:44:44 -07005102 case 1020: { // Layer updates interceptor
5103 n = data.readInt32();
5104 if (n) {
5105 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005106 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005107 }
5108 else{
5109 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005110 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005111 }
5112 return NO_ERROR;
5113 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005114 case 1021: { // Disable HWC virtual displays
5115 n = data.readInt32();
5116 mUseHwcVirtualDisplays = !n;
5117 return NO_ERROR;
5118 }
Romain Guy0147a172017-06-01 13:53:56 -07005119 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005120 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005121 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005122
Chia-I Wu28f320b2018-05-03 11:02:56 -07005123 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005124 return NO_ERROR;
5125 }
Romain Guy54f154a2017-10-24 21:40:32 +01005126 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005127 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005128 invalidateHwcGeometry();
5129 repaintEverything();
5130 return NO_ERROR;
5131 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005132 // TODO(b/111505327): Find out whether the usage of 1024 can switch to 1030,
5133 // deprecate 1024 if they can.
5134 case 1024: { // Does device have wide color gamut display?
Romain Guy54f154a2017-10-24 21:40:32 +01005135 reply->writeBool(hasWideColorDisplay);
5136 return NO_ERROR;
5137 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005138 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005139 n = data.readInt32();
5140 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005141 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005142 mTracing.enable();
5143 doTracing("tracing.enable");
5144 reply->writeInt32(NO_ERROR);
5145 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005146 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005147 status_t err = mTracing.disable();
5148 reply->writeInt32(err);
5149 }
5150 return NO_ERROR;
5151 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005152 case 1026: { // Get layer tracing status
5153 reply->writeBool(mTracing.isEnabled());
5154 return NO_ERROR;
5155 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005156 // Is a DisplayColorSetting supported?
5157 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005158 const auto display = getDefaultDisplayDevice();
5159 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005160 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005161 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005162
5163 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5164 switch (setting) {
5165 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005166 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005167 break;
5168 case DisplayColorSetting::UNMANAGED:
5169 reply->writeBool(true);
5170 break;
5171 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005172 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005173 break;
5174 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005175 reply->writeBool(
5176 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005177 break;
5178 }
5179 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005180 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005181 // Is VrFlinger active?
5182 case 1028: {
5183 Mutex::Autolock _l(mStateLock);
5184 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5185 return NO_ERROR;
5186 }
David Sodman6d46c1e2018-07-13 12:59:48 -07005187 case 1029: {
5188 // Code 1029 is an experimental feature that allows applications to
5189 // simulate a high frequency panel by setting a multiplier and divisor
5190 // on the VSYNC-sf clock. If either the multiplier or divisor are
David Sodman44b5de02018-08-21 16:28:53 -07005191 // 0, then the code simply return the current multiplier and divisor.
5192 HWC2::Device::FrequencyScaler frequencyScaler;
5193 frequencyScaler.multiplier = data.readInt32();
5194 frequencyScaler.divisor = data.readInt32();
David Sodman6d46c1e2018-07-13 12:59:48 -07005195
David Sodman44b5de02018-08-21 16:28:53 -07005196 if ((frequencyScaler.multiplier == 0) || (frequencyScaler.divisor == 0)) {
5197 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5198 reply->writeInt32(frequencyScaler.multiplier);
5199 reply->writeInt32(frequencyScaler.divisor);
5200 return NO_ERROR;
David Sodman6d46c1e2018-07-13 12:59:48 -07005201 }
5202
David Sodman44b5de02018-08-21 16:28:53 -07005203 if ((frequencyScaler.multiplier == 1) && (frequencyScaler.divisor == 1)) {
Ana Krulece588e312018-09-18 12:32:24 -07005204 if (mUseScheduler) {
5205 mScheduler->enableHardwareVsync();
5206 } else {
5207 enableHardwareVsync();
5208 }
David Sodman6d46c1e2018-07-13 12:59:48 -07005209 } else {
Ana Krulece588e312018-09-18 12:32:24 -07005210 if (mUseScheduler) {
5211 mScheduler->disableHardwareVsync(true);
5212 } else {
5213 disableHardwareVsync(true);
5214 }
David Sodman6d46c1e2018-07-13 12:59:48 -07005215 }
David Sodman44b5de02018-08-21 16:28:53 -07005216 mPrimaryDispSync->scalePeriod(frequencyScaler);
5217 getBE().mHwc->setDisplayFrequencyScaleParameters(frequencyScaler);
David Sodman6d46c1e2018-07-13 12:59:48 -07005218
David Sodman44b5de02018-08-21 16:28:53 -07005219 ATRACE_INT("PeriodMultiplier", frequencyScaler.multiplier);
5220 ATRACE_INT("PeriodDivisor", frequencyScaler.divisor);
5221
5222 const hwc2_display_t hwcDisplayId = getBE().mHwc->getActiveConfig(
5223 DisplayDevice::DISPLAY_PRIMARY)->getDisplayId();
5224
5225 onHotplugReceived(getBE().mComposerSequenceId,
5226 hwcDisplayId, HWC2::Connection::Disconnected);
5227 onHotplugReceived(getBE().mComposerSequenceId,
5228 hwcDisplayId, HWC2::Connection::Connected);
5229 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5230 reply->writeInt32(frequencyScaler.multiplier);
5231 reply->writeInt32(frequencyScaler.divisor);
5232
David Sodman6d46c1e2018-07-13 12:59:48 -07005233 return NO_ERROR;
5234 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005235 // Is device color managed?
5236 case 1030: {
5237 reply->writeBool(useColorManagement);
5238 return NO_ERROR;
5239 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005240 }
5241 }
5242 return err;
5243}
5244
Steven Thomas6d8110b2017-08-31 18:24:21 -07005245void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005246 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005247 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005248}
5249
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005250// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5251class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005252public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005253 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5254 ~WindowDisconnector() {
5255 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005256 }
5257
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005258private:
5259 ANativeWindow* mWindow;
5260 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005261};
5262
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005263status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
5264 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005265 uint32_t reqWidth, uint32_t reqHeight,
5266 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005267 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005268 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005269
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005270 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005271
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005272 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5273
Chia-I Wu20261cb2018-08-23 12:55:44 -07005274 sp<DisplayDevice> display;
5275 {
5276 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005277
Chia-I Wu20261cb2018-08-23 12:55:44 -07005278 display = getDisplayDeviceLocked(displayToken);
5279 if (!display) return BAD_VALUE;
5280
Chia-I Wu8730ba82018-08-29 09:25:59 -07005281 // ignore sourceCrop (i.e., use the projected logical display
5282 // viewport) until the framework is fixed
5283 sourceCrop.clear();
Chia-I Wucb023152018-08-28 12:57:23 -07005284
5285 // set the requested width/height to the logical display viewport size
5286 // by default
5287 if (reqWidth == 0 || reqHeight == 0) {
5288 reqWidth = uint32_t(display->getViewport().width());
5289 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005290 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005291 }
5292
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005293 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005294
5295 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005296 display, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005297 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005298}
5299
5300status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08005301 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005302 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005303 ATRACE_CALL();
5304
5305 class LayerRenderArea : public RenderArea {
5306 public:
Robert Carr578038f2018-03-09 12:25:24 -08005307 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
5308 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
Chia-I Wu9d1abea2018-08-23 13:44:43 -07005309 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08005310 mLayer(layer),
5311 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005312 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005313 mFlinger(flinger),
5314 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005315 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005316 Rect getBounds() const override {
5317 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005318 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005319 }
Marissa Wall61c58622018-07-18 10:12:20 -07005320 int getHeight() const override {
5321 return mLayer->getActiveHeight(mLayer->getDrawingState());
5322 }
5323 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005324 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005325 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005326 Rect getSourceCrop() const override {
5327 if (mCrop.isEmpty()) {
5328 return getBounds();
5329 } else {
5330 return mCrop;
5331 }
5332 }
Robert Carr578038f2018-03-09 12:25:24 -08005333 class ReparentForDrawing {
5334 public:
5335 const sp<Layer>& oldParent;
5336 const sp<Layer>& newParent;
5337
5338 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5339 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005340 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005341 }
Robert Carr15eae092018-03-23 13:43:53 -07005342 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005343 };
5344
5345 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005346 const Rect sourceCrop = getSourceCrop();
5347 // no need to check rotation because there is none
5348 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5349 sourceCrop.height() != getReqHeight();
5350
Robert Carr578038f2018-03-09 12:25:24 -08005351 if (!mChildrenOnly) {
5352 mTransform = mLayer->getTransform().inverse();
5353 drawLayers();
5354 } else {
5355 Rect bounds = getBounds();
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005356 screenshotParentLayer = new ContainerLayer(
5357 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5358 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005359
5360 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5361 drawLayers();
5362 }
5363 }
chaviwa76b2712017-09-20 12:02:26 -07005364
chaviwa76b2712017-09-20 12:02:26 -07005365 private:
chaviw7206d492017-11-10 16:16:12 -08005366 const sp<Layer> mLayer;
5367 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005368
5369 // In the "childrenOnly" case we reparent the children to a screenshot
5370 // layer which has no properties set and which does not draw.
5371 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005372 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005373 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005374
5375 SurfaceFlinger* mFlinger;
5376 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005377 };
5378
5379 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5380 auto parent = layerHandle->owner.promote();
5381
Rob Carr4bba3702018-10-08 21:53:30 +00005382 if (parent == nullptr || parent->isPendingRemoval()) {
chaviw7206d492017-11-10 16:16:12 -08005383 ALOGE("captureLayers called with a removed parent");
5384 return NAME_NOT_FOUND;
5385 }
5386
Robert Carr578038f2018-03-09 12:25:24 -08005387 const int uid = IPCThreadState::self()->getCallingUid();
5388 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5389 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5390 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5391 return PERMISSION_DENIED;
5392 }
5393
chaviw7206d492017-11-10 16:16:12 -08005394 Rect crop(sourceCrop);
5395 if (sourceCrop.width() <= 0) {
5396 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005397 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005398 }
5399
5400 if (sourceCrop.height() <= 0) {
5401 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005402 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005403 }
5404
5405 int32_t reqWidth = crop.width() * frameScale;
5406 int32_t reqHeight = crop.height() * frameScale;
5407
Chia-I Wu20261cb2018-08-23 12:55:44 -07005408 // really small crop or frameScale
5409 if (reqWidth <= 0) {
5410 reqWidth = 1;
5411 }
5412 if (reqHeight <= 0) {
5413 reqHeight = 1;
5414 }
5415
Robert Carr578038f2018-03-09 12:25:24 -08005416 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005417
Robert Carr578038f2018-03-09 12:25:24 -08005418 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005419 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5420 if (!layer->isVisible()) {
5421 return;
Robert Carr578038f2018-03-09 12:25:24 -08005422 } else if (childrenOnly && layer == parent.get()) {
5423 return;
chaviwa76b2712017-09-20 12:02:26 -07005424 }
5425 visitor(layer);
5426 });
5427 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005428 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005429}
5430
5431status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5432 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005433 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005434 bool useIdentityTransform) {
5435 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005436
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005437 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5438 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5439 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5440 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005441
5442 // This mutex protects syncFd and captureResult for communication of the return values from the
5443 // main thread back to this Binder thread
5444 std::mutex captureMutex;
5445 std::condition_variable captureCondition;
5446 std::unique_lock<std::mutex> captureLock(captureMutex);
5447 int syncFd = -1;
5448 std::optional<status_t> captureResult;
5449
Robert Carr03480e22018-01-04 16:02:06 -08005450 const int uid = IPCThreadState::self()->getCallingUid();
5451 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5452
Dominik Laskowski8c001672018-05-30 16:52:06 -07005453 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005454 // If there is a refresh pending, bug out early and tell the binder thread to try again
5455 // after the refresh.
5456 if (mRefreshPending) {
5457 ATRACE_NAME("Skipping screenshot for now");
5458 std::unique_lock<std::mutex> captureLock(captureMutex);
5459 captureResult = std::make_optional<status_t>(EAGAIN);
5460 captureCondition.notify_one();
5461 return;
5462 }
5463
5464 status_t result = NO_ERROR;
5465 int fd = -1;
5466 {
5467 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005468 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005469 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5470 useIdentityTransform, forSystem, &fd);
5471 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005472 }
5473
5474 {
5475 std::unique_lock<std::mutex> captureLock(captureMutex);
5476 syncFd = fd;
5477 captureResult = std::make_optional<status_t>(result);
5478 captureCondition.notify_one();
5479 }
5480 });
5481
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005482 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005483 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005484 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005485 while (*captureResult == EAGAIN) {
5486 captureResult.reset();
5487 result = postMessageAsync(message);
5488 if (result != NO_ERROR) {
5489 return result;
5490 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005491 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005492 }
5493 result = *captureResult;
5494 }
5495
5496 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005497 sync_wait(syncFd, -1);
5498 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005499 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005500
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005501 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005502}
5503
chaviwa76b2712017-09-20 12:02:26 -07005504void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005505 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005506 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005507 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005508
Lloyd Pique144e1162017-12-20 16:44:52 -08005509 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005510
chaviwa76b2712017-09-20 12:02:26 -07005511 const auto reqWidth = renderArea.getReqWidth();
5512 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005513 const auto sourceCrop = renderArea.getSourceCrop();
5514 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005515
Chia-I Wu36574d92018-05-16 10:54:36 -07005516 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5517 engine.setOutputDataSpace(Dataspace::SRGB);
5518 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005519
Mathias Agopian180f10d2013-04-10 22:55:41 -07005520 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005521 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005522
5523 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005524 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005525 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005526
chaviw50da5042018-04-09 13:49:37 -07005527 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005528 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005529 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005530
chaviwa76b2712017-09-20 12:02:26 -07005531 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005532 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005533 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005534 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005535 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005536}
5537
chaviwa76b2712017-09-20 12:02:26 -07005538status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5539 TraverseLayersFunction traverseLayers,
5540 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005541 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005542 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005543 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005544 ATRACE_CALL();
5545
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005546 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005547
5548 traverseLayers([&](Layer* layer) {
5549 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5550 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005551
Robert Carr03480e22018-01-04 16:02:06 -08005552 // We allow the system server to take screenshots of secure layers for
5553 // use in situations like the Screen-rotation animation and place
5554 // the impetus on WindowManager to not persist them.
5555 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005556 ALOGW("FB is protected: PERMISSION_DENIED");
5557 return PERMISSION_DENIED;
5558 }
5559
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005560 // this binds the given EGLImage as a framebuffer for the
5561 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005562 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005563 if (bufferBond.getStatus() != NO_ERROR) {
5564 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005565 return INVALID_OPERATION;
5566 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005567
Dan Stozaabcda352017-06-01 14:37:39 -07005568 // this will in fact render into our dequeued buffer
5569 // via an FBO, which means we didn't have to create
5570 // an EGLSurface and therefore we're not
5571 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005572 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005573
Alec Mouri492bc572018-09-11 21:40:04 +00005574 base::unique_fd syncFd = getRenderEngine().flush();
5575 if (syncFd < 0) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005576 getRenderEngine().finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005577 }
Alec Mouri492bc572018-09-11 21:40:04 +00005578 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005579
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005580 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005581}
5582
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005583// ---------------------------------------------------------------------------
5584
Dan Stoza412903f2017-04-27 13:42:17 -07005585void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5586 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005587}
5588
Dan Stoza412903f2017-04-27 13:42:17 -07005589void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5590 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005591}
5592
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005593void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005594 const LayerVector::Visitor& visitor) {
5595 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005596 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005597 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005598 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005599 continue;
5600 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005601 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005602 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005603 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005604 return;
5605 }
chaviwa76b2712017-09-20 12:02:26 -07005606 if (!layer->isVisible()) {
5607 return;
5608 }
5609 visitor(layer);
5610 });
5611 }
5612}
5613
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005614}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005615
Lloyd Pique074e8122018-07-26 12:57:23 -07005616
Mathias Agopian3f844832013-08-07 21:24:32 -07005617#if defined(__gl_h_)
5618#error "don't include gl/gl.h in this file"
5619#endif
5620
5621#if defined(__gl2_h_)
5622#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005623#endif