blob: c37b3b19b843b25e0288a2c32cb4153d66cb8f70 [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) {
587 mScheduler = std::make_unique<Scheduler>();
588 mAppConnectionHandle =
589 mScheduler->createConnection("appConnection", mPrimaryDispSync.get(),
590 SurfaceFlinger::vsyncPhaseOffsetNs,
591 [this] { resyncWithRateLimit(); },
592 impl::EventThread::InterceptVSyncsCallback());
593 mSfConnectionHandle =
594 mScheduler->createConnection("sfConnection", mPrimaryDispSync.get(),
595 SurfaceFlinger::sfVsyncPhaseOffsetNs,
596 [this] { resyncWithRateLimit(); },
597 [this](nsecs_t timestamp) {
598 mInterceptor->saveVSyncEvent(timestamp);
599 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800600
Ana Krulec98b5b242018-08-10 15:03:23 -0700601 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700602 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
603 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700604 } else {
605 mEventThreadSource =
606 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
607 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
608 mEventThread =
609 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
610 [this] { resyncWithRateLimit(); },
611 impl::EventThread::InterceptVSyncsCallback(),
612 "appEventThread");
613 mSfEventThreadSource =
614 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
615 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
616
617 mSFEventThread =
618 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
619 [this] { resyncWithRateLimit(); },
620 [this](nsecs_t timestamp) {
621 mInterceptor->saveVSyncEvent(timestamp);
622 },
623 "sfEventThread");
624 mEventQueue->setEventThread(mSFEventThread.get());
625 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
626 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800627
Steven Thomasb02664d2017-07-26 18:48:28 -0700628 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700629 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700630 renderEngineFeature |= (useColorManagement ?
631 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700632 renderEngineFeature |= (useContextPriority ?
633 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700634
635 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
636 getBE().mRenderEngine =
Peiyong Linf11f39b2018-09-05 14:37:41 -0700637 renderengine::RenderEngine::create(static_cast<int32_t>(compositionPixelFormat),
638 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800639 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700640
641 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
642 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800643 getBE().mHwc.reset(
644 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700645 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800646 // Process any initial hotplug and resulting display changes.
647 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700648 const auto display = getDefaultDisplayDeviceLocked();
649 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
650 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
651 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800652
Lloyd Piquefcd86612017-12-14 17:15:36 -0800653 // make the default display GLContext current so that we can create textures
654 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700655 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800656
Steven Thomas050b2c82017-03-06 11:45:16 -0800657 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700658 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700659 // This callback is called from the vr flinger dispatch thread. We
660 // need to call signalTransaction(), which requires holding
661 // mStateLock when we're not on the main thread. Acquiring
662 // mStateLock from the vr flinger dispatch thread might trigger a
663 // deadlock in surface flinger (see b/66916578), so post a message
664 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700665 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700666 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
667 mVrFlingerRequestsDisplay = requestDisplay;
668 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700669 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800670 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700671 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
672 getHwComposer()
673 .getHwcDisplayId(display->getId())
674 .value_or(0),
675 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800676 if (!mVrFlinger) {
677 ALOGE("Failed to start vrflinger");
678 }
679 }
680
Lloyd Pique379adc12018-01-22 17:31:47 -0800681 mEventControlThread = std::make_unique<impl::EventControlThread>(
682 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700683
Mathias Agopian92a979a2012-08-02 18:32:23 -0700684 // initialize our drawing state
685 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700686
Andy McFadden13a082e2012-08-24 10:16:42 -0700687 // set initial conditions (e.g. unblank default device)
688 initializeDisplays();
689
David Sodmanbc815282017-11-05 18:57:52 -0800690 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700691
Wei Wangf9b05ee2017-07-19 20:59:39 -0700692 // Inform native graphics APIs whether the present timestamp is supported:
693 if (getHwComposer().hasCapability(
694 HWC2::Capability::PresentFenceIsNotReliable)) {
695 mStartPropertySetThread = new StartPropertySetThread(false);
696 } else {
697 mStartPropertySetThread = new StartPropertySetThread(true);
698 }
699
700 if (mStartPropertySetThread->Start() != NO_ERROR) {
701 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800702 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800703
Chia-I Wud49d6692018-06-27 07:17:41 +0800704 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
705 // is used to saturate legacy sRGB content. However, to make sure the same color under
706 // Display P3 will be saturated to the same color, we intentionally break the API spec
707 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
708 // such saturation matrix on Display P3 is understood fully, the API should always return
709 // identify matrix.
710 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
711 Dataspace::SRGB_LINEAR);
712
713 // we will apply this on Display P3.
714 if (mEnhancedSaturationMatrix != mat4()) {
715 ColorSpace srgb(ColorSpace::sRGB());
716 ColorSpace displayP3(ColorSpace::DisplayP3());
717 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
718 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
719 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
720 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800721
Dan Stoza9e56aa02015-11-02 13:00:03 -0800722 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700723}
724
Romain Guy11d63f42017-07-20 12:47:14 -0700725void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700726 Mutex::Autolock _l(mStateLock);
727
Romain Guy11d63f42017-07-20 12:47:14 -0700728 char value[PROPERTY_VALUE_MAX];
729
730 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800731 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700732 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800733 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100734
735 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700736 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700737}
738
Mathias Agopiana67e4182012-06-19 17:26:12 -0700739void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800740 // Start boot animation service by setting a property mailbox
741 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700742 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800743 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700744 if (mStartPropertySetThread->join() != NO_ERROR) {
745 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800746 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700747}
748
Mathias Agopian875d8e12013-06-07 15:35:48 -0700749size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800750 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700751}
752
Mathias Agopian875d8e12013-06-07 15:35:48 -0700753size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800754 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700755}
756
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800757// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800758
Jamie Gennis582270d2011-08-17 18:19:00 -0700759bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800760 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800761 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800762 return authenticateSurfaceTextureLocked(bufferProducer);
763}
764
765bool SurfaceFlinger::authenticateSurfaceTextureLocked(
766 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800767 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800768 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800769}
770
Brian Anderson6b376712017-04-04 10:51:39 -0700771status_t SurfaceFlinger::getSupportedFrameTimestamps(
772 std::vector<FrameEvent>* outSupported) const {
773 *outSupported = {
774 FrameEvent::REQUESTED_PRESENT,
775 FrameEvent::ACQUIRE,
776 FrameEvent::LATCH,
777 FrameEvent::FIRST_REFRESH_START,
778 FrameEvent::LAST_REFRESH_START,
779 FrameEvent::GPU_COMPOSITION_DONE,
780 FrameEvent::DEQUEUE_READY,
781 FrameEvent::RELEASE,
782 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700783 ConditionalLock _l(mStateLock,
784 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700785 if (!getHwComposer().hasCapability(
786 HWC2::Capability::PresentFenceIsNotReliable)) {
787 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
788 }
789 return NO_ERROR;
790}
791
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700792status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
793 Vector<DisplayInfo>* configs) {
794 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700795 return BAD_VALUE;
796 }
797
Jesse Hall692c7232012-11-08 15:41:56 -0800798 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700799 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
800 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700801 type = i;
802 break;
803 }
804 }
805
806 if (type < 0) {
807 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700808 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700809
Mathias Agopian8b736f12012-08-13 17:54:26 -0700810 // TODO: Not sure if display density should handled by SF any longer
811 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700812 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700813 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700814 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800815 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700816 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700817 }
818 return density;
819 }
820 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700821 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700822 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700823 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700824 return getDensityFromProperty("ro.sf.lcd_density"); }
825 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700826
Dan Stoza7f7da322014-05-02 15:26:25 -0700827 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700828
Steven Thomas6d8110b2017-08-31 18:24:21 -0700829 ConditionalLock _l(mStateLock,
830 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800831 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700832 DisplayInfo info = DisplayInfo();
833
Dan Stoza9e56aa02015-11-02 13:00:03 -0800834 float xdpi = hwConfig->getDpiX();
835 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700836
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700837 info.w = hwConfig->getWidth();
838 info.h = hwConfig->getHeight();
839 // Default display viewport to display width and height
840 info.viewportW = info.w;
841 info.viewportH = info.h;
842
Dan Stoza7f7da322014-05-02 15:26:25 -0700843 if (type == DisplayDevice::DISPLAY_PRIMARY) {
844 // The density of the device is provided by a build property
845 float density = Density::getBuildDensity() / 160.0f;
846 if (density == 0) {
847 // the build doesn't provide a density -- this is wrong!
848 // use xdpi instead
849 ALOGE("ro.sf.lcd_density must be defined as a build property");
850 density = xdpi / 160.0f;
851 }
852 if (Density::getEmuDensity()) {
853 // if "qemu.sf.lcd_density" is specified, it overrides everything
854 xdpi = ydpi = density = Density::getEmuDensity();
855 density /= 160.0f;
856 }
857 info.density = density;
858
859 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700860 const auto display = getDefaultDisplayDeviceLocked();
861 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700862
863 // This is for screenrecord
864 const Rect viewport = display->getViewport();
865 if (viewport.isValid()) {
866 info.viewportW = uint32_t(viewport.getWidth());
867 info.viewportH = uint32_t(viewport.getHeight());
868 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700869 } else {
870 // TODO: where should this value come from?
871 static const int TV_DENSITY = 213;
872 info.density = TV_DENSITY / 160.0f;
873 info.orientation = 0;
874 }
875
Dan Stoza7f7da322014-05-02 15:26:25 -0700876 info.xdpi = xdpi;
877 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800878 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900879 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800880
Andy McFadden91b2ca82014-06-13 14:04:23 -0700881 // This is how far in advance a buffer must be queued for
882 // presentation at a given time. If you want a buffer to appear
883 // on the screen at time N, you must submit the buffer before
884 // (N - presentationDeadline).
885 //
886 // Normally it's one full refresh period (to give SF a chance to
887 // latch the buffer), but this can be reduced by configuring a
888 // DispSync offset. Any additional delays introduced by the hardware
889 // composer or panel must be accounted for here.
890 //
891 // We add an additional 1ms to allow for processing time and
892 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800893 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800894 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700895
896 // All non-virtual displays are currently considered secure.
897 info.secure = true;
898
Iris Chang7501ed62018-04-30 14:45:42 +0800899 if (type == DisplayDevice::DISPLAY_PRIMARY &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700900 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800901 std::swap(info.w, info.h);
902 }
903
Michael Wright28f24d02016-07-12 13:30:53 -0700904 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700905 }
906
Dan Stoza7f7da322014-05-02 15:26:25 -0700907 return NO_ERROR;
908}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700909
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700910status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
911 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700912 return BAD_VALUE;
913 }
914
915 // FIXME for now we always return stats for the primary display
916 memset(stats, 0, sizeof(*stats));
Lloyd Pique41be5d22018-06-21 13:11:48 -0700917 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
918 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700919 return NO_ERROR;
920}
921
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700922int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
923 const auto display = getDisplayDevice(displayToken);
924 if (!display) {
925 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800926 return BAD_VALUE;
927 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700928
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700929 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700930}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700931
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700932void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
933 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700934 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700935 return;
936 }
937
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700938 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700939 ALOGW("Trying to set config for virtual display");
940 return;
941 }
942
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700943 display->setActiveConfig(mode);
944 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700945}
946
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700947status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700948 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700949 Vector<DisplayInfo> configs;
950 getDisplayConfigs(displayToken, &configs);
951 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
952 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
953 configs.size());
954 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700955 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700956 const auto display = getDisplayDevice(displayToken);
957 if (!display) {
958 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
959 displayToken.get());
960 } else if (display->isVirtual()) {
961 ALOGW("Attempt to set active config %d for virtual display", mode);
962 } else {
963 setActiveConfigInternal(display, mode);
964 }
965 }));
966
Mathias Agopian888c8222012-08-04 21:10:38 -0700967 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700968}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700969status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
970 Vector<ColorMode>* outColorModes) {
971 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700972 return BAD_VALUE;
973 }
974
Michael Wright28f24d02016-07-12 13:30:53 -0700975 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700976 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
977 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700978 type = i;
979 break;
980 }
981 }
982
983 if (type < 0) {
984 return type;
985 }
986
Peiyong Lina52f0292018-03-14 17:26:31 -0700987 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700988 {
989 ConditionalLock _l(mStateLock,
990 std::this_thread::get_id() != mMainThreadId);
991 modes = getHwComposer().getColorModes(type);
992 }
Michael Wright28f24d02016-07-12 13:30:53 -0700993 outColorModes->clear();
994 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
995
996 return NO_ERROR;
997}
998
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700999ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1000 if (const auto display = getDisplayDevice(displayToken)) {
1001 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001002 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001003 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001004}
1005
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001006void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1007 Dataspace dataSpace, RenderIntent renderIntent) {
1008 ColorMode currentMode = display->getActiveColorMode();
1009 Dataspace currentDataSpace = display->getCompositionDataSpace();
1010 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001011
Peiyong Lin38e9a562018-04-10 16:24:20 -07001012 if (mode == currentMode && dataSpace == currentDataSpace &&
1013 renderIntent == currentRenderIntent) {
1014 return;
1015 }
1016
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001017 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001018 ALOGW("Trying to set config for virtual display");
1019 return;
1020 }
1021
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001022 display->setActiveColorMode(mode);
1023 display->setCompositionDataSpace(dataSpace);
1024 display->setActiveRenderIntent(renderIntent);
1025 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001026
1027 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001028 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1029 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001030}
1031
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001032status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001033 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001034 Vector<ColorMode> modes;
1035 getDisplayColorModes(displayToken, &modes);
1036 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1037 if (mode < ColorMode::NATIVE || !exists) {
1038 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1039 decodeColorMode(mode).c_str(), mode, displayToken.get());
1040 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001041 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001042 const auto display = getDisplayDevice(displayToken);
1043 if (!display) {
1044 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1045 decodeColorMode(mode).c_str(), mode, displayToken.get());
1046 } else if (display->isVirtual()) {
1047 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1048 decodeColorMode(mode).c_str(), mode);
1049 } else {
1050 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1051 RenderIntent::COLORIMETRIC);
1052 }
1053 }));
1054
Michael Wright28f24d02016-07-12 13:30:53 -07001055 return NO_ERROR;
1056}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001057
Svetoslavd85084b2014-03-20 10:28:31 -07001058status_t SurfaceFlinger::clearAnimationFrameStats() {
1059 Mutex::Autolock _l(mStateLock);
1060 mAnimFrameTracker.clearStats();
1061 return NO_ERROR;
1062}
1063
1064status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1065 Mutex::Autolock _l(mStateLock);
1066 mAnimFrameTracker.getStats(outStats);
1067 return NO_ERROR;
1068}
1069
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001070status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1071 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001072 Mutex::Autolock _l(mStateLock);
1073
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001074 const auto display = getDisplayDeviceLocked(displayToken);
1075 if (!display) {
1076 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001077 return BAD_VALUE;
1078 }
1079
Peiyong Linfb069302018-04-25 14:34:31 -07001080 // At this point the DisplayDeivce should already be set up,
1081 // meaning the luminance information is already queried from
1082 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001083 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001084 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1085 capabilities.getDesiredMaxLuminance(),
1086 capabilities.getDesiredMaxAverageLuminance(),
1087 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001088
1089 return NO_ERROR;
1090}
1091
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001092status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001093 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001094 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001095
Chia-I Wu90f669f2017-10-05 14:24:41 -07001096 if (mInjectVSyncs == enable) {
1097 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001098 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001099
Ana Krulec98b5b242018-08-10 15:03:23 -07001100 // TODO(akrulec): Part of the Injector should be refactored, so that it
1101 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001102 if (enable) {
1103 ALOGV("VSync Injections enabled");
1104 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001105 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001106 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001107 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001108 impl::EventThread::InterceptVSyncsCallback(),
1109 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001110 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001111 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001112 } else {
1113 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001114 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001115 }
1116
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001117 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001118 }));
1119
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001120 return NO_ERROR;
1121}
1122
1123status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001124 Mutex::Autolock _l(mStateLock);
1125
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001126 if (!mInjectVSyncs) {
1127 ALOGE("VSync Injections not enabled");
1128 return BAD_VALUE;
1129 }
1130 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1131 ALOGV("Injecting VSync inside SurfaceFlinger");
1132 mVSyncInjector->onInjectSyncEvent(when);
1133 }
1134 return NO_ERROR;
1135}
1136
Lloyd Pique755e3192018-01-31 16:46:15 -08001137status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1138 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001139 // Try to acquire a lock for 1s, fail gracefully
1140 const status_t err = mStateLock.timedLock(s2ns(1));
1141 const bool locked = (err == NO_ERROR);
1142 if (!locked) {
1143 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1144 return TIMED_OUT;
1145 }
1146
1147 outLayers->clear();
1148 mCurrentState.traverseInZOrder([&](Layer* layer) {
1149 outLayers->push_back(layer->getLayerDebugInfo());
1150 });
1151
1152 mStateLock.unlock();
1153 return NO_ERROR;
1154}
1155
Peiyong Lin0256f722018-08-31 15:45:10 -07001156status_t SurfaceFlinger::getCompositionPreference(Dataspace* outDataSpace,
1157 ui::PixelFormat* outPixelFormat) const {
1158 *outDataSpace = compositionDataSpace;
1159 *outPixelFormat = compositionPixelFormat;
1160 return NO_ERROR;
1161}
1162
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001163// ----------------------------------------------------------------------------
1164
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001165sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1166 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001167 if (mUseScheduler) {
1168 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1169 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1170 } else {
1171 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1172 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001173 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001174 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1175 return mSFEventThread->createEventConnection();
1176 } else {
1177 return mEventThread->createEventConnection();
1178 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001179 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001180}
1181
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001182// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001183
1184void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001185 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001186}
1187
1188void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001189 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001190}
1191
1192void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001193 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001194}
1195
1196void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001197 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001198 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001199}
1200
1201status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001202 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001203 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001204}
1205
1206status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001207 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001208 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001209 if (res == NO_ERROR) {
1210 msg->wait();
1211 }
1212 return res;
1213}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001214
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001215void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001216 do {
1217 waitForEvent();
1218 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001219}
1220
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001221void SurfaceFlinger::enableHardwareVsync() {
1222 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001223 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001224 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001225 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001226 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001227 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001228}
1229
Jesse Hall948fe0c2013-10-14 12:56:09 -07001230void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001231 Mutex::Autolock _l(mHWVsyncLock);
1232
Jesse Hall948fe0c2013-10-14 12:56:09 -07001233 if (makeAvailable) {
1234 mHWVsyncAvailable = true;
1235 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001236 // Hardware vsync is not currently available, so abort the resync
1237 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001238 return;
1239 }
1240
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001241 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1242 if (!getHwComposer().isConnected(displayId)) {
1243 return;
1244 }
1245
1246 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001247 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001248
Lloyd Pique41be5d22018-06-21 13:11:48 -07001249 mPrimaryDispSync->reset();
1250 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001251
1252 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001253 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001254 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001255 mPrimaryHWVsyncEnabled = true;
1256 }
1257}
1258
Jesse Hall948fe0c2013-10-14 12:56:09 -07001259void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001260 Mutex::Autolock _l(mHWVsyncLock);
1261 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001262 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001263 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001264 mPrimaryHWVsyncEnabled = false;
1265 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001266 if (makeUnavailable) {
1267 mHWVsyncAvailable = false;
1268 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001269}
1270
Tim Murray4a4e4a22016-04-19 16:29:23 +00001271void SurfaceFlinger::resyncWithRateLimit() {
1272 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001273
1274 // No explicit locking is needed here since EventThread holds a lock while calling this method
1275 static nsecs_t sLastResyncAttempted = 0;
1276 const nsecs_t now = systemTime();
1277 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001278 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001279 }
Dan Stoza57164302017-05-08 14:03:54 -07001280 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001281}
1282
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001283void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1284 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001285 ATRACE_NAME("SF onVsync");
1286
Steven Thomas3cfac282017-02-06 12:29:30 -08001287 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001288 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001289 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001290 return;
1291 }
1292
1293 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001294 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001295 return;
1296 }
1297
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001298 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1299 // For now, we don't do anything with external display vsyncs.
1300 return;
1301 }
1302
Jamie Gennisd1700752013-10-14 12:22:52 -07001303 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001304
Jamie Gennisd1700752013-10-14 12:22:52 -07001305 { // Scope for the lock
1306 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001307 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001308 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001309 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001310 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001311
1312 if (needsHwVsync) {
1313 enableHardwareVsync();
1314 } else {
1315 disableHardwareVsync(false);
1316 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001317}
1318
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001319void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001320 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1321 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001322}
1323
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001324void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001325 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001326 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001327 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001328
Lloyd Piqueba04e622017-12-14 17:11:26 -08001329 // Ignore events that do not have the right sequenceId.
1330 if (sequenceId != getBE().mComposerSequenceId) {
1331 return;
1332 }
1333
Steven Thomasb02664d2017-07-26 18:48:28 -07001334 // Only lock if we're not on the main thread. This function is normally
1335 // called on a hwbinder thread, but for the primary display it's called on
1336 // the main thread with the state lock already held, so don't attempt to
1337 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001338 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001339
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001340 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001341
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001342 if (std::this_thread::get_id() == mMainThreadId) {
1343 // Process all pending hot plug events immediately if we are on the main thread.
1344 processDisplayHotplugEventsLocked();
1345 }
1346
Lloyd Piqueba04e622017-12-14 17:11:26 -08001347 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001348}
1349
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001350void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001351 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001352 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001353 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001354 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001355 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001356}
1357
Dan Stoza9e56aa02015-11-02 13:00:03 -08001358void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001359 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001360 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001361 getHwComposer().setVsyncEnabled(disp,
1362 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001363}
1364
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001365// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001366void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001367 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001368 // Clear the drawing state so that the logic inside of
1369 // handleTransactionLocked will fire. It will determine the delta between
1370 // mCurrentState and mDrawingState and re-apply all changes when we make the
1371 // transition.
1372 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001373 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001374 mDisplays.clear();
1375}
1376
Steven Thomas050b2c82017-03-06 11:45:16 -08001377void SurfaceFlinger::updateVrFlinger() {
1378 if (!mVrFlinger)
1379 return;
1380 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001381 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001382 return;
1383 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001384
David Sodman105b7dc2017-11-04 20:28:14 -07001385 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001386 ALOGE("Vr flinger is only supported for remote hardware composer"
1387 " service connections. Ignoring request to transition to vr"
1388 " flinger.");
1389 mVrFlingerRequestsDisplay = false;
1390 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001391 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001392
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001393 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001394
Steven Thomas0123ac62018-07-12 11:32:34 -07001395 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001396 LOG_ALWAYS_FATAL_IF(!display);
1397 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001398 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1399 // called below. Clear the reference now so we don't accidentally use it
1400 // later.
1401 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001402
Steven Thomasb02664d2017-07-26 18:48:28 -07001403 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001404 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001405 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001406
Steven Thomasb02664d2017-07-26 18:48:28 -07001407 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001408 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001409 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1410 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001411 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001412
David Sodman105b7dc2017-11-04 20:28:14 -07001413 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1414 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001415
1416 if (vrFlingerRequestsDisplay) {
1417 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001418 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001419
1420 mVisibleRegionsDirty = true;
1421 invalidateHwcGeometry();
1422
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001423 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001424 display = getDefaultDisplayDeviceLocked();
1425 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001426 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001427
Steven Thomasb02664d2017-07-26 18:48:28 -07001428 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001429 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001430 const nsecs_t period = activeConfig->getVsyncPeriod();
1431 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001432
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001433 // The present fences returned from vr_hwc are not an accurate
1434 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001435 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1436 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001437
Steven Thomasb02664d2017-07-26 18:48:28 -07001438 // Use phase of 0 since phase is not known.
1439 // Use latency of 0, which will snap to the ideal latency.
1440 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001441
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001442 resyncToHardwareVsync(false);
1443
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001444 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001445 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001446}
1447
Mathias Agopian4fec8732012-06-29 14:12:52 -07001448void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001449 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001450 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001451 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001452 bool frameMissed = !mHadClientComposition &&
1453 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001454 (mPreviousPresentFence->getSignalTime() ==
1455 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001456 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001457 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001458 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001459 mTimeStats.incrementMissedFrames();
1460 if (mPropagateBackpressure) {
1461 signalLayerUpdate();
1462 break;
1463 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001464 }
Dan Stoza50182882016-07-08 12:02:20 -07001465
Steven Thomas050b2c82017-03-06 11:45:16 -08001466 // Now that we're going to make it to the handleMessageTransaction()
1467 // call below it's safe to call updateVrFlinger(), which will
1468 // potentially trigger a display handoff.
1469 updateVrFlinger();
1470
Dan Stoza6b9454d2014-11-07 16:00:59 -08001471 bool refreshNeeded = handleMessageTransaction();
1472 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001473 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001474 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001475 // Signal a refresh if a transaction modified the window state,
1476 // a new buffer was latched, or if HWC has requested a full
1477 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001478 signalRefresh();
1479 }
1480 break;
1481 }
1482 case MessageQueue::REFRESH: {
1483 handleMessageRefresh();
1484 break;
1485 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001486 }
1487}
1488
Dan Stoza6b9454d2014-11-07 16:00:59 -08001489bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001490 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001491 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001492 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001493 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001494 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001495 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001496}
1497
Mathias Agopian4fec8732012-06-29 14:12:52 -07001498void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001499 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001500
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001501 mRefreshPending = false;
1502
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001503 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001504 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001505 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001506 calculateWorkingSet();
David Sodman10a41ff2018-08-05 12:14:17 -07001507
David Sodmanfa9b2af2017-12-24 13:28:59 -08001508 for (const auto& [token, display] : mDisplays) {
David Sodman10a41ff2018-08-05 12:14:17 -07001509 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001510 beginFrame(display);
David Sodman10a41ff2018-08-05 12:14:17 -07001511 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
1512 setUpHWComposer(compositionInfo);
1513 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001514 prepareFrame(display);
1515 doDebugFlashRegions(display, repaintEverything);
1516 doComposition(display, repaintEverything);
1517 }
1518
Adrian Roos1e1a1282017-11-01 19:05:31 +01001519 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001520 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001521
1522 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001523 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001524
Dan Stozabfbffeb2016-07-21 14:49:33 -07001525 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001526 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001527 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001528 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001529 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001530
Jorim Jaggi90535212018-05-23 23:44:06 +02001531 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001532
David Sodman7e4ae112018-02-09 15:02:28 -08001533 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001534 for (const auto& [token, display] : mDisplays) {
1535 const auto displayId = display->getId();
David Sodman7e4ae112018-02-09 15:02:28 -08001536 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[displayId]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001537 compositionInfo.hwc.hwcLayer = nullptr;
1538 }
David Sodmanba340492018-08-05 21:51:33 -07001539 }
David Sodman7e4ae112018-02-09 15:02:28 -08001540
1541 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001542}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001543
David Sodmanfa9b2af2017-12-24 13:28:59 -08001544
1545bool SurfaceFlinger::handleMessageInvalidate() {
1546 ATRACE_CALL();
1547 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001548}
1549
David Sodman79bba0e2018-08-05 18:07:49 -07001550void SurfaceFlinger::calculateWorkingSet() {
1551 ATRACE_CALL();
1552 ALOGV(__FUNCTION__);
1553
David Sodman79bba0e2018-08-05 18:07:49 -07001554 // build the h/w work list
1555 if (CC_UNLIKELY(mGeometryInvalid)) {
1556 mGeometryInvalid = false;
1557 for (const auto& [token, display] : mDisplays) {
1558 const auto displayId = display->getId();
1559 if (displayId >= 0) {
1560 const Vector<sp<Layer>>& currentLayers(
1561 display->getVisibleLayersSortedByZ());
1562 for (size_t i = 0; i < currentLayers.size(); i++) {
1563 const auto& layer = currentLayers[i];
1564
1565 if (!layer->hasHwcLayer(displayId)) {
1566 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1567 layer->forceClientComposition(displayId);
1568 continue;
1569 }
1570 }
1571
1572 layer->setGeometry(display, i);
1573 if (mDebugDisableHWC || mDebugRegion) {
1574 layer->forceClientComposition(displayId);
1575 }
1576 }
1577 }
1578 }
1579 }
1580
1581 // Set the per-frame data
1582 for (const auto& [token, display] : mDisplays) {
1583 const auto displayId = display->getId();
1584 if (displayId < 0) {
1585 continue;
1586 }
1587
1588 if (mDrawingState.colorMatrixChanged) {
1589 display->setColorTransform(mDrawingState.colorMatrix);
1590 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1591 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1592 "display %d: %d", displayId, result);
1593 }
1594 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1595 if (layer->isHdrY410()) {
1596 layer->forceClientComposition(displayId);
1597 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1598 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1599 !display->hasHDR10Support()) {
1600 layer->forceClientComposition(displayId);
1601 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1602 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1603 !display->hasHLGSupport()) {
1604 layer->forceClientComposition(displayId);
1605 }
1606
Peiyong Lind3788632018-09-18 16:01:31 -07001607 // TODO(b/111562338) remove when composer 2.3 is shipped.
1608 if (layer->hasColorTransform()) {
1609 layer->forceClientComposition(displayId);
1610 }
1611
David Sodman79bba0e2018-08-05 18:07:49 -07001612 if (layer->getForceClientComposition(displayId)) {
1613 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1614 layer->setCompositionType(displayId, HWC2::Composition::Client);
1615 continue;
1616 }
1617
1618 layer->setPerFrameData(display);
1619 }
1620
Peiyong Lin13effd12018-07-24 17:01:47 -07001621 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001622 ColorMode colorMode;
1623 Dataspace dataSpace;
1624 RenderIntent renderIntent;
1625 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1626 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1627 }
1628 }
1629
1630 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001631
1632 for (const auto& [token, display] : mDisplays) {
David Sodman15fb96e2018-01-07 10:23:24 -08001633 const auto displayId = display->getId();
1634 getBE().mCompositionInfo[displayId].clear();
David Sodmanba340492018-08-05 21:51:33 -07001635 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1636 auto displayId = display->getId();
1637 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1638 if (!layer->setHwcLayer(displayId)) {
1639 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1640 }
David Sodman15fb96e2018-01-07 10:23:24 -08001641 layer->getBE().compositionInfo.hwc.displayId = displayId;
1642 getBE().mCompositionInfo[displayId].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001643 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1644 }
1645 }
David Sodman79bba0e2018-08-05 18:07:49 -07001646}
1647
David Sodmanfa9b2af2017-12-24 13:28:59 -08001648void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001649{
David Sodmanfb95bcc2017-12-22 15:45:30 -08001650 const auto displayId = display->getId();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001651 // is debugging enabled
1652 if (CC_LIKELY(!mDebugRegion))
1653 return;
1654
David Sodmanfa9b2af2017-12-24 13:28:59 -08001655 if (display->isPoweredOn()) {
1656 // transform the dirty region into this screen's coordinate space
1657 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1658 if (!dirtyRegion.isEmpty()) {
1659 // redraw the whole screen
1660 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001661
David Sodmanfa9b2af2017-12-24 13:28:59 -08001662 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001663 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001664 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001665
David Sodmanfa9b2af2017-12-24 13:28:59 -08001666 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001667 }
1668 }
1669
David Sodmanfa9b2af2017-12-24 13:28:59 -08001670 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001671
1672 if (mDebugRegion > 1) {
1673 usleep(mDebugRegion * 1000);
1674 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001675
David Sodmanfa9b2af2017-12-24 13:28:59 -08001676 if (display->isPoweredOn()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08001677 status_t result = display->prepareFrame(
1678 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001679 ALOGE_IF(result != NO_ERROR,
1680 "prepareFrame for display %d failed:"
1681 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001682 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001683 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001684}
1685
Adrian Roos1e1a1282017-11-01 19:05:31 +01001686void SurfaceFlinger::doTracing(const char* where) {
1687 ATRACE_CALL();
1688 ATRACE_NAME(where);
1689 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001690 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001691 }
1692}
1693
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001694void SurfaceFlinger::logLayerStats() {
1695 ATRACE_CALL();
1696 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001697 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001698 if (display->isPrimary()) {
1699 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001700 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001701 }
1702 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001703
1704 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001705 }
1706}
1707
David Sodman2b406362017-12-15 13:33:47 -08001708void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001709{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001710 ATRACE_CALL();
1711 ALOGV("preComposition");
1712
David Sodman2b406362017-12-15 13:33:47 -08001713 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1714
Mathias Agopiancd60f992012-08-16 16:28:27 -07001715 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001716 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001717 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001718 needExtraInvalidate = true;
1719 }
Robert Carr2047fae2016-11-28 14:09:09 -08001720 });
1721
Mathias Agopiancd60f992012-08-16 16:28:27 -07001722 if (needExtraInvalidate) {
1723 signalLayerUpdate();
1724 }
1725}
1726
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001727void SurfaceFlinger::updateCompositorTiming(
1728 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1729 std::shared_ptr<FenceTime>& presentFenceTime) {
1730 // Update queue of past composite+present times and determine the
1731 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001732 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001733 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001734 while (!getBE().mCompositePresentTimes.empty()) {
1735 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001736 // Cached values should have been updated before calling this method,
1737 // which helps avoid duplicate syscalls.
1738 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1739 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1740 break;
1741 }
1742 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001743 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001744 }
1745
1746 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001747 while (getBE().mCompositePresentTimes.size() > 16) {
1748 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001749 }
1750
Brian Andersond0010582017-03-07 13:20:31 -08001751 setCompositorTimingSnapped(
1752 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1753}
1754
1755void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1756 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001757 // Integer division and modulo round toward 0 not -inf, so we need to
1758 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001759 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001760 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1761 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1762
Brian Andersond0010582017-03-07 13:20:31 -08001763 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1764 if (idealLatency <= 0) {
1765 idealLatency = vsyncInterval;
1766 }
1767
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001768 // Snap the latency to a value that removes scheduling jitter from the
1769 // composition and present times, which often have >1ms of jitter.
1770 // Reducing jitter is important if an app attempts to extrapolate
1771 // something (such as user input) to an accurate diasplay time.
1772 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1773 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001774 nsecs_t bias = vsyncInterval / 2;
1775 int64_t extraVsyncs =
1776 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1777 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1778 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001779
David Sodman99974d22017-11-28 12:04:33 -08001780 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1781 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1782 getBE().mCompositorTiming.interval = vsyncInterval;
1783 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001784}
1785
David Sodman2b406362017-12-15 13:33:47 -08001786void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001787{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001788 ATRACE_CALL();
1789 ALOGV("postComposition");
1790
Brian Anderson3546a3f2016-07-14 11:51:14 -07001791 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001792 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001793 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001794 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001795 }
1796
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001797 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001798 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001799
David Sodman73beded2017-11-15 11:56:06 -08001800 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001801 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001802 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001803 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001804 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001805 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001806 } else {
1807 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1808 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001809
David Sodman73beded2017-11-15 11:56:06 -08001810 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001811 mPreviousPresentFence =
1812 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1813 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001814 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001815
Lloyd Pique41be5d22018-06-21 13:11:48 -07001816 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1817 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001818
David Sodman2b406362017-12-15 13:33:47 -08001819 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001820 // when we started doing work for this frame, but that should be okay
1821 // since updateCompositorTiming has snapping logic.
1822 updateCompositorTiming(
David Sodman2b406362017-12-15 13:33:47 -08001823 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001824 CompositorTiming compositorTiming;
1825 {
David Sodman99974d22017-11-28 12:04:33 -08001826 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1827 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001828 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001829
Robert Carr2047fae2016-11-28 14:09:09 -08001830 mDrawingState.traverseInZOrder([&](Layer* layer) {
1831 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001832 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001833 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001834 recordBufferingStats(layer->getName().string(),
1835 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001836 }
Robert Carr2047fae2016-11-28 14:09:09 -08001837 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001838
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001839 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001840 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001841 enableHardwareVsync();
1842 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001843 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001844 }
1845 }
1846
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001847 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001848 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001849 enableHardwareVsync();
1850 }
1851 }
1852
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001853 if (mAnimCompositionPending) {
1854 mAnimCompositionPending = false;
1855
Brian Anderson4e606e32017-03-16 15:34:57 -07001856 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001857 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001858 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001859 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001860 // The HWC doesn't support present fences, so use the refresh
1861 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001862 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001863 mAnimFrameTracker.setActualPresentTime(presentTime);
1864 }
1865 mAnimFrameTracker.advanceFrame();
1866 }
Dan Stozab90cf072015-03-05 11:05:59 -08001867
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001868 mTimeStats.incrementTotalFrames();
1869 if (mHadClientComposition) {
1870 mTimeStats.incrementClientCompositionFrames();
1871 }
1872
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001873 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001874 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001875 return;
1876 }
1877
1878 nsecs_t currentTime = systemTime();
1879 if (mHasPoweredOff) {
1880 mHasPoweredOff = false;
1881 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001882 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001883 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001884 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1885 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001886 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001887 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001888 }
David Sodman4a36e932017-11-07 14:29:47 -08001889 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001890 }
David Sodman4a36e932017-11-07 14:29:47 -08001891 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001892
1893 {
1894 std::lock_guard lock(mTexturePoolMutex);
1895 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1896 if (refillCount > 0) {
1897 const size_t offset = mTexturePool.size();
1898 mTexturePool.resize(mTexturePoolSize);
1899 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1900 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1901 }
1902 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001903}
1904
1905void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001906 ATRACE_CALL();
1907 ALOGV("rebuildLayerStacks");
1908
Mathias Agopiancd60f992012-08-16 16:28:27 -07001909 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001910 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001911 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001912 mVisibleRegionsDirty = false;
1913 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001914
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001915 for (const auto& pair : mDisplays) {
1916 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001917 Region opaqueRegion;
1918 Region dirtyRegion;
1919 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001920 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001921 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001922 const Rect bounds = display->getBounds();
1923 if (display->isPoweredOn()) {
1924 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001925
Jeff Sharkey76488112017-02-27 14:15:18 -07001926 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001927 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001928 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001929 Region drawRegion(tr.transform(
1930 layer->visibleNonTransparentRegion));
1931 drawRegion.andSelf(bounds);
1932 if (!drawRegion.isEmpty()) {
1933 layersSortedByZ.add(layer);
1934 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001935 // Clear out the HWC layer if this layer was
1936 // previously visible, but no longer is
1937 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001938 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001939 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001940 // WM changes display->layerStack upon sleep/awake.
1941 // Here we make sure we delete the HWC layers even if
1942 // WM changed their layer stack.
1943 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001944 }
1945
1946 // If a layer is not going to get a release fence because
1947 // it is invisible, but it is also going to release its
1948 // old buffer, add it to the list of layers needing
1949 // fences.
1950 if (hwcLayerDestroyed) {
1951 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1952 mLayersWithQueuedFrames.cend(), layer);
1953 if (found != mLayersWithQueuedFrames.cend()) {
1954 layersNeedingFences.add(layer);
1955 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001956 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001957 });
1958 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001959 display->setVisibleLayersSortedByZ(layersSortedByZ);
1960 display->setLayersNeedingFences(layersNeedingFences);
1961 display->undefinedRegion.set(bounds);
1962 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1963 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001964 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001965 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001966}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001967
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001968// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001969// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001970// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001971// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001972// The returned HDR data space is one of
1973// - Dataspace::UNKNOWN
1974// - Dataspace::BT2020_HLG
1975// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001976Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1977 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001978 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001979 *outHdrDataSpace = Dataspace::UNKNOWN;
1980
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001981 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001982 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001983 case Dataspace::V0_SCRGB:
1984 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001985 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001986 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001987 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001988 case Dataspace::BT2020_PQ:
1989 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001990 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001991 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001992 case Dataspace::BT2020_HLG:
1993 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001994 // When there's mixed PQ content and HLG content, we set the HDR
1995 // data space to be BT2020_PQ and convert HLG to PQ.
1996 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1997 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001998 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001999 break;
2000 default:
2001 break;
2002 }
Romain Guy54f154a2017-10-24 21:40:32 +01002003 }
2004
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002005 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002006}
2007
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002008// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002009void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2010 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002011 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2012 *outMode = ColorMode::NATIVE;
2013 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002014 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002015 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002016 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002017
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002018 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002019 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002020
Peiyong Lindfde5112018-06-05 10:58:41 -07002021 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002022 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002023 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002024 if (isHdr) {
2025 bestDataSpace = hdrDataSpace;
2026 }
2027
Chia-I Wu0d711262018-05-21 15:19:35 -07002028 RenderIntent intent;
2029 switch (mDisplayColorSetting) {
2030 case DisplayColorSetting::MANAGED:
2031 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002032 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002033 break;
2034 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002035 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002036 break;
2037 default: // vendor display color setting
2038 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2039 break;
2040 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002041
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002042 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002043}
2044
David Sodman10a41ff2018-08-05 12:14:17 -07002045void SurfaceFlinger::configureSidebandComposition(const CompositionInfo& compositionInfo) const
2046{
2047 HWC2::Error error;
2048 LOG_ALWAYS_FATAL_IF(compositionInfo.hwc.sidebandStream == nullptr,
2049 "CompositionType is sideband, but sideband stream is nullptr");
2050 error = (compositionInfo.hwc.hwcLayer)
2051 ->setSidebandStream(compositionInfo.hwc.sidebandStream->handle());
2052 if (error != HWC2::Error::None) {
2053 ALOGE("[SF] Failed to set sideband stream %p: %s (%d)",
2054 compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
2055 static_cast<int32_t>(error));
2056 }
2057}
2058
2059void SurfaceFlinger::configureHwcCommonData(const CompositionInfo& compositionInfo) const
2060{
2061 HWC2::Error error;
2062
2063 if (!compositionInfo.hwc.skipGeometry) {
2064 error = (compositionInfo.hwc.hwcLayer)->setBlendMode(compositionInfo.hwc.blendMode);
2065 ALOGE_IF(error != HWC2::Error::None,
2066 "[SF] Failed to set blend mode %s:"
2067 " %s (%d)",
2068 to_string(compositionInfo.hwc.blendMode).c_str(), to_string(error).c_str(),
2069 static_cast<int32_t>(error));
2070
2071 error = (compositionInfo.hwc.hwcLayer)->setDisplayFrame(compositionInfo.hwc.displayFrame);
2072 ALOGE_IF(error != HWC2::Error::None,
2073 "[SF] Failed to set the display frame [%d, %d, %d, %d] %s (%d)",
2074 compositionInfo.hwc.displayFrame.left,
2075 compositionInfo.hwc.displayFrame.right,
2076 compositionInfo.hwc.displayFrame.top,
2077 compositionInfo.hwc.displayFrame.bottom,
2078 to_string(error).c_str(), static_cast<int32_t>(error));
2079
2080 error = (compositionInfo.hwc.hwcLayer)->setSourceCrop(compositionInfo.hwc.sourceCrop);
2081 ALOGE_IF(error != HWC2::Error::None,
2082 "[SF] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: %s (%d)",
2083 compositionInfo.hwc.sourceCrop.left,
2084 compositionInfo.hwc.sourceCrop.right,
2085 compositionInfo.hwc.sourceCrop.top,
2086 compositionInfo.hwc.sourceCrop.bottom,
2087 to_string(error).c_str(), static_cast<int32_t>(error));
2088
2089 error = (compositionInfo.hwc.hwcLayer)->setPlaneAlpha(compositionInfo.hwc.alpha);
2090 ALOGE_IF(error != HWC2::Error::None,
2091 "[SF] Failed to set plane alpha %.3f: "
2092 "%s (%d)",
2093 compositionInfo.hwc.alpha,
2094 to_string(error).c_str(), static_cast<int32_t>(error));
2095
2096
2097 error = (compositionInfo.hwc.hwcLayer)->setZOrder(compositionInfo.hwc.z);
2098 ALOGE_IF(error != HWC2::Error::None,
2099 "[SF] Failed to set Z %u: %s (%d)",
2100 compositionInfo.hwc.z,
2101 to_string(error).c_str(), static_cast<int32_t>(error));
2102
2103 error = (compositionInfo.hwc.hwcLayer)
2104 ->setInfo(compositionInfo.hwc.type, compositionInfo.hwc.appId);
2105 ALOGE_IF(error != HWC2::Error::None,
2106 "[SF] Failed to set info (%d)",
2107 static_cast<int32_t>(error));
2108
2109 error = (compositionInfo.hwc.hwcLayer)->setTransform(compositionInfo.hwc.transform);
2110 ALOGE_IF(error != HWC2::Error::None,
2111 "[SF] Failed to set transform %s: "
2112 "%s (%d)",
2113 to_string(compositionInfo.hwc.transform).c_str(), to_string(error).c_str(),
2114 static_cast<int32_t>(error));
2115 }
2116
2117 error = (compositionInfo.hwc.hwcLayer)->setCompositionType(compositionInfo.compositionType);
2118 ALOGE_IF(error != HWC2::Error::None,
2119 "[SF] Failed to set composition type: %s (%d)",
2120 to_string(error).c_str(), static_cast<int32_t>(error));
2121
2122 error = (compositionInfo.hwc.hwcLayer)->setDataspace(compositionInfo.hwc.dataspace);
2123 ALOGE_IF(error != HWC2::Error::None,
2124 "[SF] Failed to set dataspace: %s (%d)",
2125 to_string(error).c_str(), static_cast<int32_t>(error));
2126
2127 error = (compositionInfo.hwc.hwcLayer)->setPerFrameMetadata(
2128 compositionInfo.hwc.supportedPerFrameMetadata, compositionInfo.hwc.hdrMetadata);
2129 ALOGE_IF(error != HWC2::Error::None && error != HWC2::Error::Unsupported,
2130 "[SF] Failed to set hdrMetadata: %s (%d)",
2131 to_string(error).c_str(), static_cast<int32_t>(error));
2132
2133 if (compositionInfo.compositionType == HWC2::Composition::SolidColor) {
2134 error = (compositionInfo.hwc.hwcLayer)->setColor(compositionInfo.hwc.color);
2135 ALOGE_IF(error != HWC2::Error::None,
2136 "[SF] Failed to set color: %s (%d)",
2137 to_string(error).c_str(), static_cast<int32_t>(error));
2138 }
2139
2140 error = (compositionInfo.hwc.hwcLayer)->setVisibleRegion(compositionInfo.hwc.visibleRegion);
2141 ALOGE_IF(error != HWC2::Error::None,
2142 "[SF] Failed to set visible region: %s (%d)",
2143 to_string(error).c_str(), static_cast<int32_t>(error));
2144
2145 error = (compositionInfo.hwc.hwcLayer)->setSurfaceDamage(compositionInfo.hwc.surfaceDamage);
2146 ALOGE_IF(error != HWC2::Error::None,
2147 "[SF] Failed to set surface damage: %s (%d)",
2148 to_string(error).c_str(), static_cast<int32_t>(error));
Peiyong Lind3788632018-09-18 16:01:31 -07002149
2150 error = (compositionInfo.hwc.hwcLayer)->setColorTransform(compositionInfo.hwc.colorTransform);
David Sodman10a41ff2018-08-05 12:14:17 -07002151}
2152
2153void SurfaceFlinger::configureDeviceComposition(const CompositionInfo& compositionInfo) const
2154{
2155 HWC2::Error error;
2156
2157 if (compositionInfo.hwc.fence) {
2158 error = (compositionInfo.hwc.hwcLayer)->setBuffer(compositionInfo.mBufferSlot,
2159 compositionInfo.mBuffer, compositionInfo.hwc.fence);
2160 ALOGE_IF(error != HWC2::Error::None,
2161 "[SF] Failed to set buffer: %s (%d)",
2162 to_string(error).c_str(), static_cast<int32_t>(error));
2163 }
2164}
2165
David Sodmanfa9b2af2017-12-24 13:28:59 -08002166void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002167{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002168 bool dirty = !display->getDirtyRegion(false).isEmpty();
2169 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2170 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002171
David Sodmanfa9b2af2017-12-24 13:28:59 -08002172 // If nothing has changed (!dirty), don't recompose.
2173 // If something changed, but we don't currently have any visible layers,
2174 // and didn't when we last did a composition, then skip it this time.
2175 // The second rule does two things:
2176 // - When all layers are removed from a display, we'll emit one black
2177 // frame, then nothing more until we get new layers.
2178 // - When a display is created with a private layer stack, we won't
2179 // emit any black frames until a layer is added to the layer stack.
2180 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002181
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002182 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2183 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002184 mustRecompose ? "doing" : "skipping",
2185 dirty ? "+" : "-",
2186 empty ? "+" : "-",
2187 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002188
David Sodmanfa9b2af2017-12-24 13:28:59 -08002189 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002190
David Sodmanfa9b2af2017-12-24 13:28:59 -08002191 if (mustRecompose) {
2192 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002193 }
2194}
2195
David Sodmanfa9b2af2017-12-24 13:28:59 -08002196void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002197{
David Sodmanfb95bcc2017-12-22 15:45:30 -08002198 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002199 if (!display->isPoweredOn()) {
2200 return;
David Sodman2b406362017-12-15 13:33:47 -08002201 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002202
David Sodmanfb95bcc2017-12-22 15:45:30 -08002203 status_t result = display->prepareFrame(
2204 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08002205 ALOGE_IF(result != NO_ERROR,
2206 "prepareFrame for display %d failed:"
2207 " %d (%s)",
2208 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002209}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002210
David Sodman10a41ff2018-08-05 12:14:17 -07002211void SurfaceFlinger::setUpHWComposer(const CompositionInfo& compositionInfo) {
2212 ATRACE_CALL();
2213 ALOGV("setUpHWComposer");
2214
2215 switch (compositionInfo.compositionType)
2216 {
2217 case HWC2::Composition::Invalid:
David Sodmana6d42332018-08-29 14:07:04 -07002218 break;
2219
David Sodman10a41ff2018-08-05 12:14:17 -07002220 case HWC2::Composition::Client:
David Sodmana6d42332018-08-29 14:07:04 -07002221 if (compositionInfo.hwc.hwcLayer) {
2222 auto error = (compositionInfo.hwc.hwcLayer)->
2223 setCompositionType(compositionInfo.compositionType);
2224 ALOGE_IF(error != HWC2::Error::None,
2225 "[SF] Failed to set composition type: %s (%d)",
2226 to_string(error).c_str(), static_cast<int32_t>(error));
2227 }
David Sodman10a41ff2018-08-05 12:14:17 -07002228 break;
2229
2230 case HWC2::Composition::Sideband:
2231 configureHwcCommonData(compositionInfo);
2232 configureSidebandComposition(compositionInfo);
2233 break;
2234
2235 case HWC2::Composition::SolidColor:
2236 configureHwcCommonData(compositionInfo);
2237 break;
2238
2239 case HWC2::Composition::Device:
2240 case HWC2::Composition::Cursor:
2241 configureHwcCommonData(compositionInfo);
2242 configureDeviceComposition(compositionInfo);
2243 break;
2244 }
2245}
2246
David Sodmanfa9b2af2017-12-24 13:28:59 -08002247void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002248 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002249 ALOGV("doComposition");
2250
David Sodmanfa9b2af2017-12-24 13:28:59 -08002251 if (display->isPoweredOn()) {
2252 // transform the dirty region into this screen's coordinate space
2253 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002254
David Sodmanfa9b2af2017-12-24 13:28:59 -08002255 // repaint the framebuffer (if needed)
2256 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002257
David Sodmanfa9b2af2017-12-24 13:28:59 -08002258 display->dirtyRegion.clear();
2259 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002260 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002261 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002262}
2263
David Sodmanfa9b2af2017-12-24 13:28:59 -08002264void SurfaceFlinger::postFrame()
2265{
2266 // |mStateLock| not needed as we are on the main thread
2267 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2268 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2269 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2270 logFrameStats();
2271 }
2272 }
2273}
2274
2275void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002276{
Mathias Agopian841cde52012-03-01 15:44:37 -08002277 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002278 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002279
David Sodmanfa9b2af2017-12-24 13:28:59 -08002280 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002281
David Sodmanfa9b2af2017-12-24 13:28:59 -08002282 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002283 const auto displayId = display->getId();
2284 if (displayId >= 0) {
2285 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002286 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002287 display->onSwapBuffersCompleted();
2288 display->makeCurrent();
David Sodman10a41ff2018-08-05 12:14:17 -07002289 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002290 sp<Fence> releaseFence = Fence::NO_FENCE;
Chia-I Wu7b549592017-11-15 09:14:57 -08002291 // The layer buffer from the previous frame (if any) is released
2292 // by HWC only when the release fence from this frame (if any) is
2293 // signaled. Always get the release fence from HWC first.
David Sodman10a41ff2018-08-05 12:14:17 -07002294 auto hwcLayer = compositionInfo.hwc.hwcLayer;
2295 if ((displayId >= 0) && hwcLayer) {
2296 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer.get());
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002297 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002298
2299 // If the layer was client composited in the previous frame, we
2300 // need to merge with the previous client target acquire fence.
2301 // Since we do not track that, always merge with the current
2302 // client target acquire fence when it is available, even though
2303 // this is suboptimal.
David Sodman10a41ff2018-08-05 12:14:17 -07002304 if (compositionInfo.compositionType == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002305 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002306 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002307 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002308
David Sodman10a41ff2018-08-05 12:14:17 -07002309 if (compositionInfo.layer) {
2310 compositionInfo.layer->onLayerDisplayed(releaseFence);
2311 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002312 }
Chia-I Wu83806892017-11-16 10:50:20 -08002313
2314 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002315 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002316 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002317 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002318 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002319 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002320 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002321 }
2322 }
2323
Dominik Laskowski7e045462018-05-30 13:02:02 -07002324 if (displayId >= 0) {
2325 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002326 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002327 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002328}
2329
Mathias Agopian87baae12012-07-31 12:38:26 -07002330void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002331{
Mathias Agopian841cde52012-03-01 15:44:37 -08002332 ATRACE_CALL();
2333
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002334 // here we keep a copy of the drawing state (that is the state that's
2335 // going to be overwritten by handleTransactionLocked()) outside of
2336 // mStateLock so that the side-effects of the State assignment
2337 // don't happen with mStateLock held (which can cause deadlocks).
2338 State drawingState(mDrawingState);
2339
Mathias Agopianca4d3602011-05-19 15:38:14 -07002340 Mutex::Autolock _l(mStateLock);
2341 const nsecs_t now = systemTime();
2342 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002343
Mathias Agopianca4d3602011-05-19 15:38:14 -07002344 // Here we're guaranteed that some transaction flags are set
2345 // so we can call handleTransactionLocked() unconditionally.
2346 // We call getTransactionFlags(), which will also clear the flags,
2347 // with mStateLock held to guarantee that mCurrentState won't change
2348 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002349
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002350 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002351 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002352 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002353
Mathias Agopianca4d3602011-05-19 15:38:14 -07002354 mLastTransactionTime = systemTime() - now;
2355 mDebugInTransaction = 0;
2356 invalidateHwcGeometry();
2357 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002358}
2359
Dominik Laskowski7e045462018-05-30 13:02:02 -07002360DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002361 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002362 // Figure out whether the event is for the primary display or an
2363 // external display by matching the Hwc display id against one for a
2364 // connected display. If we did not find a match, we then check what
2365 // displays are not already connected to determine the type. If we don't
2366 // have a connected primary display, we assume the new display is meant to
2367 // be the primary display, and then if we don't have an external display,
2368 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002369 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2370 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002371 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002372 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002373 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002374 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002375 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002376 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002377 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002378 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002379 return DisplayDevice::DISPLAY_EXTERNAL;
2380 }
2381
2382 return DisplayDevice::DISPLAY_ID_INVALID;
2383}
2384
Lloyd Piqueba04e622017-12-14 17:11:26 -08002385void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2386 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002387 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002388 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002389 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002390 continue;
2391 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002392
2393 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2394 ALOGE("External displays are not supported by the vr hardware composer.");
2395 continue;
2396 }
2397
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002398 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002399 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002400 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002401 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002402 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002403
2404 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002405 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002406 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002407 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002408 DisplayDeviceState info;
2409 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002410 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2411 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002412 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002413 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002414 mInterceptor->saveDisplayCreation(info);
2415 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002416 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002417 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002418
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002419 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002420 if (idx >= 0) {
2421 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002422 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002423 mCurrentState.displays.removeItemsAt(idx);
2424 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002425 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002426 }
2427
2428 processDisplayChangesLocked();
2429 }
2430
2431 mPendingHotplugEvents.clear();
2432}
2433
Lloyd Pique99d3da52018-01-22 17:48:03 -08002434sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002435 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002436 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002437 DisplayDeviceCreationArgs creationArgs(this, displayToken, state.type, displayId);
2438 creationArgs.isSecure = state.isSecure;
2439 creationArgs.displaySurface = dispSurface;
2440 creationArgs.hasWideColorGamut = false;
2441 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002442
Peiyong Lin13effd12018-07-24 17:01:47 -07002443 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002444 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002445 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002446 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002447 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002448 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002449
Dominik Laskowski7e045462018-05-30 13:02:02 -07002450 std::vector<RenderIntent> renderIntents =
2451 getHwComposer().getRenderIntents(displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002452 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002453 }
tangrobin6753a022018-08-10 10:58:54 +08002454 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002455
tangrobin6753a022018-08-10 10:58:54 +08002456 if (displayId >= 0) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002457 getHwComposer().getHdrCapabilities(displayId, &creationArgs.hdrCapabilities);
2458 creationArgs.supportedPerFrameMetadata =
2459 getHwComposer().getSupportedPerFrameMetadata(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002460 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002461
2462 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2463 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002464 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002465
2466 /*
2467 * Create our display's surface
2468 */
Peiyong Lin833074a2018-08-28 11:53:54 -07002469 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002470 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002471 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002472 renderSurface->setNativeWindow(nativeWindow.get());
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002473 creationArgs.displayWidth = renderSurface->getWidth();
2474 creationArgs.displayHeight = renderSurface->getHeight();
2475 creationArgs.renderSurface = std::move(renderSurface);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002476
2477 // Make sure that composition can never be stalled by a virtual display
2478 // consumer that isn't processing buffers fast enough. We have to do this
2479 // in two places:
2480 // * Here, in case the display is composed entirely by HWC.
2481 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2482 // window's swap interval in eglMakeCurrent, so they'll override the
2483 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002484 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002485 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2486 }
2487
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002488 creationArgs.displayInstallOrientation = state.type == DisplayDevice::DISPLAY_PRIMARY
2489 ? primaryDisplayOrientation
2490 : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002491
Lloyd Pique99d3da52018-01-22 17:48:03 -08002492 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002493 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002494
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002495 sp<DisplayDevice> display = new DisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002496
2497 if (maxFrameBufferAcquiredBuffers >= 3) {
2498 nativeWindowSurface->preallocateBuffers();
2499 }
2500
2501 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002502 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002503 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002504 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002505 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002506 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002507 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002508 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002509 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002510 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002511 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002512 display->setLayerStack(state.layerStack);
2513 display->setProjection(state.orientation, state.viewport, state.frame);
2514 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002515
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002516 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002517}
2518
Lloyd Pique347200f2017-12-14 17:00:15 -08002519void SurfaceFlinger::processDisplayChangesLocked() {
2520 // here we take advantage of Vector's copy-on-write semantics to
2521 // improve performance by skipping the transaction entirely when
2522 // know that the lists are identical
2523 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2524 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2525 if (!curr.isIdenticalTo(draw)) {
2526 mVisibleRegionsDirty = true;
2527 const size_t cc = curr.size();
2528 size_t dc = draw.size();
2529
2530 // find the displays that were removed
2531 // (ie: in drawing state but not in current state)
2532 // also handle displays that changed
2533 // (ie: displays that are in both lists)
2534 for (size_t i = 0; i < dc;) {
2535 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2536 if (j < 0) {
2537 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002538 // Call makeCurrent() on the primary display so we can
2539 // be sure that nothing associated with this display
2540 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002541 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2542 defaultDisplay->makeCurrent();
2543 }
2544 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2545 display->disconnect(getHwComposer());
2546 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002547 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002548 if (mUseScheduler) {
2549 mScheduler->hotplugReceived(mAppConnectionHandle,
2550 EventThread::DisplayType::Primary, false);
2551 } else {
2552 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2553 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002554 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002555 if (mUseScheduler) {
2556 mScheduler->hotplugReceived(mAppConnectionHandle,
2557 EventThread::DisplayType::External, false);
2558 } else {
2559 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2560 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002561 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002562 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002563 } else {
2564 // this display is in both lists. see if something changed.
2565 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002566 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002567 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2568 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2569 if (state_binder != draw_binder) {
2570 // changing the surface is like destroying and
2571 // recreating the DisplayDevice, so we just remove it
2572 // from the drawing state, so that it get re-added
2573 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002574 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2575 display->disconnect(getHwComposer());
2576 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002577 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002578 mDrawingState.displays.removeItemsAt(i);
2579 dc--;
2580 // at this point we must loop to the next item
2581 continue;
2582 }
2583
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002584 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002585 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002586 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002587 }
2588 if ((state.orientation != draw[i].orientation) ||
2589 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002590 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002591 }
2592 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002593 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002594 }
2595 }
2596 }
2597 ++i;
2598 }
2599
2600 // find displays that were added
2601 // (ie: in current state but not in drawing state)
2602 for (size_t i = 0; i < cc; i++) {
2603 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2604 const DisplayDeviceState& state(curr[i]);
2605
2606 sp<DisplaySurface> dispSurface;
2607 sp<IGraphicBufferProducer> producer;
2608 sp<IGraphicBufferProducer> bqProducer;
2609 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002610 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002611
Dominik Laskowski7e045462018-05-30 13:02:02 -07002612 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002613 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002614 // Virtual displays without a surface are dormant:
2615 // they have external state (layer stack, projection,
2616 // etc.) but no internal state (i.e. a DisplayDevice).
2617 if (state.surface != nullptr) {
2618 // Allow VR composer to use virtual displays.
2619 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2620 int width = 0;
2621 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2622 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2623 int height = 0;
2624 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2625 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2626 int intFormat = 0;
2627 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2628 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002629 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002630
Dominik Laskowski7e045462018-05-30 13:02:02 -07002631 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2632 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002633 }
2634
2635 // TODO: Plumb requested format back up to consumer
2636
2637 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002638 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002639 bqProducer, bqConsumer,
2640 state.displayName);
2641
2642 dispSurface = vds;
2643 producer = vds;
2644 }
2645 } else {
2646 ALOGE_IF(state.surface != nullptr,
2647 "adding a supported display, but rendering "
2648 "surface is provided (%p), ignoring it",
2649 state.surface.get());
2650
Dominik Laskowski7e045462018-05-30 13:02:02 -07002651 displayId = state.type;
2652 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002653 producer = bqProducer;
2654 }
2655
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002656 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002657 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002658 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002659 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002660 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002661 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002662 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002663 if (mUseScheduler) {
2664 mScheduler->hotplugReceived(mAppConnectionHandle,
2665 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002666 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002667 } else {
2668 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2669 true);
2670 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002671 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002672 if (mUseScheduler) {
2673 mScheduler->hotplugReceived(mAppConnectionHandle,
2674 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002675 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002676 } else {
2677 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2678 true);
2679 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002680 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002681 }
2682 }
2683 }
2684 }
2685 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002686
2687 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002688}
2689
Mathias Agopian87baae12012-07-31 12:38:26 -07002690void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002691{
Dan Stoza7dde5992015-05-22 09:51:44 -07002692 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002693 mCurrentState.traverseInZOrder([](Layer* layer) {
2694 layer->notifyAvailableFrames();
2695 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002696
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002697 /*
2698 * Traversal of the children
2699 * (perform the transaction for each of them if needed)
2700 */
2701
Mathias Agopian3559b072012-08-15 13:46:03 -07002702 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002703 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002704 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002705 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002706
2707 const uint32_t flags = layer->doTransaction(0);
2708 if (flags & Layer::eVisibleRegion)
2709 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002710 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002711 }
2712
2713 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002714 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002715 */
2716
Mathias Agopiane57f2922012-08-09 16:29:12 -07002717 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002718 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002719 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002720 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002721
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002722 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002723 // The transform hint might have changed for some layers
2724 // (either because a display has changed, or because a layer
2725 // as changed).
2726 //
2727 // Walk through all the layers in currentLayers,
2728 // and update their transform hint.
2729 //
2730 // If a layer is visible only on a single display, then that
2731 // display is used to calculate the hint, otherwise we use the
2732 // default display.
2733 //
2734 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2735 // the hint is set before we acquire a buffer from the surface texture.
2736 //
2737 // NOTE: layer transactions have taken place already, so we use their
2738 // drawing state. However, SurfaceFlinger's own transaction has not
2739 // happened yet, so we must use the current state layer list
2740 // (soon to become the drawing state list).
2741 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002742 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002743 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002744 bool first = true;
2745 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002746 // NOTE: we rely on the fact that layers are sorted by
2747 // layerStack first (so we don't have to traverse the list
2748 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002749 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002750 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002751 currentlayerStack = layerStack;
2752 // figure out if this layerstack is mirrored
2753 // (more than one display) if so, pick the default display,
2754 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002755 hintDisplay = nullptr;
2756 for (const auto& [token, display] : mDisplays) {
2757 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2758 if (hintDisplay) {
2759 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002760 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002761 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002762 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002763 }
2764 }
2765 }
2766 }
Chet Haase91d25932013-04-11 15:24:55 -07002767
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002768 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002769 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2770 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002771
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002772 // could be null when this layer is using a layerStack
2773 // that is not visible on any display. Also can occur at
2774 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002775 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002776 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002777
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002778 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002779 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002780 if (hintDisplay) {
2781 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002782 }
Robert Carr2047fae2016-11-28 14:09:09 -08002783
2784 first = false;
2785 });
Mathias Agopian84300952012-11-21 16:02:13 -08002786 }
2787
2788
Mathias Agopian3559b072012-08-15 13:46:03 -07002789 /*
2790 * Perform our own transaction if needed
2791 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002792
2793 if (mLayersAdded) {
2794 mLayersAdded = false;
2795 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002796 mVisibleRegionsDirty = true;
2797 }
2798
2799 // some layers might have been removed, so
2800 // we need to update the regions they're exposing.
2801 if (mLayersRemoved) {
2802 mLayersRemoved = false;
2803 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002804 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002805 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002806 // this layer is not visible anymore
2807 // TODO: we could traverse the tree from front to back and
2808 // compute the actual visible region
2809 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002810 Region visibleReg;
2811 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002812 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002813 }
Robert Carr2047fae2016-11-28 14:09:09 -08002814 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002815 }
2816
2817 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002818
2819 updateCursorAsync();
2820}
2821
2822void SurfaceFlinger::updateCursorAsync()
2823{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002824 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002825 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002826 continue;
2827 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002828
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002829 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2830 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002831 }
2832 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002833}
2834
2835void SurfaceFlinger::commitTransaction()
2836{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002837 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002838 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002839 for (const auto& l : mLayersPendingRemoval) {
2840 recordBufferingStats(l->getName().string(),
2841 l->getOccupancyHistory(true));
2842 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002843 }
2844 mLayersPendingRemoval.clear();
2845 }
2846
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002847 // If this transaction is part of a window animation then the next frame
2848 // we composite should be considered an animation as well.
2849 mAnimCompositionPending = mAnimTransactionPending;
2850
Mathias Agopian4fec8732012-06-29 14:12:52 -07002851 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002852 // clear the "changed" flags in current state
2853 mCurrentState.colorMatrixChanged = false;
2854
Robert Carr1f0a16a2016-10-24 16:27:39 -07002855 mDrawingState.traverseInZOrder([](Layer* layer) {
2856 layer->commitChildList();
2857 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002858 mTransactionPending = false;
2859 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002860 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002861}
2862
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002863void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2864 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002865 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002866 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002867
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002868 Region aboveOpaqueLayers;
2869 Region aboveCoveredLayers;
2870 Region dirty;
2871
Mathias Agopian87baae12012-07-31 12:38:26 -07002872 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002873
Robert Carr2047fae2016-11-28 14:09:09 -08002874 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002875 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002876 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002877
Jesse Hall01e29052013-02-19 16:13:35 -08002878 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002879 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002880 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002881 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002882
Mathias Agopianab028732010-03-16 16:41:46 -07002883 /*
2884 * opaqueRegion: area of a surface that is fully opaque.
2885 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002886 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002887
2888 /*
2889 * visibleRegion: area of a surface that is visible on screen
2890 * and not fully transparent. This is essentially the layer's
2891 * footprint minus the opaque regions above it.
2892 * Areas covered by a translucent surface are considered visible.
2893 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002894 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002895
2896 /*
2897 * coveredRegion: area of a surface that is covered by all
2898 * visible regions above it (which includes the translucent areas).
2899 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002900 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002901
Jesse Halla8026d22012-09-25 13:25:04 -07002902 /*
2903 * transparentRegion: area of a surface that is hinted to be completely
2904 * transparent. This is only used to tell when the layer has no visible
2905 * non-transparent regions and can be removed from the layer list. It
2906 * does not affect the visibleRegion of this layer or any layers
2907 * beneath it. The hint may not be correct if apps don't respect the
2908 * SurfaceView restrictions (which, sadly, some don't).
2909 */
2910 Region transparentRegion;
2911
Mathias Agopianab028732010-03-16 16:41:46 -07002912
2913 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002914 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002915 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002916 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002917 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002918 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002919 if (!visibleRegion.isEmpty()) {
2920 // Remove the transparent area from the visible region
2921 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002922 if (tr.preserveRects()) {
2923 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002924 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002925 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002926 // transformation too complex, can't do the
2927 // transparent region optimization.
2928 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002929 }
Mathias Agopianab028732010-03-16 16:41:46 -07002930 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002931
Mathias Agopianab028732010-03-16 16:41:46 -07002932 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002933 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002934 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002935 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002936 // the opaque region is the layer's footprint
2937 opaqueRegion = visibleRegion;
2938 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002939 }
2940 }
2941
Robert Carre5f4f692018-01-12 13:12:28 -08002942 if (visibleRegion.isEmpty()) {
2943 layer->clearVisibilityRegions();
2944 return;
2945 }
2946
Mathias Agopianab028732010-03-16 16:41:46 -07002947 // Clip the covered region to the visible region
2948 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2949
2950 // Update aboveCoveredLayers for next (lower) layer
2951 aboveCoveredLayers.orSelf(visibleRegion);
2952
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002953 // subtract the opaque region covered by the layers above us
2954 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002955
2956 // compute this layer's dirty region
2957 if (layer->contentDirty) {
2958 // we need to invalidate the whole region
2959 dirty = visibleRegion;
2960 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002961 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002962 layer->contentDirty = false;
2963 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002964 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002965 * the exposed region consists of two components:
2966 * 1) what's VISIBLE now and was COVERED before
2967 * 2) what's EXPOSED now less what was EXPOSED before
2968 *
2969 * note that (1) is conservative, we start with the whole
2970 * visible region but only keep what used to be covered by
2971 * something -- which mean it may have been exposed.
2972 *
2973 * (2) handles areas that were not covered by anything but got
2974 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002975 */
Mathias Agopianab028732010-03-16 16:41:46 -07002976 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002977 const Region oldVisibleRegion = layer->visibleRegion;
2978 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002979 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2980 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002981 }
2982 dirty.subtractSelf(aboveOpaqueLayers);
2983
2984 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002985 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002986
Mathias Agopianab028732010-03-16 16:41:46 -07002987 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002988 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002989
Jesse Halla8026d22012-09-25 13:25:04 -07002990 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002991 layer->setVisibleRegion(visibleRegion);
2992 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002993 layer->setVisibleNonTransparentRegion(
2994 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002995 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002996
Mathias Agopian87baae12012-07-31 12:38:26 -07002997 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002998}
2999
Chia-I Wuab0c3192017-08-01 11:29:00 -07003000void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003001 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003002 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
3003 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003004 }
3005 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003006}
3007
Dan Stoza6b9454d2014-11-07 16:00:59 -08003008bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003009{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003010 ALOGV("handlePageFlip");
3011
Brian Andersond6927fb2016-07-23 23:37:30 -07003012 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003013
Mathias Agopian4fec8732012-06-29 14:12:52 -07003014 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003015 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003016 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003017
3018 // Store the set of layers that need updates. This set must not change as
3019 // buffers are being latched, as this could result in a deadlock.
3020 // Example: Two producers share the same command stream and:
3021 // 1.) Layer 0 is latched
3022 // 2.) Layer 0 gets a new frame
3023 // 2.) Layer 1 gets a new frame
3024 // 3.) Layer 1 is latched.
3025 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3026 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003027 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003028 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003029 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07003030 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003031 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003032 } else {
3033 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003034 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003035 } else {
3036 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003037 }
Robert Carr2047fae2016-11-28 14:09:09 -08003038 });
3039
Dan Stoza9e56aa02015-11-02 13:00:03 -08003040 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07003041 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07003042 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003043 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07003044 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06003045 newDataLatched = true;
3046 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003047 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003048
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003049 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003050
3051 // If we will need to wake up at some time in the future to deal with a
3052 // queued frame that shouldn't be displayed during this vsync period, wake
3053 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003054 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003055 signalLayerUpdate();
3056 }
3057
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003058 // enter boot animation on first buffer latch
3059 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3060 ALOGI("Enter boot animation");
3061 mBootStage = BootStage::BOOTANIMATION;
3062 }
3063
Dan Stoza6b9454d2014-11-07 16:00:59 -08003064 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003065 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003066}
3067
Mathias Agopianad456f92011-01-13 17:53:01 -08003068void SurfaceFlinger::invalidateHwcGeometry()
3069{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003070 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003071}
3072
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003073void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
3074 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003075 // We only need to actually compose the display if:
3076 // 1) It is being handled by hardware composer, which may need this to
3077 // keep its virtual display state machine in sync, or
3078 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07003079 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08003080 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003081 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003082 return;
3083 }
3084
Dan Stoza9e56aa02015-11-02 13:00:03 -08003085 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003086 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003087
3088 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003089 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003090}
3091
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003092bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003093 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003094
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003095 const Region bounds(display->bounds());
3096 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003097 const auto displayId = display->getId();
3098 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003099 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003100
Peiyong Lind3788632018-09-18 16:01:31 -07003101 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003102 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003103 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003104
Dan Stoza9e56aa02015-11-02 13:00:03 -08003105 if (hasClientComposition) {
3106 ALOGV("hasClientComposition");
3107
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003108 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003109 if (display->hasWideColorGamut()) {
3110 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003111 }
3112 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003113 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003114 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003115
Dominik Laskowski7e045462018-05-30 13:02:02 -07003116 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003117 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3118 HWC2::Capability::SkipClientColorTransform);
3119
Peiyong Lind3788632018-09-18 16:01:31 -07003120 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003121 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3122 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003123 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003124 }
3125
Chia-I Wud49d6692018-06-27 07:17:41 +08003126 // The current enhanced saturation matrix is designed to enhance Display P3,
3127 // thus we only apply this matrix when the render intent is not colorimetric
3128 // and the output color space is Display P3.
3129 needsEnhancedColorMatrix =
3130 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3131 outputDataspace == Dataspace::DISPLAY_P3);
3132 if (needsEnhancedColorMatrix) {
3133 colorMatrix *= mEnhancedSaturationMatrix;
3134 }
3135
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003136 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003137 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003138 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003139 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003140
3141 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003142 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3143 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3144 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003145 }
3146 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003147 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003148
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003149 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003150 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003151 // when using overlays, we assume a fully transparent framebuffer
3152 // NOTE: we could reduce how much we need to clear, for instance
3153 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003154 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003155 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003156 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003157 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003158 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003159 // we're left with the letterbox region
3160 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003161 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003162
3163 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003164 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003165
Mathias Agopianb9494d52012-04-18 02:28:45 -07003166 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003167 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003168 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003169 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003170 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003171 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003172
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003173 const Rect& bounds = display->getBounds();
3174 const Rect& scissor = display->getScissor();
3175 if (scissor != bounds) {
3176 // scissor doesn't match the screen's dimensions, so we
3177 // need to clear everything outside of it and enable
3178 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003179
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003180 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003181 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003182 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003183 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003184
Mathias Agopian85d751c2012-08-29 16:59:24 -07003185 /*
3186 * and then, render the layers targeted at the framebuffer
3187 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003188
Dan Stoza9e56aa02015-11-02 13:00:03 -08003189 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003190 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003191 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003192 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003193 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003194 displayTransform.transform(layer->visibleRegion)));
3195 ALOGV("Layer: %s", layer->getName().string());
3196 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003197 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003198 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003199 case HWC2::Composition::Cursor:
3200 case HWC2::Composition::Device:
3201 case HWC2::Composition::Sideband:
3202 case HWC2::Composition::SolidColor: {
David Sodmanc1498e62018-09-12 14:36:26 -07003203 const Layer::State& state(layer->getDrawingState());
3204 if (layer->getClearClientTarget(displayId) && !firstLayer &&
3205 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3206 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003207 // never clear the very first layer since we're
3208 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003209 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003210 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003211 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003212 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003213 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003214 if (layer->hasColorTransform()) {
3215 mat4 tmpMatrix;
3216 if (applyColorMatrix) {
3217 tmpMatrix = mDrawingState.colorMatrix;
3218 }
3219 tmpMatrix *= layer->getColorTransform();
3220 if (needsEnhancedColorMatrix) {
3221 tmpMatrix *= mEnhancedSaturationMatrix;
3222 }
3223 getRenderEngine().setColorTransform(tmpMatrix);
3224 } else {
3225 getRenderEngine().setColorTransform(colorMatrix);
3226 }
David Sodmanc1498e62018-09-12 14:36:26 -07003227 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003228 break;
3229 }
3230 default:
3231 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003232 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003233 } else {
3234 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003235 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003236 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003237 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003238
Peiyong Lind3788632018-09-18 16:01:31 -07003239 // Clear color transform matrix at the end of the frame.
3240 getRenderEngine().setColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003241
Mathias Agopianf45c5102012-10-24 16:29:17 -07003242 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003243 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003244 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003245}
3246
Chia-I Wu28e3a252018-09-07 12:05:02 -07003247void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003248 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003249 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003250}
3251
Dan Stoza7d89d062015-04-30 13:29:25 -07003252status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003253 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003254 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003255 const sp<Layer>& lbc,
3256 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003257{
Dan Stoza7d89d062015-04-30 13:29:25 -07003258 // add this layer to the current state list
3259 {
3260 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003261 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003262 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3263 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003264 return NO_MEMORY;
3265 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003266 if (parent == nullptr) {
3267 mCurrentState.layersSortedByZ.add(lbc);
3268 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003269 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003270 ALOGE("addClientLayer called with a removed parent");
3271 return NAME_NOT_FOUND;
3272 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003273 parent->addChild(lbc);
3274 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003275
Yiwei Zhang243b3782018-05-15 17:40:04 -07003276 if (gbc != nullptr) {
3277 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3278 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3279 mMaxGraphicBufferProducerListSize,
3280 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3281 mGraphicBufferProducerList.size(),
3282 mMaxGraphicBufferProducerListSize, mNumLayers);
3283 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003284 mLayersAdded = true;
3285 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003286 }
3287
Mathias Agopian96f08192010-06-02 23:28:45 -07003288 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003289 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003290
Dan Stoza7d89d062015-04-30 13:29:25 -07003291 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003292}
3293
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003294status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003295 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003296 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3297}
Robert Carr7f9b8992017-03-10 11:08:39 -08003298
chaviwca27f252018-02-06 16:46:39 -08003299status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3300 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003301 if (layer->isPendingRemoval()) {
3302 return NO_ERROR;
3303 }
3304
Robert Carr1f0a16a2016-10-24 16:27:39 -07003305 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003306 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003307 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003308 if (topLevelOnly) {
3309 return NO_ERROR;
3310 }
3311
Chia-I Wu98f1c102017-05-30 14:54:08 -07003312 sp<Layer> ancestor = p;
3313 while (ancestor->getParent() != nullptr) {
3314 ancestor = ancestor->getParent();
3315 }
3316 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3317 ALOGE("removeLayer called with a layer whose parent has been removed");
3318 return NAME_NOT_FOUND;
3319 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003320
3321 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003322 } else {
3323 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003324 }
3325
Robert Carr136e2f62017-02-08 17:54:29 -08003326 // As a matter of normal operation, the LayerCleaner will produce a second
3327 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3328 // so we will succeed in promoting it, but it's already been removed
3329 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3330 // otherwise something has gone wrong and we are leaking the layer.
3331 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003332 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3333 layer->getName().string(),
3334 (p != nullptr) ? p->getName().string() : "no-parent");
3335 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003336 } else if (index < 0) {
3337 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003338 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003339
Chia-I Wuc6657022017-08-15 11:18:17 -07003340 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003341 mLayersPendingRemoval.add(layer);
3342 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003343 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003344 setTransactionFlags(eTransactionNeeded);
3345 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003346}
3347
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003348uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003349 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003350}
3351
Mathias Agopian3f844832013-08-07 21:24:32 -07003352uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003353 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003354}
3355
Mathias Agopian3f844832013-08-07 21:24:32 -07003356uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003357 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3358}
3359
3360uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3361 VSyncModulator::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003362 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003363 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003364 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003365 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003366 }
3367 return old;
3368}
3369
chaviwca27f252018-02-06 16:46:39 -08003370bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3371 for (const ComposerState& state : states) {
3372 // Here we need to check that the interface we're given is indeed
3373 // one of our own. A malicious client could give us a nullptr
3374 // IInterface, or one of its own or even one of our own but a
3375 // different type. All these situations would cause us to crash.
3376 if (state.client == nullptr) {
3377 return true;
3378 }
3379
3380 sp<IBinder> binder = IInterface::asBinder(state.client);
3381 if (binder == nullptr) {
3382 return true;
3383 }
3384
3385 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3386 return true;
3387 }
3388 }
3389 return false;
3390}
3391
Mathias Agopian8b33f032012-07-24 20:43:54 -07003392void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003393 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003394 const Vector<DisplayState>& displays,
3395 uint32_t flags)
3396{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003397 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003398 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003399 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003400
chaviwca27f252018-02-06 16:46:39 -08003401 if (containsAnyInvalidClientState(states)) {
3402 return;
3403 }
3404
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003405 if (flags & eAnimation) {
3406 // For window updates that are part of an animation we must wait for
3407 // previous animation "frames" to be handled.
3408 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003409 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003410 if (CC_UNLIKELY(err != NO_ERROR)) {
3411 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003412 // caller after a few seconds.
3413 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3414 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003415 mAnimTransactionPending = false;
3416 break;
3417 }
3418 }
3419 }
3420
chaviwca27f252018-02-06 16:46:39 -08003421 for (const DisplayState& display : displays) {
3422 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003423 }
3424
chaviwca27f252018-02-06 16:46:39 -08003425 for (const ComposerState& state : states) {
3426 transactionFlags |= setClientStateLocked(state);
3427 }
3428
3429 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3430 // as destroyed should only occur after setting all other states. This is to allow for a
3431 // child re-parent to happen before marking its original parent as destroyed (which would
3432 // then mark the child as destroyed).
3433 for (const ComposerState& state : states) {
3434 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003435 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003436
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003437 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3438 // anyway. This can be used as a flush mechanism for previous async transactions.
3439 // Empty animation transaction can be used to simulate back-pressure, so also force a
3440 // transaction for empty animation transactions.
3441 if (transactionFlags == 0 &&
3442 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003443 transactionFlags = eTransactionNeeded;
3444 }
3445
Mathias Agopian386aa982011-11-07 21:58:03 -08003446 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003447 if (mInterceptor->isEnabled()) {
3448 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003449 }
Irvel468051e2016-06-13 16:44:44 -07003450
Mathias Agopian386aa982011-11-07 21:58:03 -08003451 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003452 const auto start = (flags & eEarlyWakeup)
3453 ? VSyncModulator::TransactionStart::EARLY
3454 : VSyncModulator::TransactionStart::NORMAL;
3455 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003456
3457 // if this is a synchronous transaction, wait for it to take effect
3458 // before returning.
3459 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003460 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003461 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003462 if (flags & eAnimation) {
3463 mAnimTransactionPending = true;
3464 }
3465 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003466 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3467 if (CC_UNLIKELY(err != NO_ERROR)) {
3468 // just in case something goes wrong in SF, return to the
3469 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003470 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3471 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003472 break;
3473 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003474 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003475 }
3476}
3477
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003478uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3479 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3480 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003481
Mathias Agopiane57f2922012-08-09 16:29:12 -07003482 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003483 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3484
3485 const uint32_t what = s.what;
3486 if (what & DisplayState::eSurfaceChanged) {
3487 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3488 state.surface = s.surface;
3489 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003490 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003491 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003492 if (what & DisplayState::eLayerStackChanged) {
3493 if (state.layerStack != s.layerStack) {
3494 state.layerStack = s.layerStack;
3495 flags |= eDisplayTransactionNeeded;
3496 }
3497 }
3498 if (what & DisplayState::eDisplayProjectionChanged) {
3499 if (state.orientation != s.orientation) {
3500 state.orientation = s.orientation;
3501 flags |= eDisplayTransactionNeeded;
3502 }
3503 if (state.frame != s.frame) {
3504 state.frame = s.frame;
3505 flags |= eDisplayTransactionNeeded;
3506 }
3507 if (state.viewport != s.viewport) {
3508 state.viewport = s.viewport;
3509 flags |= eDisplayTransactionNeeded;
3510 }
3511 }
3512 if (what & DisplayState::eDisplaySizeChanged) {
3513 if (state.width != s.width) {
3514 state.width = s.width;
3515 flags |= eDisplayTransactionNeeded;
3516 }
3517 if (state.height != s.height) {
3518 state.height = s.height;
3519 flags |= eDisplayTransactionNeeded;
3520 }
3521 }
3522
Mathias Agopiane57f2922012-08-09 16:29:12 -07003523 return flags;
3524}
3525
Robert Carrd4ae7f32018-06-07 16:10:57 -07003526bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3527 IPCThreadState* ipc = IPCThreadState::self();
3528 const int pid = ipc->getCallingPid();
3529 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003530 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003531 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003532 return false;
3533 }
3534 return true;
3535}
3536
chaviwca27f252018-02-06 16:46:39 -08003537uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3538 const layer_state_t& s = composerState.state;
3539 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3540
Mathias Agopian13127d82013-03-05 17:47:11 -08003541 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003542 if (layer == nullptr) {
3543 return 0;
3544 }
3545
3546 if (layer->isPendingRemoval()) {
3547 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3548 return 0;
3549 }
3550
3551 uint32_t flags = 0;
3552
3553 const uint32_t what = s.what;
3554 bool geometryAppliesWithResize =
3555 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003556
3557 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3558 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003559 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003560 layer->pushPendingState();
3561 }
3562
chaviw8b3871a2017-11-01 17:41:01 -07003563 if (what & layer_state_t::ePositionChanged) {
3564 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3565 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003566 }
chaviw8b3871a2017-11-01 17:41:01 -07003567 }
3568 if (what & layer_state_t::eLayerChanged) {
3569 // NOTE: index needs to be calculated before we update the state
3570 const auto& p = layer->getParent();
3571 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003572 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003573 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003574 mCurrentState.layersSortedByZ.removeAt(idx);
3575 mCurrentState.layersSortedByZ.add(layer);
3576 // we need traversal (state changed)
3577 // AND transaction (list changed)
3578 flags |= eTransactionNeeded|eTraversalNeeded;
3579 }
chaviw8b3871a2017-11-01 17:41:01 -07003580 } else {
3581 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003582 flags |= eTransactionNeeded|eTraversalNeeded;
3583 }
3584 }
chaviw8b3871a2017-11-01 17:41:01 -07003585 }
3586 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003587 // NOTE: index needs to be calculated before we update the state
3588 const auto& p = layer->getParent();
3589 if (p == nullptr) {
3590 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3591 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3592 mCurrentState.layersSortedByZ.removeAt(idx);
3593 mCurrentState.layersSortedByZ.add(layer);
3594 // we need traversal (state changed)
3595 // AND transaction (list changed)
3596 flags |= eTransactionNeeded|eTraversalNeeded;
3597 }
3598 } else {
3599 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3600 flags |= eTransactionNeeded|eTraversalNeeded;
3601 }
chaviw8b3871a2017-11-01 17:41:01 -07003602 }
3603 }
3604 if (what & layer_state_t::eSizeChanged) {
3605 if (layer->setSize(s.w, s.h)) {
3606 flags |= eTraversalNeeded;
3607 }
3608 }
3609 if (what & layer_state_t::eAlphaChanged) {
3610 if (layer->setAlpha(s.alpha))
3611 flags |= eTraversalNeeded;
3612 }
3613 if (what & layer_state_t::eColorChanged) {
3614 if (layer->setColor(s.color))
3615 flags |= eTraversalNeeded;
3616 }
Peiyong Lind3788632018-09-18 16:01:31 -07003617 if (what & layer_state_t::eColorTransformChanged) {
3618 if (layer->setColorTransform(s.colorTransform)) {
3619 flags |= eTraversalNeeded;
3620 }
3621 }
chaviw8b3871a2017-11-01 17:41:01 -07003622 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003623 // TODO: b/109894387
3624 //
3625 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3626 // rotation. To see the problem observe that if we have a square parent, and a child
3627 // of the same size, then we rotate the child 45 degrees around it's center, the child
3628 // must now be cropped to a non rectangular 8 sided region.
3629 //
3630 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3631 // private API, and the WindowManager only uses rotation in one case, which is on a top
3632 // level layer in which cropping is not an issue.
3633 //
3634 // However given that abuse of rotation matrices could lead to surfaces extending outside
3635 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3636 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3637 // transformations.
3638 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003639 flags |= eTraversalNeeded;
3640 }
3641 if (what & layer_state_t::eTransparentRegionChanged) {
3642 if (layer->setTransparentRegionHint(s.transparentRegion))
3643 flags |= eTraversalNeeded;
3644 }
3645 if (what & layer_state_t::eFlagsChanged) {
3646 if (layer->setFlags(s.flags, s.mask))
3647 flags |= eTraversalNeeded;
3648 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003649 if (what & layer_state_t::eCropChanged_legacy) {
3650 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003651 flags |= eTraversalNeeded;
3652 }
chaviw8b3871a2017-11-01 17:41:01 -07003653 if (what & layer_state_t::eLayerStackChanged) {
3654 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3655 // We only allow setting layer stacks for top level layers,
3656 // everything else inherits layer stack from its parent.
3657 if (layer->hasParent()) {
3658 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3659 layer->getName().string());
3660 } else if (idx < 0) {
3661 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3662 "that also does not appear in the top level layer list. Something"
3663 " has gone wrong.", layer->getName().string());
3664 } else if (layer->setLayerStack(s.layerStack)) {
3665 mCurrentState.layersSortedByZ.removeAt(idx);
3666 mCurrentState.layersSortedByZ.add(layer);
3667 // we need traversal (state changed)
3668 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003669 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003670 }
3671 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003672 if (what & layer_state_t::eDeferTransaction_legacy) {
3673 if (s.barrierHandle_legacy != nullptr) {
3674 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3675 } else if (s.barrierGbp_legacy != nullptr) {
3676 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003677 if (authenticateSurfaceTextureLocked(gbp)) {
3678 const auto& otherLayer =
3679 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003680 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003681 } else {
3682 ALOGE("Attempt to defer transaction to to an"
3683 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003684 }
3685 }
chaviw8b3871a2017-11-01 17:41:01 -07003686 // We don't trigger a traversal here because if no other state is
3687 // changed, we don't want this to cause any more work
3688 }
3689 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003690 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003691 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003692 if (!hadParent) {
3693 mCurrentState.layersSortedByZ.remove(layer);
3694 }
chaviw8b3871a2017-11-01 17:41:01 -07003695 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003696 }
chaviw8b3871a2017-11-01 17:41:01 -07003697 }
3698 if (what & layer_state_t::eReparentChildren) {
3699 if (layer->reparentChildren(s.reparentHandle)) {
3700 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003701 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003702 }
chaviw8b3871a2017-11-01 17:41:01 -07003703 if (what & layer_state_t::eDetachChildren) {
3704 layer->detachChildren();
3705 }
3706 if (what & layer_state_t::eOverrideScalingModeChanged) {
3707 layer->setOverrideScalingMode(s.overrideScalingMode);
3708 // We don't trigger a traversal here because if no other state is
3709 // changed, we don't want this to cause any more work
3710 }
Marissa Wall61c58622018-07-18 10:12:20 -07003711 if (what & layer_state_t::eTransformChanged) {
3712 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3713 }
3714 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3715 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3716 flags |= eTraversalNeeded;
3717 }
3718 if (what & layer_state_t::eCropChanged) {
3719 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3720 }
3721 if (what & layer_state_t::eBufferChanged) {
3722 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3723 }
3724 if (what & layer_state_t::eAcquireFenceChanged) {
3725 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3726 }
3727 if (what & layer_state_t::eDataspaceChanged) {
3728 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3729 }
3730 if (what & layer_state_t::eHdrMetadataChanged) {
3731 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3732 }
3733 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3734 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3735 }
3736 if (what & layer_state_t::eApiChanged) {
3737 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3738 }
3739 if (what & layer_state_t::eSidebandStreamChanged) {
3740 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3741 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003742 return flags;
3743}
3744
chaviwca27f252018-02-06 16:46:39 -08003745void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3746 const layer_state_t& state = composerState.state;
3747 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3748
3749 sp<Layer> layer(client->getLayerUser(state.surface));
3750 if (layer == nullptr) {
3751 return;
3752 }
3753
3754 if (layer->isPendingRemoval()) {
3755 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3756 return;
3757 }
3758
3759 if (state.what & layer_state_t::eDestroySurface) {
3760 removeLayerLocked(mStateLock, layer);
3761 }
3762}
3763
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003764status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003765 const String8& name,
3766 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003767 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003768 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003769 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003770{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003771 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003772 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003773 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003774 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003775 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003776
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003777 status_t result = NO_ERROR;
3778
3779 sp<Layer> layer;
3780
Cody Northropbc755282017-03-31 12:00:08 -06003781 String8 uniqueName = getUniqueLayerName(name);
3782
Mathias Agopian3165cc22012-08-08 19:42:09 -07003783 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003784 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003785 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3786 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003787
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003788 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003789 case ISurfaceComposerClient::eFXSurfaceBufferState:
3790 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3791 break;
chaviw13fdc492017-06-27 12:40:18 -07003792 case ISurfaceComposerClient::eFXSurfaceColor:
3793 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003794 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003795 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003796 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003797 case ISurfaceComposerClient::eFXSurfaceContainer:
3798 result = createContainerLayer(client,
3799 uniqueName, w, h, flags,
3800 handle, &layer);
3801 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003802 default:
3803 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003804 break;
3805 }
3806
Dan Stoza7d89d062015-04-30 13:29:25 -07003807 if (result != NO_ERROR) {
3808 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003809 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003810
Chia-I Wuab0c3192017-08-01 11:29:00 -07003811 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3812 // TODO b/64227542
3813 if (windowType == 441731) {
3814 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3815 layer->setPrimaryDisplayOnly();
3816 }
3817
Albert Chaulk479c60c2017-01-27 14:21:34 -05003818 layer->setInfo(windowType, ownerUid);
3819
Robert Carr1f0a16a2016-10-24 16:27:39 -07003820 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003821 if (result != NO_ERROR) {
3822 return result;
3823 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003824 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003825
3826 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003827 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003828}
3829
Cody Northropbc755282017-03-31 12:00:08 -06003830String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3831{
3832 bool matchFound = true;
3833 uint32_t dupeCounter = 0;
3834
3835 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3836 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3837
Dan Stoza436ccf32018-06-21 12:10:12 -07003838 // Grab the state lock since we're accessing mCurrentState
3839 Mutex::Autolock lock(mStateLock);
3840
Cody Northropbc755282017-03-31 12:00:08 -06003841 // Loop over layers until we're sure there is no matching name
3842 while (matchFound) {
3843 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003844 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003845 if (layer->getName() == uniqueName) {
3846 matchFound = true;
3847 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3848 }
3849 });
3850 }
3851
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003852 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3853 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003854
3855 return uniqueName;
3856}
3857
Marissa Wallfd668622018-05-10 10:21:13 -07003858status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3859 uint32_t w, uint32_t h, uint32_t flags,
3860 PixelFormat& format, sp<IBinder>* handle,
3861 sp<IGraphicBufferProducer>* gbp,
3862 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003863 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003864 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003865 case PIXEL_FORMAT_TRANSPARENT:
3866 case PIXEL_FORMAT_TRANSLUCENT:
3867 format = PIXEL_FORMAT_RGBA_8888;
3868 break;
3869 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003870 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003871 break;
3872 }
3873
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003874 sp<BufferQueueLayer> layer =
3875 new BufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003876 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003877 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003878 *handle = layer->getHandle();
3879 *gbp = layer->getProducer();
3880 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003881 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003882
Marissa Wallfd668622018-05-10 10:21:13 -07003883 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003884 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003885}
3886
Marissa Wall61c58622018-07-18 10:12:20 -07003887status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3888 uint32_t w, uint32_t h, uint32_t flags,
3889 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003890 sp<BufferStateLayer> layer =
3891 new BufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003892 *handle = layer->getHandle();
3893 *outLayer = layer;
3894
3895 return NO_ERROR;
3896}
3897
chaviw13fdc492017-06-27 12:40:18 -07003898status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003899 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003900 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003901{
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003902 *outLayer = new ColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003903 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003904 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003905}
3906
Robert Carr6b3f6c52018-08-13 13:05:17 -07003907status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3908 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3909 sp<IBinder>* handle, sp<Layer>* outLayer)
3910{
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003911 *outLayer = new ContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003912 *handle = (*outLayer)->getHandle();
3913 return NO_ERROR;
3914}
3915
3916
Mathias Agopianac9fa422013-02-11 16:40:36 -08003917status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003918{
Robert Carr9524cb32017-02-13 11:32:32 -08003919 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003920 status_t err = NO_ERROR;
3921 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003922 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003923 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003924 err = removeLayer(l);
3925 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3926 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003927 }
3928 return err;
3929}
3930
Mathias Agopian13127d82013-03-05 17:47:11 -08003931status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003932{
Mathias Agopian67106042013-03-14 19:18:13 -07003933 // called by ~LayerCleaner() when all references to the IBinder (handle)
3934 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003935 sp<Layer> l = layer.promote();
3936 if (l == nullptr) {
3937 // The layer has already been removed, carry on
3938 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003939 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003940 // If we have a parent, then we can continue to live as long as it does.
3941 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003942}
3943
Mathias Agopianb60314a2012-04-10 22:09:54 -07003944// ---------------------------------------------------------------------------
3945
Andy McFadden13a082e2012-08-24 10:16:42 -07003946void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003947 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3948 if (!displayToken) return;
3949
Jesse Hall01e29052013-02-19 16:13:35 -08003950 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003951 Vector<ComposerState> state;
3952 Vector<DisplayState> displays;
3953 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003954 d.what = DisplayState::eDisplayProjectionChanged |
3955 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003956 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003957 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003958 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003959 d.frame.makeInvalid();
3960 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003961 d.width = 0;
3962 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003963 displays.add(d);
3964 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003965
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003966 const auto display = getDisplayDevice(displayToken);
3967 if (!display) return;
3968
3969 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3970
3971 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003972 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003973 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003974
Brian Andersond0010582017-03-07 13:20:31 -08003975 // Use phase of 0 since phase is not known.
3976 // Use latency of 0, which will snap to the ideal latency.
3977 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003978}
3979
3980void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003981 // Async since we may be called from the main thread.
3982 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003983}
3984
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003985void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3986 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003987 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003988 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003989
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003990 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003991 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003992 return;
3993 }
3994
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003995 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003996 ALOGW("Trying to set power mode for virtual display");
3997 return;
3998 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003999
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004000 display->setPowerMode(mode);
4001
Lloyd Pique4dccc412018-01-22 17:21:36 -08004002 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07004003 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004004 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07004005 if (idx < 0) {
4006 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
4007 return;
4008 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07004009 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07004010 }
4011
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004012 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004013 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004014 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004015 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004016 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004017 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004018 if (mUseScheduler) {
4019 mScheduler->onScreenAcquired(mAppConnectionHandle);
4020 } else {
4021 mEventThread->onScreenAcquired();
4022 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004023 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004024 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004025
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004026 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004027 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004028 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004029
4030 struct sched_param param = {0};
4031 param.sched_priority = 1;
4032 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4033 ALOGW("Couldn't set SCHED_FIFO on display on");
4034 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004035 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004036 // Turn off the display
4037 struct sched_param param = {0};
4038 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4039 ALOGW("Couldn't set SCHED_OTHER on display off");
4040 }
4041
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004042 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07004043 disableHardwareVsync(true); // also cancels any in-progress resync
4044
Mathias Agopiancde87a32012-09-13 14:09:01 -07004045 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004046 if (mUseScheduler) {
4047 mScheduler->onScreenReleased(mAppConnectionHandle);
4048 } else {
4049 mEventThread->onScreenReleased();
4050 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004051 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004052
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004053 getHwComposer().setPowerMode(type, mode);
4054 mVisibleRegionsDirty = true;
4055 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004056 } else if (mode == HWC_POWER_MODE_DOZE ||
4057 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004058 // Update display while dozing
4059 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004060 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004061 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004062 if (mUseScheduler) {
4063 mScheduler->onScreenAcquired(mAppConnectionHandle);
4064 } else {
4065 mEventThread->onScreenAcquired();
4066 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004067 resyncToHardwareVsync(true);
4068 }
4069 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4070 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004071 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004072 disableHardwareVsync(true); // also cancels any in-progress resync
4073 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004074 if (mUseScheduler) {
4075 mScheduler->onScreenReleased(mAppConnectionHandle);
4076 } else {
4077 mEventThread->onScreenReleased();
4078 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004079 }
4080 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004081 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004082 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004083 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004084 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004085
4086 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004087}
4088
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004089void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004090 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004091 const auto display = getDisplayDevice(displayToken);
4092 if (!display) {
4093 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4094 displayToken.get());
4095 } else if (display->isVirtual()) {
4096 ALOGW("Attempt to set power mode %d for virtual display", mode);
4097 } else {
4098 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004099 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004100 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004101}
4102
4103// ---------------------------------------------------------------------------
4104
Lloyd Pique755e3192018-01-31 16:46:15 -08004105status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4106 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004107 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004108
Mathias Agopianbd115332013-04-18 16:41:04 -07004109 IPCThreadState* ipc = IPCThreadState::self();
4110 const int pid = ipc->getCallingPid();
4111 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004112
Mathias Agopianbd115332013-04-18 16:41:04 -07004113 if ((uid != AID_SHELL) &&
4114 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004115 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004116 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004117 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004118 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004119 // (this would indicate SF is stuck, but we want to be able to
4120 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004121 status_t err = mStateLock.timedLock(s2ns(1));
4122 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004123 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004124 result.appendFormat(
4125 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4126 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004127 }
4128
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004129 bool dumpAll = true;
4130 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004131 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004132
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004133 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004134 if ((index < numArgs) &&
4135 (args[index] == String16("--list"))) {
4136 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004137 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004138 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004139 }
4140
4141 if ((index < numArgs) &&
4142 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004143 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004144 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004145 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004146 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004147
4148 if ((index < numArgs) &&
4149 (args[index] == String16("--latency-clear"))) {
4150 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004151 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004152 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004153 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004154
4155 if ((index < numArgs) &&
4156 (args[index] == String16("--dispsync"))) {
4157 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004158 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004159 dumpAll = false;
4160 }
Dan Stozab90cf072015-03-05 11:05:59 -08004161
4162 if ((index < numArgs) &&
4163 (args[index] == String16("--static-screen"))) {
4164 index++;
4165 dumpStaticScreenStats(result);
4166 dumpAll = false;
4167 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004168
4169 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004170 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004171 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004172 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004173 dumpAll = false;
4174 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004175
4176 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4177 index++;
4178 dumpWideColorInfo(result);
4179 dumpAll = false;
4180 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004181
4182 if ((index < numArgs) &&
4183 (args[index] == String16("--enable-layer-stats"))) {
4184 index++;
4185 mLayerStats.enable();
4186 dumpAll = false;
4187 }
4188
4189 if ((index < numArgs) &&
4190 (args[index] == String16("--disable-layer-stats"))) {
4191 index++;
4192 mLayerStats.disable();
4193 dumpAll = false;
4194 }
4195
4196 if ((index < numArgs) &&
4197 (args[index] == String16("--clear-layer-stats"))) {
4198 index++;
4199 mLayerStats.clear();
4200 dumpAll = false;
4201 }
4202
4203 if ((index < numArgs) &&
4204 (args[index] == String16("--dump-layer-stats"))) {
4205 index++;
4206 mLayerStats.dump(result);
4207 dumpAll = false;
4208 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004209
4210 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004211 (args[index] == String16("--frame-composition"))) {
4212 index++;
4213 dumpFrameCompositionInfo(result);
4214 dumpAll = false;
4215 }
4216
4217 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004218 (args[index] == String16("--display-identification"))) {
4219 index++;
4220 dumpDisplayIdentificationData(result);
4221 dumpAll = false;
4222 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004223
4224 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4225 index++;
4226 mTimeStats.parseArgs(asProto, args, index, result);
4227 dumpAll = false;
4228 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004229 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004230
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004231 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004232 if (asProto) {
4233 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4234 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4235 } else {
4236 dumpAllLocked(args, index, result);
4237 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004238 }
4239
Mathias Agopian9795c422009-08-26 16:36:26 -07004240 if (locked) {
4241 mStateLock.unlock();
4242 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004243 }
4244 write(fd, result.string(), result.size());
4245 return NO_ERROR;
4246}
4247
Dan Stozac7014012014-02-14 15:03:43 -08004248void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4249 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004250{
Robert Carr2047fae2016-11-28 14:09:09 -08004251 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004252 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004253 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004254}
4255
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004256void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004257 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004258{
4259 String8 name;
4260 if (index < args.size()) {
4261 name = String8(args[index]);
4262 index++;
4263 }
4264
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004265 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4266 getHwComposer().isConnected(displayId)) {
4267 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4268 const nsecs_t period = activeConfig->getVsyncPeriod();
4269 result.appendFormat("%" PRId64 "\n", period);
4270 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004271
4272 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004273 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004274 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004275 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004276 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004277 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004278 }
Robert Carr2047fae2016-11-28 14:09:09 -08004279 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004280 }
4281}
4282
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004283void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004284 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004285{
4286 String8 name;
4287 if (index < args.size()) {
4288 name = String8(args[index]);
4289 index++;
4290 }
4291
Robert Carr2047fae2016-11-28 14:09:09 -08004292 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004293 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004294 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004295 }
Robert Carr2047fae2016-11-28 14:09:09 -08004296 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004297
Svetoslavd85084b2014-03-20 10:28:31 -07004298 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004299}
4300
Jamie Gennis6547ff42013-07-16 20:12:42 -07004301// This should only be called from the main thread. Otherwise it would need
4302// the lock and should use mCurrentState rather than mDrawingState.
4303void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004304 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004305 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004306 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004307
4308 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4309}
4310
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004311void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004312{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004313 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004314
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004315 if (isLayerTripleBufferingDisabled())
4316 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004317
4318 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004319 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004320 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004321 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004322 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4323 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004324 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004325}
4326
Dan Stozab90cf072015-03-05 11:05:59 -08004327void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4328{
4329 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004330 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4331 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004332 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004333 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004334 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4335 b + 1, bucketTimeSec, percent);
4336 }
David Sodman4a36e932017-11-07 14:29:47 -08004337 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004338 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004339 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004340 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004341 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004342}
4343
Dan Stozae77c7662016-05-13 11:37:28 -07004344void SurfaceFlinger::recordBufferingStats(const char* layerName,
4345 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004346 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4347 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004348 for (const auto& segment : history) {
4349 if (!segment.usedThirdBuffer) {
4350 stats.twoBufferTime += segment.totalTime;
4351 }
4352 if (segment.occupancyAverage < 1.0f) {
4353 stats.doubleBufferedTime += segment.totalTime;
4354 } else if (segment.occupancyAverage < 2.0f) {
4355 stats.tripleBufferedTime += segment.totalTime;
4356 }
4357 ++stats.numSegments;
4358 stats.totalTime += segment.totalTime;
4359 }
4360}
4361
Brian Andersond6927fb2016-07-23 23:37:30 -07004362void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4363 result.appendFormat("Layer frame timestamps:\n");
4364
4365 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4366 const size_t count = currentLayers.size();
4367 for (size_t i=0 ; i<count ; i++) {
4368 currentLayers[i]->dumpFrameEvents(result);
4369 }
4370}
4371
Dan Stozae77c7662016-05-13 11:37:28 -07004372void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4373 result.append("Buffering stats:\n");
4374 result.append(" [Layer name] <Active time> <Two buffer> "
4375 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004376 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004377 typedef std::tuple<std::string, float, float, float> BufferTuple;
4378 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004379 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004380 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004381 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004382 if (stats.numSegments == 0) {
4383 continue;
4384 }
4385 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4386 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4387 stats.totalTime;
4388 float doubleBufferRatio = static_cast<float>(
4389 stats.doubleBufferedTime) / stats.totalTime;
4390 float tripleBufferRatio = static_cast<float>(
4391 stats.tripleBufferedTime) / stats.totalTime;
4392 sorted.insert({activeTime, {name, twoBufferRatio,
4393 doubleBufferRatio, tripleBufferRatio}});
4394 }
4395 for (const auto& sortedPair : sorted) {
4396 float activeTime = sortedPair.first;
4397 const BufferTuple& values = sortedPair.second;
4398 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4399 std::get<0>(values).c_str(), activeTime,
4400 std::get<1>(values), std::get<2>(values),
4401 std::get<3>(values));
4402 }
4403 result.append("\n");
4404}
4405
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004406void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004407 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004408 const int32_t displayId = display->getId();
4409 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4410 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004411 continue;
4412 }
4413
Dominik Laskowski7e045462018-05-30 13:02:02 -07004414 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004415 uint8_t port;
4416 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004417 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004418 result.append("no identification data\n");
4419 continue;
4420 }
4421
4422 if (!isEdid(data)) {
4423 result.append("unknown identification data: ");
4424 for (uint8_t byte : data) {
4425 result.appendFormat("%x ", byte);
4426 }
4427 result.append("\n");
4428 continue;
4429 }
4430
4431 const auto edid = parseEdid(data);
4432 if (!edid) {
4433 result.append("invalid EDID: ");
4434 for (uint8_t byte : data) {
4435 result.appendFormat("%x ", byte);
4436 }
4437 result.append("\n");
4438 continue;
4439 }
4440
4441 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4442 result.append(edid->displayName.data(), edid->displayName.length());
4443 result.append("\"\n");
4444 }
4445 result.append("\n");
4446}
4447
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004448void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004449 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4450 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004451 result.appendFormat("DisplayColorSetting: %s\n",
4452 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004453
4454 // TODO: print out if wide-color mode is active or not
4455
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004456 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004457 const int32_t displayId = display->getId();
4458 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004459 continue;
4460 }
4461
Dominik Laskowski7e045462018-05-30 13:02:02 -07004462 result.appendFormat("Display %d color modes:\n", displayId);
4463 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004464 for (auto&& mode : modes) {
4465 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4466 }
4467
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004468 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004469 result.appendFormat(" Current color mode: %s (%d)\n",
4470 decodeColorMode(currentMode).c_str(), currentMode);
4471 }
4472 result.append("\n");
4473}
4474
David Sodman7e4ae112018-02-09 15:02:28 -08004475void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4476 std::string stringResult;
4477
4478 for (const auto& [token, display] : mDisplays) {
4479 const auto displayId = display->getId();
4480 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
4481 continue;
4482 }
4483
4484 const auto& compositionInfoIt = getBE().mEndOfFrameCompositionInfo.find(displayId);
4485 if (compositionInfoIt == getBE().mEndOfFrameCompositionInfo.end()) {
4486 break;
4487 }
4488 const auto& compositionInfoList = compositionInfoIt->second;
4489 stringResult += base::StringPrintf("Display: %d\n", displayId);
4490 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4491 for (const auto& compositionInfo : compositionInfoList) {
4492 compositionInfo.dump(stringResult, nullptr);
4493 stringResult += base::StringPrintf("\n");
4494 }
4495 }
4496
4497 result.append(stringResult.c_str());
4498}
4499
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004500LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004501 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004502 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4503 const State& state = useDrawing ? mDrawingState : mCurrentState;
4504 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004505 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004506 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004507 });
4508
4509 return layersProto;
4510}
4511
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004512LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004513 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004514
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004515 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004516 resolution->set_w(display.getWidth());
4517 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004518
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004519 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4520 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4521 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004522
Dominik Laskowski7e045462018-05-30 13:02:02 -07004523 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004524 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004525 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004526 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004527 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004528 }
4529 });
4530
4531 return layersProto;
4532}
4533
Mathias Agopian74d211a2013-04-22 16:55:35 +02004534void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4535 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004536{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004537 bool colorize = false;
4538 if (index < args.size()
4539 && (args[index] == String16("--color"))) {
4540 colorize = true;
4541 index++;
4542 }
4543
4544 Colorizer colorizer(colorize);
4545
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004546 // figure out if we're stuck somewhere
4547 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004548 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004549 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4550
4551 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004552 * Dump library configuration.
4553 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004554
4555 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004556 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004557 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004558 appendSfConfigString(result);
4559 appendUiConfigString(result);
4560 appendGuiConfigString(result);
4561 result.append("\n");
4562
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004563 result.append("\nDisplay identification data:\n");
4564 dumpDisplayIdentificationData(result);
4565
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004566 result.append("\nWide-Color information:\n");
4567 dumpWideColorInfo(result);
4568
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004569 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004570 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004571 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004572 result.append(SyncFeatures::getInstance().toString());
4573 result.append("\n");
4574
Andy McFadden41d67d72014-04-25 16:58:34 -07004575 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004576 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004577 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004578
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004579 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4580 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004581 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4582 getHwComposer().isConnected(displayId)) {
4583 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004584 result.appendFormat("Display %d: "
4585 "app phase %" PRId64 " ns, "
4586 "sf phase %" PRId64 " ns, "
4587 "early app phase %" PRId64 " ns, "
4588 "early sf phase %" PRId64 " ns, "
4589 "early app gl phase %" PRId64 " ns, "
4590 "early sf gl phase %" PRId64 " ns, "
4591 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4592 displayId,
4593 vsyncPhaseOffsetNs,
4594 sfVsyncPhaseOffsetNs,
4595 appEarlyOffset,
4596 sfEarlyOffset,
4597 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004598 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004599 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004600 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004601 result.append("\n");
4602
Dan Stozab90cf072015-03-05 11:05:59 -08004603 // Dump static screen stats
4604 result.append("\n");
4605 dumpStaticScreenStats(result);
4606 result.append("\n");
4607
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004608 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4609
Dan Stozae77c7662016-05-13 11:37:28 -07004610 dumpBufferingStats(result);
4611
Andy McFadden4803b742012-09-24 19:07:20 -07004612 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004613 * Dump the visible layer list
4614 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004615 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004616 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004617 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4618 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004619 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004620
Chia-I Wu2f884132018-09-13 15:17:58 -07004621 {
4622 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4623 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4624 result.append(LayerProtoParser::layerTreeToString(layerTree).c_str());
4625 result.append("\n");
4626 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004627
David Sodman7e4ae112018-02-09 15:02:28 -08004628 result.append("\nFrame-Composition information:\n");
4629 dumpFrameCompositionInfo(result);
4630 result.append("\n");
4631
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004632 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004633 * Dump Display state
4634 */
4635
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004636 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004637 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004638 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004639 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004640 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004641 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004642 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004643
4644 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004645 * Dump SurfaceFlinger global state
4646 */
4647
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004648 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004649 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004650 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004651
Mathias Agopian888c8222012-08-04 21:10:38 -07004652 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004653 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004654
David Sodmanbc815282017-11-05 18:57:52 -08004655 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004656
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004657 if (display) {
4658 display->undefinedRegion.dump(result, "undefinedRegion");
4659 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4660 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004661 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004662 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004663 " gpu_to_cpu_unsupported : %d\n",
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004664 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004665
4666 if (display) {
4667 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4668 result.appendFormat(" refresh-rate : %f fps\n"
4669 " x-dpi : %f\n"
4670 " y-dpi : %f\n",
4671 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4672 activeConfig->getDpiY());
4673 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004674
Mathias Agopian74d211a2013-04-22 16:55:35 +02004675 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004676 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004677
Ana Krulec98b5b242018-08-10 15:03:23 -07004678 result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004679 /*
4680 * VSYNC state
4681 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004682 if (mUseScheduler) {
4683 mScheduler->dump(mAppConnectionHandle, result);
4684 } else {
4685 mEventThread->dump(result);
4686 }
Dan Stozae22aec72016-08-01 13:20:59 -07004687 result.append("\n");
4688
4689 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004690 * Tracing state
4691 */
4692 mTracing.dump(result);
4693 result.append("\n");
4694
4695 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004696 * HWC layer minidump
4697 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004698 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004699 const int32_t displayId = display->getId();
4700 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004701 continue;
4702 }
4703
Dominik Laskowski7e045462018-05-30 13:02:02 -07004704 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004705 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004706 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004707 result.append("\n");
4708 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004709
4710 /*
4711 * Dump HWComposer state
4712 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004713 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004714 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004715 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004716 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004717 result.appendFormat(" h/w composer %s\n",
4718 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004719 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004720
4721 /*
4722 * Dump gralloc state
4723 */
4724 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4725 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004726
4727 /*
4728 * Dump VrFlinger state if in use.
4729 */
4730 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4731 result.append("VrFlinger state:\n");
4732 result.append(mVrFlinger->Dump().c_str());
4733 result.append("\n");
4734 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004735}
4736
Dominik Laskowski7e045462018-05-30 13:02:02 -07004737const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004738 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004739 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004740 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004741 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004742 }
4743 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004744
4745 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4746 static const Vector<sp<Layer>> empty;
4747 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004748}
4749
Keun young Park63f165f2012-08-31 10:53:36 -07004750bool SurfaceFlinger::startDdmConnection()
4751{
4752 void* libddmconnection_dso =
4753 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4754 if (!libddmconnection_dso) {
4755 return false;
4756 }
4757 void (*DdmConnection_start)(const char* name);
4758 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004759 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004760 if (!DdmConnection_start) {
4761 dlclose(libddmconnection_dso);
4762 return false;
4763 }
4764 (*DdmConnection_start)(getServiceName());
4765 return true;
4766}
4767
Chia-I Wu28f320b2018-05-03 11:02:56 -07004768void SurfaceFlinger::updateColorMatrixLocked() {
4769 mat4 colorMatrix;
4770 if (mGlobalSaturationFactor != 1.0f) {
4771 // Rec.709 luma coefficients
4772 float3 luminance{0.213f, 0.715f, 0.072f};
4773 luminance *= 1.0f - mGlobalSaturationFactor;
4774 mat4 saturationMatrix = mat4(
4775 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4776 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4777 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4778 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4779 );
4780 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4781 } else {
4782 colorMatrix = mClientColorMatrix * mDaltonizer();
4783 }
4784
4785 if (mCurrentState.colorMatrix != colorMatrix) {
4786 mCurrentState.colorMatrix = colorMatrix;
4787 mCurrentState.colorMatrixChanged = true;
4788 setTransactionFlags(eTransactionNeeded);
4789 }
4790}
4791
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004792status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004793#pragma clang diagnostic push
4794#pragma clang diagnostic error "-Wswitch-enum"
4795 switch (static_cast<ISurfaceComposerTag>(code)) {
4796 // These methods should at minimum make sure that the client requested
4797 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004798 case BOOT_FINISHED:
4799 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004800 case CREATE_CONNECTION:
4801 case CREATE_DISPLAY:
4802 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004803 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004804 case GET_ACTIVE_COLOR_MODE:
4805 case GET_ANIMATION_FRAME_STATS:
4806 case GET_HDR_CAPABILITIES:
4807 case SET_ACTIVE_CONFIG:
4808 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004809 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004810 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004811 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4812 IPCThreadState* ipc = IPCThreadState::self();
4813 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4814 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004815 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004816 }
Robert Carr1db73f62016-12-21 12:58:51 -08004817 return OK;
4818 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004819 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004820 IPCThreadState* ipc = IPCThreadState::self();
4821 const int pid = ipc->getCallingPid();
4822 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004823 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4824 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004825 return PERMISSION_DENIED;
4826 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004827 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004828 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004829 // Used by apps to hook Choreographer to SurfaceFlinger.
4830 case CREATE_DISPLAY_EVENT_CONNECTION:
4831 // The following calls are currently used by clients that do not
4832 // request necessary permissions. However, they do not expose any secret
4833 // information, so it is OK to pass them.
4834 case AUTHENTICATE_SURFACE:
4835 case GET_ACTIVE_CONFIG:
4836 case GET_BUILT_IN_DISPLAY:
4837 case GET_DISPLAY_COLOR_MODES:
4838 case GET_DISPLAY_CONFIGS:
4839 case GET_DISPLAY_STATS:
4840 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4841 // Calling setTransactionState is safe, because you need to have been
4842 // granted a reference to Client* and Handle* to do anything with it.
4843 case SET_TRANSACTION_STATE:
4844 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004845 case CREATE_SCOPED_CONNECTION:
4846 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004847 return OK;
4848 }
4849 case CAPTURE_LAYERS:
4850 case CAPTURE_SCREEN: {
4851 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004852 IPCThreadState* ipc = IPCThreadState::self();
4853 const int pid = ipc->getCallingPid();
4854 const int uid = ipc->getCallingUid();
4855 if ((uid != AID_GRAPHICS) &&
4856 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4857 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4858 return PERMISSION_DENIED;
4859 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004860 return OK;
4861 }
4862 // The following codes are deprecated and should never be allowed to access SF.
4863 case CONNECT_DISPLAY_UNUSED:
4864 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4865 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4866 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004867 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004868 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004869
4870 // These codes are used for the IBinder protocol to either interrogate the recipient
4871 // side of the transaction for its canonical interface descriptor or to dump its state.
4872 // We let them pass by default.
4873 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4874 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4875 code == IBinder::SYSPROPS_TRANSACTION) {
4876 return OK;
4877 }
4878 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4879 // in onTransact verifies that the user is root, and has access to use SF.
4880 if (code >= 1000 && code <= 1029) {
4881 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4882 return OK;
4883 }
4884 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4885 return PERMISSION_DENIED;
4886#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004887}
4888
Ana Krulec13be8ad2018-08-21 02:43:56 +00004889status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4890 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004891 status_t credentialCheck = CheckTransactCodeCredentials(code);
4892 if (credentialCheck != OK) {
4893 return credentialCheck;
4894 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004895
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004896 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4897 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004898 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004899 IPCThreadState* ipc = IPCThreadState::self();
4900 const int uid = ipc->getCallingUid();
4901 if (CC_UNLIKELY(uid != AID_SYSTEM
4902 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004903 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004904 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004905 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004906 return PERMISSION_DENIED;
4907 }
4908 int n;
4909 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004910 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004911 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004912 return NO_ERROR;
4913 case 1002: // SHOW_UPDATES
4914 n = data.readInt32();
4915 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004916 invalidateHwcGeometry();
4917 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004918 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004919 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004920 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004921 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004922 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004923 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004924 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004925 setTransactionFlags(
4926 eTransactionNeeded|
4927 eDisplayTransactionNeeded|
4928 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004929 return NO_ERROR;
4930 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004931 case 1006:{ // send empty update
4932 signalRefresh();
4933 return NO_ERROR;
4934 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004935 case 1008: // toggle use of hw composer
4936 n = data.readInt32();
4937 mDebugDisableHWC = n ? 1 : 0;
4938 invalidateHwcGeometry();
4939 repaintEverything();
4940 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004941 case 1009: // toggle use of transform hint
4942 n = data.readInt32();
4943 mDebugDisableTransformHint = n ? 1 : 0;
4944 invalidateHwcGeometry();
4945 repaintEverything();
4946 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004947 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004948 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004949 reply->writeInt32(0);
4950 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004951 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004952 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004953 return NO_ERROR;
4954 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004955 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004956 if (!display) {
4957 return NAME_NOT_FOUND;
4958 }
4959
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004960 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004961 return NO_ERROR;
4962 }
4963 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004964 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004965 // daltonize
4966 n = data.readInt32();
4967 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004968 case 1:
4969 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4970 break;
4971 case 2:
4972 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4973 break;
4974 case 3:
4975 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4976 break;
4977 default:
4978 mDaltonizer.setType(ColorBlindnessType::None);
4979 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004980 }
4981 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004982 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004983 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004984 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004985 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004986
4987 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004988 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004989 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004990 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004991 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004992 // apply a color matrix
4993 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004994 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004995 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004996 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004997 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004998 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004999 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005000 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005001 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005002 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005003 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005004
5005 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5006 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005007 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005008 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5009 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5010 }
5011
Chia-I Wu28f320b2018-05-03 11:02:56 -07005012 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005013 return NO_ERROR;
5014 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005015 // This is an experimental interface
5016 // Needs to be shifted to proper binder interface when we productize
5017 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005018 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07005019 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005020 return NO_ERROR;
5021 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005022 case 1017: {
5023 n = data.readInt32();
5024 mForceFullDamage = static_cast<bool>(n);
5025 return NO_ERROR;
5026 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005027 case 1018: { // Modify Choreographer's phase offset
5028 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005029 if (mUseScheduler) {
5030 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5031 } else {
5032 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5033 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005034 return NO_ERROR;
5035 }
5036 case 1019: { // Modify SurfaceFlinger's phase offset
5037 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005038 if (mUseScheduler) {
5039 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5040 } else {
5041 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5042 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005043 return NO_ERROR;
5044 }
Irvel468051e2016-06-13 16:44:44 -07005045 case 1020: { // Layer updates interceptor
5046 n = data.readInt32();
5047 if (n) {
5048 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005049 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005050 }
5051 else{
5052 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005053 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005054 }
5055 return NO_ERROR;
5056 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005057 case 1021: { // Disable HWC virtual displays
5058 n = data.readInt32();
5059 mUseHwcVirtualDisplays = !n;
5060 return NO_ERROR;
5061 }
Romain Guy0147a172017-06-01 13:53:56 -07005062 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005063 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005064 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005065
Chia-I Wu28f320b2018-05-03 11:02:56 -07005066 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005067 return NO_ERROR;
5068 }
Romain Guy54f154a2017-10-24 21:40:32 +01005069 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005070 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005071 invalidateHwcGeometry();
5072 repaintEverything();
5073 return NO_ERROR;
5074 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005075 // TODO(b/111505327): Find out whether the usage of 1024 can switch to 1030,
5076 // deprecate 1024 if they can.
5077 case 1024: { // Does device have wide color gamut display?
Romain Guy54f154a2017-10-24 21:40:32 +01005078 reply->writeBool(hasWideColorDisplay);
5079 return NO_ERROR;
5080 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005081 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005082 n = data.readInt32();
5083 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005084 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005085 mTracing.enable();
5086 doTracing("tracing.enable");
5087 reply->writeInt32(NO_ERROR);
5088 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005089 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005090 status_t err = mTracing.disable();
5091 reply->writeInt32(err);
5092 }
5093 return NO_ERROR;
5094 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005095 case 1026: { // Get layer tracing status
5096 reply->writeBool(mTracing.isEnabled());
5097 return NO_ERROR;
5098 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005099 // Is a DisplayColorSetting supported?
5100 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005101 const auto display = getDefaultDisplayDevice();
5102 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005103 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005104 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005105
5106 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5107 switch (setting) {
5108 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005109 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005110 break;
5111 case DisplayColorSetting::UNMANAGED:
5112 reply->writeBool(true);
5113 break;
5114 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005115 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005116 break;
5117 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005118 reply->writeBool(
5119 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005120 break;
5121 }
5122 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005123 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005124 // Is VrFlinger active?
5125 case 1028: {
5126 Mutex::Autolock _l(mStateLock);
5127 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5128 return NO_ERROR;
5129 }
David Sodman6d46c1e2018-07-13 12:59:48 -07005130 case 1029: {
5131 // Code 1029 is an experimental feature that allows applications to
5132 // simulate a high frequency panel by setting a multiplier and divisor
5133 // on the VSYNC-sf clock. If either the multiplier or divisor are
David Sodman44b5de02018-08-21 16:28:53 -07005134 // 0, then the code simply return the current multiplier and divisor.
5135 HWC2::Device::FrequencyScaler frequencyScaler;
5136 frequencyScaler.multiplier = data.readInt32();
5137 frequencyScaler.divisor = data.readInt32();
David Sodman6d46c1e2018-07-13 12:59:48 -07005138
David Sodman44b5de02018-08-21 16:28:53 -07005139 if ((frequencyScaler.multiplier == 0) || (frequencyScaler.divisor == 0)) {
5140 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5141 reply->writeInt32(frequencyScaler.multiplier);
5142 reply->writeInt32(frequencyScaler.divisor);
5143 return NO_ERROR;
David Sodman6d46c1e2018-07-13 12:59:48 -07005144 }
5145
David Sodman44b5de02018-08-21 16:28:53 -07005146 if ((frequencyScaler.multiplier == 1) && (frequencyScaler.divisor == 1)) {
David Sodman6d46c1e2018-07-13 12:59:48 -07005147 enableHardwareVsync();
5148 } else {
5149 disableHardwareVsync(true);
5150 }
David Sodman44b5de02018-08-21 16:28:53 -07005151 mPrimaryDispSync->scalePeriod(frequencyScaler);
5152 getBE().mHwc->setDisplayFrequencyScaleParameters(frequencyScaler);
David Sodman6d46c1e2018-07-13 12:59:48 -07005153
David Sodman44b5de02018-08-21 16:28:53 -07005154 ATRACE_INT("PeriodMultiplier", frequencyScaler.multiplier);
5155 ATRACE_INT("PeriodDivisor", frequencyScaler.divisor);
5156
5157 const hwc2_display_t hwcDisplayId = getBE().mHwc->getActiveConfig(
5158 DisplayDevice::DISPLAY_PRIMARY)->getDisplayId();
5159
5160 onHotplugReceived(getBE().mComposerSequenceId,
5161 hwcDisplayId, HWC2::Connection::Disconnected);
5162 onHotplugReceived(getBE().mComposerSequenceId,
5163 hwcDisplayId, HWC2::Connection::Connected);
5164 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5165 reply->writeInt32(frequencyScaler.multiplier);
5166 reply->writeInt32(frequencyScaler.divisor);
5167
David Sodman6d46c1e2018-07-13 12:59:48 -07005168 return NO_ERROR;
5169 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005170 // Is device color managed?
5171 case 1030: {
5172 reply->writeBool(useColorManagement);
5173 return NO_ERROR;
5174 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005175 }
5176 }
5177 return err;
5178}
5179
Steven Thomas6d8110b2017-08-31 18:24:21 -07005180void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005181 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005182 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005183}
5184
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005185// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5186class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005187public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005188 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5189 ~WindowDisconnector() {
5190 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005191 }
5192
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005193private:
5194 ANativeWindow* mWindow;
5195 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005196};
5197
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005198status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
5199 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005200 uint32_t reqWidth, uint32_t reqHeight,
5201 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005202 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005203 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005204
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005205 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005206
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005207 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5208
Chia-I Wu20261cb2018-08-23 12:55:44 -07005209 sp<DisplayDevice> display;
5210 {
5211 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005212
Chia-I Wu20261cb2018-08-23 12:55:44 -07005213 display = getDisplayDeviceLocked(displayToken);
5214 if (!display) return BAD_VALUE;
5215
Chia-I Wu8730ba82018-08-29 09:25:59 -07005216 // ignore sourceCrop (i.e., use the projected logical display
5217 // viewport) until the framework is fixed
5218 sourceCrop.clear();
Chia-I Wucb023152018-08-28 12:57:23 -07005219
5220 // set the requested width/height to the logical display viewport size
5221 // by default
5222 if (reqWidth == 0 || reqHeight == 0) {
5223 reqWidth = uint32_t(display->getViewport().width());
5224 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005225 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005226 }
5227
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005228 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005229
5230 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005231 display, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005232 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005233}
5234
5235status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08005236 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005237 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005238 ATRACE_CALL();
5239
5240 class LayerRenderArea : public RenderArea {
5241 public:
Robert Carr578038f2018-03-09 12:25:24 -08005242 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
5243 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
Chia-I Wu9d1abea2018-08-23 13:44:43 -07005244 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08005245 mLayer(layer),
5246 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005247 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005248 mFlinger(flinger),
5249 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005250 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005251 Rect getBounds() const override {
5252 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005253 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005254 }
Marissa Wall61c58622018-07-18 10:12:20 -07005255 int getHeight() const override {
5256 return mLayer->getActiveHeight(mLayer->getDrawingState());
5257 }
5258 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005259 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005260 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005261 Rect getSourceCrop() const override {
5262 if (mCrop.isEmpty()) {
5263 return getBounds();
5264 } else {
5265 return mCrop;
5266 }
5267 }
Robert Carr578038f2018-03-09 12:25:24 -08005268 class ReparentForDrawing {
5269 public:
5270 const sp<Layer>& oldParent;
5271 const sp<Layer>& newParent;
5272
5273 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5274 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005275 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005276 }
Robert Carr15eae092018-03-23 13:43:53 -07005277 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005278 };
5279
5280 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005281 const Rect sourceCrop = getSourceCrop();
5282 // no need to check rotation because there is none
5283 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5284 sourceCrop.height() != getReqHeight();
5285
Robert Carr578038f2018-03-09 12:25:24 -08005286 if (!mChildrenOnly) {
5287 mTransform = mLayer->getTransform().inverse();
5288 drawLayers();
5289 } else {
5290 Rect bounds = getBounds();
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005291 screenshotParentLayer = new ContainerLayer(
5292 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5293 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005294
5295 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5296 drawLayers();
5297 }
5298 }
chaviwa76b2712017-09-20 12:02:26 -07005299
chaviwa76b2712017-09-20 12:02:26 -07005300 private:
chaviw7206d492017-11-10 16:16:12 -08005301 const sp<Layer> mLayer;
5302 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005303
5304 // In the "childrenOnly" case we reparent the children to a screenshot
5305 // layer which has no properties set and which does not draw.
5306 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005307 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005308 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005309
5310 SurfaceFlinger* mFlinger;
5311 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005312 };
5313
5314 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5315 auto parent = layerHandle->owner.promote();
5316
chaviw7206d492017-11-10 16:16:12 -08005317 if (parent == nullptr || parent->isPendingRemoval()) {
5318 ALOGE("captureLayers called with a removed parent");
5319 return NAME_NOT_FOUND;
5320 }
5321
Robert Carr578038f2018-03-09 12:25:24 -08005322 const int uid = IPCThreadState::self()->getCallingUid();
5323 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5324 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5325 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5326 return PERMISSION_DENIED;
5327 }
5328
chaviw7206d492017-11-10 16:16:12 -08005329 Rect crop(sourceCrop);
5330 if (sourceCrop.width() <= 0) {
5331 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005332 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005333 }
5334
5335 if (sourceCrop.height() <= 0) {
5336 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005337 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005338 }
5339
5340 int32_t reqWidth = crop.width() * frameScale;
5341 int32_t reqHeight = crop.height() * frameScale;
5342
Chia-I Wu20261cb2018-08-23 12:55:44 -07005343 // really small crop or frameScale
5344 if (reqWidth <= 0) {
5345 reqWidth = 1;
5346 }
5347 if (reqHeight <= 0) {
5348 reqHeight = 1;
5349 }
5350
Robert Carr578038f2018-03-09 12:25:24 -08005351 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005352
Robert Carr578038f2018-03-09 12:25:24 -08005353 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005354 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5355 if (!layer->isVisible()) {
5356 return;
Robert Carr578038f2018-03-09 12:25:24 -08005357 } else if (childrenOnly && layer == parent.get()) {
5358 return;
chaviwa76b2712017-09-20 12:02:26 -07005359 }
5360 visitor(layer);
5361 });
5362 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005363 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005364}
5365
5366status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5367 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005368 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005369 bool useIdentityTransform) {
5370 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005371
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005372 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5373 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5374 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5375 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005376
5377 // This mutex protects syncFd and captureResult for communication of the return values from the
5378 // main thread back to this Binder thread
5379 std::mutex captureMutex;
5380 std::condition_variable captureCondition;
5381 std::unique_lock<std::mutex> captureLock(captureMutex);
5382 int syncFd = -1;
5383 std::optional<status_t> captureResult;
5384
Robert Carr03480e22018-01-04 16:02:06 -08005385 const int uid = IPCThreadState::self()->getCallingUid();
5386 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5387
Dominik Laskowski8c001672018-05-30 16:52:06 -07005388 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005389 // If there is a refresh pending, bug out early and tell the binder thread to try again
5390 // after the refresh.
5391 if (mRefreshPending) {
5392 ATRACE_NAME("Skipping screenshot for now");
5393 std::unique_lock<std::mutex> captureLock(captureMutex);
5394 captureResult = std::make_optional<status_t>(EAGAIN);
5395 captureCondition.notify_one();
5396 return;
5397 }
5398
5399 status_t result = NO_ERROR;
5400 int fd = -1;
5401 {
5402 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005403 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005404 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5405 useIdentityTransform, forSystem, &fd);
5406 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005407 }
5408
5409 {
5410 std::unique_lock<std::mutex> captureLock(captureMutex);
5411 syncFd = fd;
5412 captureResult = std::make_optional<status_t>(result);
5413 captureCondition.notify_one();
5414 }
5415 });
5416
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005417 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005418 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005419 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005420 while (*captureResult == EAGAIN) {
5421 captureResult.reset();
5422 result = postMessageAsync(message);
5423 if (result != NO_ERROR) {
5424 return result;
5425 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005426 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005427 }
5428 result = *captureResult;
5429 }
5430
5431 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005432 sync_wait(syncFd, -1);
5433 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005434 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005435
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005436 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005437}
5438
chaviwa76b2712017-09-20 12:02:26 -07005439void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005440 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005441 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005442 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005443
Lloyd Pique144e1162017-12-20 16:44:52 -08005444 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005445
chaviwa76b2712017-09-20 12:02:26 -07005446 const auto reqWidth = renderArea.getReqWidth();
5447 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005448 const auto sourceCrop = renderArea.getSourceCrop();
5449 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005450
Chia-I Wu36574d92018-05-16 10:54:36 -07005451 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5452 engine.setOutputDataSpace(Dataspace::SRGB);
5453 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005454
Mathias Agopian180f10d2013-04-10 22:55:41 -07005455 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005456 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005457
5458 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005459 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005460 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005461
chaviw50da5042018-04-09 13:49:37 -07005462 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005463 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005464 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005465
chaviwa76b2712017-09-20 12:02:26 -07005466 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005467 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005468 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005469 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005470 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005471}
5472
chaviwa76b2712017-09-20 12:02:26 -07005473status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5474 TraverseLayersFunction traverseLayers,
5475 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005476 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005477 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005478 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005479 ATRACE_CALL();
5480
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005481 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005482
5483 traverseLayers([&](Layer* layer) {
5484 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5485 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005486
Robert Carr03480e22018-01-04 16:02:06 -08005487 // We allow the system server to take screenshots of secure layers for
5488 // use in situations like the Screen-rotation animation and place
5489 // the impetus on WindowManager to not persist them.
5490 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005491 ALOGW("FB is protected: PERMISSION_DENIED");
5492 return PERMISSION_DENIED;
5493 }
5494
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005495 // this binds the given EGLImage as a framebuffer for the
5496 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005497 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005498 if (bufferBond.getStatus() != NO_ERROR) {
5499 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005500 return INVALID_OPERATION;
5501 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005502
Dan Stozaabcda352017-06-01 14:37:39 -07005503 // this will in fact render into our dequeued buffer
5504 // via an FBO, which means we didn't have to create
5505 // an EGLSurface and therefore we're not
5506 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005507 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005508
Alec Mouri492bc572018-09-11 21:40:04 +00005509 base::unique_fd syncFd = getRenderEngine().flush();
5510 if (syncFd < 0) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005511 getRenderEngine().finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005512 }
Alec Mouri492bc572018-09-11 21:40:04 +00005513 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005514
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005515 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005516}
5517
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005518// ---------------------------------------------------------------------------
5519
Dan Stoza412903f2017-04-27 13:42:17 -07005520void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5521 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005522}
5523
Dan Stoza412903f2017-04-27 13:42:17 -07005524void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5525 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005526}
5527
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005528void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005529 const LayerVector::Visitor& visitor) {
5530 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005531 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005532 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005533 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005534 continue;
5535 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005536 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005537 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005538 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005539 return;
5540 }
chaviwa76b2712017-09-20 12:02:26 -07005541 if (!layer->isVisible()) {
5542 return;
5543 }
5544 visitor(layer);
5545 });
5546 }
5547}
5548
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005549}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005550
Lloyd Pique074e8122018-07-26 12:57:23 -07005551
Mathias Agopian3f844832013-08-07 21:24:32 -07005552#if defined(__gl_h_)
5553#error "don't include gl/gl.h in this file"
5554#endif
5555
5556#if defined(__gl2_h_)
5557#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005558#endif