blob: d3f34601b401ef4e7f9e9288207c73c7d44db6e1 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Chia-I Wud49d6692018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070050#include <renderengine/RenderEngine.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070051#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070066#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070067#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020070#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080072#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080073#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070077#include "NativeWindowSurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070081#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070082#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070083#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070084#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070086#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070087#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070088#include "Scheduler/EventControlThread.h"
89#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070090#include "Scheduler/InjectVSyncSource.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070091#include "Scheduler/Scheduler.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070092
Mathias Agopianff2ed702013-09-01 21:36:12 -070093#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070094
David Sodman7e4ae112018-02-09 15:02:28 -080095#include "android-base/stringprintf.h"
96
Jiyong Park4b20c2e2017-01-14 19:45:11 +090097#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080098#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -070099#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800100#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900101#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900102
chaviw1d044282017-09-27 12:19:28 -0700103#include <layerproto/LayerProtoParser.h>
104
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800105#define DISPLAY_COUNT 1
106
107namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700108
Jaesoo Lee43518572017-01-23 19:03:16 +0900109using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900110using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700111using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700112using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700113using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700114using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900115
Steven Thomasb02664d2017-07-26 18:48:28 -0700116namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700117
118#pragma clang diagnostic push
119#pragma clang diagnostic error "-Wswitch-enum"
120
121bool isWideColorMode(const ColorMode colorMode) {
122 switch (colorMode) {
123 case ColorMode::DISPLAY_P3:
124 case ColorMode::ADOBE_RGB:
125 case ColorMode::DCI_P3:
126 case ColorMode::BT2020:
127 case ColorMode::BT2100_PQ:
128 case ColorMode::BT2100_HLG:
129 return true;
130 case ColorMode::NATIVE:
131 case ColorMode::STANDARD_BT601_625:
132 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
133 case ColorMode::STANDARD_BT601_525:
134 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
135 case ColorMode::STANDARD_BT709:
136 case ColorMode::SRGB:
137 return false;
138 }
139 return false;
140}
141
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700142ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
143 switch (rotation) {
144 case ISurfaceComposer::eRotateNone:
145 return ui::Transform::ROT_0;
146 case ISurfaceComposer::eRotate90:
147 return ui::Transform::ROT_90;
148 case ISurfaceComposer::eRotate180:
149 return ui::Transform::ROT_180;
150 case ISurfaceComposer::eRotate270:
151 return ui::Transform::ROT_270;
152 }
153 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
154 return ui::Transform::ROT_0;
155}
156
Peiyong Linfca547f2018-07-09 13:03:33 -0700157#pragma clang diagnostic pop
158
Steven Thomasb02664d2017-07-26 18:48:28 -0700159class ConditionalLock {
160public:
161 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
162 if (lock) {
163 mMutex.lock();
164 }
165 }
166 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
167private:
168 Mutex& mMutex;
169 bool mLocked;
170};
Peiyong Linfca547f2018-07-09 13:03:33 -0700171
Steven Thomasb02664d2017-07-26 18:48:28 -0700172} // namespace anonymous
173
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800174// ---------------------------------------------------------------------------
175
Mathias Agopian99b49842011-06-27 16:05:52 -0700176const String16 sHardwareTest("android.permission.HARDWARE_TEST");
177const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
178const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
179const String16 sDump("android.permission.DUMP");
180
181// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800182int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
183int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700184int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700185bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800186uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800187bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800188bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800189int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800190// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600191bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700192int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700193bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700194bool SurfaceFlinger::useContextPriority;
Peiyong Lin0256f722018-08-31 15:45:10 -0700195Dataspace SurfaceFlinger::compositionDataSpace = Dataspace::V0_SRGB;
196ui::PixelFormat SurfaceFlinger::compositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700197
Kalle Raitaa099a242017-01-11 11:17:29 -0800198std::string getHwcServiceName() {
199 char value[PROPERTY_VALUE_MAX] = {};
200 property_get("debug.sf.hwc_service_name", value, "default");
201 ALOGI("Using HWComposer service: '%s'", value);
202 return std::string(value);
203}
204
205bool useTrebleTestingOverride() {
206 char value[PROPERTY_VALUE_MAX] = {};
207 property_get("debug.sf.treble_testing_override", value, "false");
208 ALOGI("Treble testing override: '%s'", value);
209 return std::string(value) == "true";
210}
211
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800212std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
213 switch(displayColorSetting) {
214 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700215 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800216 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700217 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800218 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700219 return std::string("Enhanced");
220 default:
221 return std::string("Unknown ") +
222 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800223 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800224}
225
David Sodmanbc815282017-11-05 18:57:52 -0800226SurfaceFlingerBE::SurfaceFlingerBE()
227 : mHwcServiceName(getHwcServiceName()),
228 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800229 mFrameBuckets(),
230 mTotalTime(0),
231 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800232 mComposerSequenceId(0) {
233}
234
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800235SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800236 : BnSurfaceComposer(),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700237 mTransactionPending(false),
238 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700239 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700240 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800241 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700242 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800243 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800244 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800245 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800246 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800247 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700248 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700249 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700250 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700251 mDebugInTransaction(0),
252 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700253 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700254 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700255 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800256 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800257 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800258 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700259 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800260 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800261 mCreateBufferQueue(&BufferQueue::createBufferQueue),
Lloyd Pique22098362018-09-13 11:46:49 -0700262 mCreateNativeWindowSurface(&surfaceflinger::impl::createNativeWindowSurface) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800263
264SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800265 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800266
267 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
268 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
269
270 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
271 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
272
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800273 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
274 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800275
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700276 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
277 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
278
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700279 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
280 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
281
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800282 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
283 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
284
Steven Thomas050b2c82017-03-06 11:45:16 -0800285 // Vr flinger is only enabled on Daydream ready devices.
286 useVrFlinger = getBool< ISurfaceFlingerConfigs,
287 &ISurfaceFlingerConfigs::useVrFlinger>(false);
288
Fabien Sanglard1971b632017-03-10 14:50:03 -0800289 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
290 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
291
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600292 hasWideColorDisplay =
293 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700294 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700295 getBool<V1_2::ISurfaceFlingerConfigs,
296 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
297
298 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
299 if (surfaceFlingerConfigsServiceV1_2) {
300 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
301 [&](Dataspace tmpDataSpace, ui::PixelFormat tmpPixelFormat) {
302 compositionDataSpace = tmpDataSpace;
303 compositionPixelFormat = tmpPixelFormat;
304 });
305 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600306
Peiyong Linb3839ad2018-09-05 15:37:19 -0700307 useContextPriority = getBool<ISurfaceFlingerConfigs,
308 &ISurfaceFlingerConfigs::useContextPriority>(true);
309
Iris Chang7501ed62018-04-30 14:45:42 +0800310 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700311 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
312 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800313 V1_1::DisplayOrientation::ORIENTATION_0);
314
315 switch (primaryDisplayOrientation) {
316 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700317 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800318 break;
319 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700320 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800321 break;
322 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700323 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800324 break;
325 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700326 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800327 break;
328 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700329 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800330
Lloyd Pique41be5d22018-06-21 13:11:48 -0700331 // Note: We create a local temporary with the real DispSync implementation
332 // type temporarily so we can initialize it with the configured values,
333 // before storing it for more generic use using the interface type.
334 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
335 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
336 SurfaceFlinger::dispSyncPresentTimeOffset);
337 mPrimaryDispSync = std::move(primaryDispSync);
Saurabh Shahf4174532017-07-13 10:45:07 -0700338
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800339 // debugging stuff...
340 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700341
Mathias Agopianb4b17302013-03-20 18:36:41 -0700342 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700343 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700344
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800345 property_get("debug.sf.showupdates", value, "0");
346 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700347
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700348 property_get("debug.sf.ddms", value, "0");
349 mDebugDDMS = atoi(value);
350 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700351 if (!startDdmConnection()) {
352 // start failed, and DDMS debugging not enabled
353 mDebugDDMS = 0;
354 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700355 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700356 ALOGI_IF(mDebugRegion, "showupdates enabled");
357 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700358
359 property_get("debug.sf.disable_backpressure", value, "0");
360 mPropagateBackpressure = !atoi(value);
361 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700362
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800363 property_get("debug.sf.enable_hwc_vds", value, "0");
364 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800365 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800366
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800367 property_get("ro.sf.disable_triple_buffer", value, "1");
368 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800369 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700370
Yiwei Zhang243b3782018-05-15 17:40:04 -0700371 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700372 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
373 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
374
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200375 property_get("debug.sf.early_phase_offset_ns", value, "-1");
376 const int earlySfOffsetNs = atoi(value);
377
378 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
379 const int earlyGlSfOffsetNs = atoi(value);
380
381 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
382 const int earlyAppOffsetNs = atoi(value);
383
384 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
385 const int earlyGlAppOffsetNs = atoi(value);
386
Ana Krulec98b5b242018-08-10 15:03:23 -0700387 property_get("debug.sf.use_scheduler", value, "0");
388 mUseScheduler = atoi(value);
389
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200390 const VSyncModulator::Offsets earlyOffsets =
391 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
392 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
393 const VSyncModulator::Offsets earlyGlOffsets =
394 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
395 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
396 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
397 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700398
Romain Guy11d63f42017-07-20 12:47:14 -0700399 // We should be reading 'persist.sys.sf.color_saturation' here
400 // but since /data may be encrypted, we need to wait until after vold
401 // comes online to attempt to read the property. The property is
402 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800403
404 if (useTrebleTestingOverride()) {
405 // Without the override SurfaceFlinger cannot connect to HIDL
406 // services that are not listed in the manifests. Considered
407 // deriving the setting from the set service name, but it
408 // would be brittle if the name that's not 'default' is used
409 // for production purposes later on.
410 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
411 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800412}
413
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800414void SurfaceFlinger::onFirstRef()
415{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800416 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800417}
418
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800419SurfaceFlinger::~SurfaceFlinger()
420{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800421}
422
Dan Stozac7014012014-02-14 15:03:43 -0800423void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800424{
425 // the window manager died on us. prepare its eulogy.
426
Andy McFadden13a082e2012-08-24 10:16:42 -0700427 // restore initial conditions (default device unblank, etc)
428 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800429
430 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700431 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800432}
433
Robert Carr1db73f62016-12-21 12:58:51 -0800434static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700435 status_t err = client->initCheck();
436 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800437 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800438 }
Robert Carr1db73f62016-12-21 12:58:51 -0800439 return nullptr;
440}
441
442sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
443 return initClient(new Client(this));
444}
445
446sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
447 const sp<IGraphicBufferProducer>& gbp) {
448 if (authenticateSurfaceTexture(gbp) == false) {
449 return nullptr;
450 }
451 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
452 if (layer == nullptr) {
453 return nullptr;
454 }
455
456 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800457}
458
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700459sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
460 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700461{
462 class DisplayToken : public BBinder {
463 sp<SurfaceFlinger> flinger;
464 virtual ~DisplayToken() {
465 // no more references, this display must be terminated
466 Mutex::Autolock _l(flinger->mStateLock);
467 flinger->mCurrentState.displays.removeItem(this);
468 flinger->setTransactionFlags(eDisplayTransactionNeeded);
469 }
470 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700471 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700472 : flinger(flinger) {
473 }
474 };
475
476 sp<BBinder> token = new DisplayToken(this);
477
478 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700479 DisplayDeviceState info;
480 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700481 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700482 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700483 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800484 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700485 return token;
486}
487
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700488void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700489 Mutex::Autolock _l(mStateLock);
490
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700491 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700492 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700493 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700494 return;
495 }
496
497 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700498 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700499 ALOGE("destroyDisplay called for non-virtual display");
500 return;
501 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700502 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700503 mCurrentState.displays.removeItemsAt(idx);
504 setTransactionFlags(eDisplayTransactionNeeded);
505}
506
Mathias Agopiane57f2922012-08-09 16:29:12 -0700507sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700508 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700509 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800510 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700511 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700512 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700513}
514
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800515void SurfaceFlinger::bootFinished()
516{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700517 if (mStartPropertySetThread->join() != NO_ERROR) {
518 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800519 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800520 const nsecs_t now = systemTime();
521 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000522 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700523
524 // wait patiently for the window manager death
525 const String16 name("window");
526 sp<IBinder> window(defaultServiceManager()->getService(name));
527 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700528 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700529 }
530
Steven Thomas050b2c82017-03-06 11:45:16 -0800531 if (mVrFlinger) {
532 mVrFlinger->OnBootFinished();
533 }
534
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700535 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700536 // formerly we would just kill the process, but we now ask it to exit so it
537 // can choose where to stop the animation.
538 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700539
540 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
541 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
542 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700543
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800544 postMessageAsync(new LambdaMessage([this] {
545 readPersistentProperties();
546 mBootStage = BootStage::FINISHED;
547 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800548}
549
Dan Stoza436ccf32018-06-21 12:10:12 -0700550uint32_t SurfaceFlinger::getNewTexture() {
551 {
552 std::lock_guard lock(mTexturePoolMutex);
553 if (!mTexturePool.empty()) {
554 uint32_t name = mTexturePool.back();
555 mTexturePool.pop_back();
556 ATRACE_INT("TexturePoolSize", mTexturePool.size());
557 return name;
558 }
559
560 // The pool was too small, so increase it for the future
561 ++mTexturePoolSize;
562 }
563
564 // The pool was empty, so we need to get a new texture name directly using a
565 // blocking call to the main thread
566 uint32_t name = 0;
567 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
568 return name;
569}
570
Mathias Agopian3f844832013-08-07 21:24:32 -0700571void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700572 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700573}
574
Wei Wangf9b05ee2017-07-19 20:59:39 -0700575// Do not call property_set on main thread which will be blocked by init
576// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700577void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700578 ALOGI( "SurfaceFlinger's main thread ready to run. "
579 "Initializing graphics H/W...");
580
Thierry Strudel2924d012017-08-14 15:19:37 -0700581 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900582
Steven Thomasb02664d2017-07-26 18:48:28 -0700583 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800584
Steven Thomasb02664d2017-07-26 18:48:28 -0700585 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700586 if (mUseScheduler) {
Ana Krulece588e312018-09-18 12:32:24 -0700587 mScheduler = std::make_unique<Scheduler>(
588 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Ana Krulec98b5b242018-08-10 15:03:23 -0700589 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700590 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700591 [this] { resyncWithRateLimit(); },
592 impl::EventThread::InterceptVSyncsCallback());
593 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700594 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700595 [this] { resyncWithRateLimit(); },
596 [this](nsecs_t timestamp) {
597 mInterceptor->saveVSyncEvent(timestamp);
598 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800599
Ana Krulec98b5b242018-08-10 15:03:23 -0700600 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700601 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
602 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700603 } else {
604 mEventThreadSource =
605 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
606 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
607 mEventThread =
608 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
609 [this] { resyncWithRateLimit(); },
610 impl::EventThread::InterceptVSyncsCallback(),
611 "appEventThread");
612 mSfEventThreadSource =
613 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
614 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
615
616 mSFEventThread =
617 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
618 [this] { resyncWithRateLimit(); },
619 [this](nsecs_t timestamp) {
620 mInterceptor->saveVSyncEvent(timestamp);
621 },
622 "sfEventThread");
623 mEventQueue->setEventThread(mSFEventThread.get());
624 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
625 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800626
Steven Thomasb02664d2017-07-26 18:48:28 -0700627 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700628 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700629 renderEngineFeature |= (useColorManagement ?
630 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700631 renderEngineFeature |= (useContextPriority ?
632 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700633
634 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
635 getBE().mRenderEngine =
Peiyong Linf11f39b2018-09-05 14:37:41 -0700636 renderengine::RenderEngine::create(static_cast<int32_t>(compositionPixelFormat),
637 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800638 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700639
640 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
641 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800642 getBE().mHwc.reset(
643 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700644 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800645 // Process any initial hotplug and resulting display changes.
646 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700647 const auto display = getDefaultDisplayDeviceLocked();
648 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
649 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
650 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800651
Lloyd Piquefcd86612017-12-14 17:15:36 -0800652 // make the default display GLContext current so that we can create textures
653 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700654 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800655
Steven Thomas050b2c82017-03-06 11:45:16 -0800656 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700657 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700658 // This callback is called from the vr flinger dispatch thread. We
659 // need to call signalTransaction(), which requires holding
660 // mStateLock when we're not on the main thread. Acquiring
661 // mStateLock from the vr flinger dispatch thread might trigger a
662 // deadlock in surface flinger (see b/66916578), so post a message
663 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700664 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700665 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
666 mVrFlingerRequestsDisplay = requestDisplay;
667 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700668 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800669 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700670 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
671 getHwComposer()
672 .getHwcDisplayId(display->getId())
673 .value_or(0),
674 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800675 if (!mVrFlinger) {
676 ALOGE("Failed to start vrflinger");
677 }
678 }
679
Lloyd Pique379adc12018-01-22 17:31:47 -0800680 mEventControlThread = std::make_unique<impl::EventControlThread>(
681 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700682
Mathias Agopian92a979a2012-08-02 18:32:23 -0700683 // initialize our drawing state
684 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700685
Andy McFadden13a082e2012-08-24 10:16:42 -0700686 // set initial conditions (e.g. unblank default device)
687 initializeDisplays();
688
David Sodmanbc815282017-11-05 18:57:52 -0800689 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700690
Wei Wangf9b05ee2017-07-19 20:59:39 -0700691 // Inform native graphics APIs whether the present timestamp is supported:
692 if (getHwComposer().hasCapability(
693 HWC2::Capability::PresentFenceIsNotReliable)) {
694 mStartPropertySetThread = new StartPropertySetThread(false);
695 } else {
696 mStartPropertySetThread = new StartPropertySetThread(true);
697 }
698
699 if (mStartPropertySetThread->Start() != NO_ERROR) {
700 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800701 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800702
Chia-I Wud49d6692018-06-27 07:17:41 +0800703 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
704 // is used to saturate legacy sRGB content. However, to make sure the same color under
705 // Display P3 will be saturated to the same color, we intentionally break the API spec
706 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
707 // such saturation matrix on Display P3 is understood fully, the API should always return
708 // identify matrix.
709 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
710 Dataspace::SRGB_LINEAR);
711
712 // we will apply this on Display P3.
713 if (mEnhancedSaturationMatrix != mat4()) {
714 ColorSpace srgb(ColorSpace::sRGB());
715 ColorSpace displayP3(ColorSpace::DisplayP3());
716 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
717 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
718 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
719 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800720
Dan Stoza9e56aa02015-11-02 13:00:03 -0800721 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700722}
723
Romain Guy11d63f42017-07-20 12:47:14 -0700724void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700725 Mutex::Autolock _l(mStateLock);
726
Romain Guy11d63f42017-07-20 12:47:14 -0700727 char value[PROPERTY_VALUE_MAX];
728
729 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800730 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700731 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800732 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100733
734 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700735 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700736}
737
Mathias Agopiana67e4182012-06-19 17:26:12 -0700738void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800739 // Start boot animation service by setting a property mailbox
740 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700741 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800742 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700743 if (mStartPropertySetThread->join() != NO_ERROR) {
744 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800745 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700746}
747
Mathias Agopian875d8e12013-06-07 15:35:48 -0700748size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800749 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700750}
751
Mathias Agopian875d8e12013-06-07 15:35:48 -0700752size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800753 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700754}
755
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800756// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800757
Jamie Gennis582270d2011-08-17 18:19:00 -0700758bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800759 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800760 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800761 return authenticateSurfaceTextureLocked(bufferProducer);
762}
763
764bool SurfaceFlinger::authenticateSurfaceTextureLocked(
765 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800766 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800767 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800768}
769
Brian Anderson6b376712017-04-04 10:51:39 -0700770status_t SurfaceFlinger::getSupportedFrameTimestamps(
771 std::vector<FrameEvent>* outSupported) const {
772 *outSupported = {
773 FrameEvent::REQUESTED_PRESENT,
774 FrameEvent::ACQUIRE,
775 FrameEvent::LATCH,
776 FrameEvent::FIRST_REFRESH_START,
777 FrameEvent::LAST_REFRESH_START,
778 FrameEvent::GPU_COMPOSITION_DONE,
779 FrameEvent::DEQUEUE_READY,
780 FrameEvent::RELEASE,
781 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700782 ConditionalLock _l(mStateLock,
783 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700784 if (!getHwComposer().hasCapability(
785 HWC2::Capability::PresentFenceIsNotReliable)) {
786 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
787 }
788 return NO_ERROR;
789}
790
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700791status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
792 Vector<DisplayInfo>* configs) {
793 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700794 return BAD_VALUE;
795 }
796
Jesse Hall692c7232012-11-08 15:41:56 -0800797 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700798 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
799 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700800 type = i;
801 break;
802 }
803 }
804
805 if (type < 0) {
806 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700807 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700808
Mathias Agopian8b736f12012-08-13 17:54:26 -0700809 // TODO: Not sure if display density should handled by SF any longer
810 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700811 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700812 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700813 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800814 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700815 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700816 }
817 return density;
818 }
819 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700820 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700821 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700822 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700823 return getDensityFromProperty("ro.sf.lcd_density"); }
824 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700825
Dan Stoza7f7da322014-05-02 15:26:25 -0700826 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700827
Steven Thomas6d8110b2017-08-31 18:24:21 -0700828 ConditionalLock _l(mStateLock,
829 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800830 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700831 DisplayInfo info = DisplayInfo();
832
Dan Stoza9e56aa02015-11-02 13:00:03 -0800833 float xdpi = hwConfig->getDpiX();
834 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700835
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700836 info.w = hwConfig->getWidth();
837 info.h = hwConfig->getHeight();
838 // Default display viewport to display width and height
839 info.viewportW = info.w;
840 info.viewportH = info.h;
841
Dan Stoza7f7da322014-05-02 15:26:25 -0700842 if (type == DisplayDevice::DISPLAY_PRIMARY) {
843 // The density of the device is provided by a build property
844 float density = Density::getBuildDensity() / 160.0f;
845 if (density == 0) {
846 // the build doesn't provide a density -- this is wrong!
847 // use xdpi instead
848 ALOGE("ro.sf.lcd_density must be defined as a build property");
849 density = xdpi / 160.0f;
850 }
851 if (Density::getEmuDensity()) {
852 // if "qemu.sf.lcd_density" is specified, it overrides everything
853 xdpi = ydpi = density = Density::getEmuDensity();
854 density /= 160.0f;
855 }
856 info.density = density;
857
858 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700859 const auto display = getDefaultDisplayDeviceLocked();
860 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700861
862 // This is for screenrecord
863 const Rect viewport = display->getViewport();
864 if (viewport.isValid()) {
865 info.viewportW = uint32_t(viewport.getWidth());
866 info.viewportH = uint32_t(viewport.getHeight());
867 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700868 } else {
869 // TODO: where should this value come from?
870 static const int TV_DENSITY = 213;
871 info.density = TV_DENSITY / 160.0f;
872 info.orientation = 0;
873 }
874
Dan Stoza7f7da322014-05-02 15:26:25 -0700875 info.xdpi = xdpi;
876 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800877 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900878 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800879
Andy McFadden91b2ca82014-06-13 14:04:23 -0700880 // This is how far in advance a buffer must be queued for
881 // presentation at a given time. If you want a buffer to appear
882 // on the screen at time N, you must submit the buffer before
883 // (N - presentationDeadline).
884 //
885 // Normally it's one full refresh period (to give SF a chance to
886 // latch the buffer), but this can be reduced by configuring a
887 // DispSync offset. Any additional delays introduced by the hardware
888 // composer or panel must be accounted for here.
889 //
890 // We add an additional 1ms to allow for processing time and
891 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800892 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800893 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700894
895 // All non-virtual displays are currently considered secure.
896 info.secure = true;
897
Iris Chang7501ed62018-04-30 14:45:42 +0800898 if (type == DisplayDevice::DISPLAY_PRIMARY &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700899 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800900 std::swap(info.w, info.h);
901 }
902
Michael Wright28f24d02016-07-12 13:30:53 -0700903 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700904 }
905
Dan Stoza7f7da322014-05-02 15:26:25 -0700906 return NO_ERROR;
907}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700908
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700909status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
910 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700911 return BAD_VALUE;
912 }
913
Ana Krulece588e312018-09-18 12:32:24 -0700914 // FIXME for now we always return stats for the primary display.
915 if (mUseScheduler) {
916 mScheduler->getDisplayStatInfo(stats);
917 } else {
918 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
919 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
920 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700921 return NO_ERROR;
922}
923
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700924int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
925 const auto display = getDisplayDevice(displayToken);
926 if (!display) {
927 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800928 return BAD_VALUE;
929 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700930
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700931 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700932}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700933
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700934void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
935 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700936 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700937 return;
938 }
939
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700940 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700941 ALOGW("Trying to set config for virtual display");
942 return;
943 }
944
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700945 display->setActiveConfig(mode);
946 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700947}
948
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700949status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700950 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700951 Vector<DisplayInfo> configs;
952 getDisplayConfigs(displayToken, &configs);
953 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
954 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
955 configs.size());
956 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700957 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700958 const auto display = getDisplayDevice(displayToken);
959 if (!display) {
960 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
961 displayToken.get());
962 } else if (display->isVirtual()) {
963 ALOGW("Attempt to set active config %d for virtual display", mode);
964 } else {
965 setActiveConfigInternal(display, mode);
966 }
967 }));
968
Mathias Agopian888c8222012-08-04 21:10:38 -0700969 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700970}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700971status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
972 Vector<ColorMode>* outColorModes) {
973 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700974 return BAD_VALUE;
975 }
976
Michael Wright28f24d02016-07-12 13:30:53 -0700977 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700978 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
979 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700980 type = i;
981 break;
982 }
983 }
984
985 if (type < 0) {
986 return type;
987 }
988
Peiyong Lina52f0292018-03-14 17:26:31 -0700989 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700990 {
991 ConditionalLock _l(mStateLock,
992 std::this_thread::get_id() != mMainThreadId);
993 modes = getHwComposer().getColorModes(type);
994 }
Michael Wright28f24d02016-07-12 13:30:53 -0700995 outColorModes->clear();
996 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
997
998 return NO_ERROR;
999}
1000
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001001ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1002 if (const auto display = getDisplayDevice(displayToken)) {
1003 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001004 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001005 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001006}
1007
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001008void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1009 Dataspace dataSpace, RenderIntent renderIntent) {
1010 ColorMode currentMode = display->getActiveColorMode();
1011 Dataspace currentDataSpace = display->getCompositionDataSpace();
1012 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001013
Peiyong Lin38e9a562018-04-10 16:24:20 -07001014 if (mode == currentMode && dataSpace == currentDataSpace &&
1015 renderIntent == currentRenderIntent) {
1016 return;
1017 }
1018
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001019 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001020 ALOGW("Trying to set config for virtual display");
1021 return;
1022 }
1023
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001024 display->setActiveColorMode(mode);
1025 display->setCompositionDataSpace(dataSpace);
1026 display->setActiveRenderIntent(renderIntent);
1027 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001028
1029 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001030 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1031 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001032}
1033
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001034status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001035 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001036 Vector<ColorMode> modes;
1037 getDisplayColorModes(displayToken, &modes);
1038 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1039 if (mode < ColorMode::NATIVE || !exists) {
1040 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1041 decodeColorMode(mode).c_str(), mode, displayToken.get());
1042 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001043 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001044 const auto display = getDisplayDevice(displayToken);
1045 if (!display) {
1046 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1047 decodeColorMode(mode).c_str(), mode, displayToken.get());
1048 } else if (display->isVirtual()) {
1049 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1050 decodeColorMode(mode).c_str(), mode);
1051 } else {
1052 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1053 RenderIntent::COLORIMETRIC);
1054 }
1055 }));
1056
Michael Wright28f24d02016-07-12 13:30:53 -07001057 return NO_ERROR;
1058}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001059
Svetoslavd85084b2014-03-20 10:28:31 -07001060status_t SurfaceFlinger::clearAnimationFrameStats() {
1061 Mutex::Autolock _l(mStateLock);
1062 mAnimFrameTracker.clearStats();
1063 return NO_ERROR;
1064}
1065
1066status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1067 Mutex::Autolock _l(mStateLock);
1068 mAnimFrameTracker.getStats(outStats);
1069 return NO_ERROR;
1070}
1071
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001072status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1073 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001074 Mutex::Autolock _l(mStateLock);
1075
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001076 const auto display = getDisplayDeviceLocked(displayToken);
1077 if (!display) {
1078 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001079 return BAD_VALUE;
1080 }
1081
Peiyong Linfb069302018-04-25 14:34:31 -07001082 // At this point the DisplayDeivce should already be set up,
1083 // meaning the luminance information is already queried from
1084 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001085 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001086 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1087 capabilities.getDesiredMaxLuminance(),
1088 capabilities.getDesiredMaxAverageLuminance(),
1089 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001090
1091 return NO_ERROR;
1092}
1093
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001094status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001095 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001096 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001097
Chia-I Wu90f669f2017-10-05 14:24:41 -07001098 if (mInjectVSyncs == enable) {
1099 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001100 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001101
Ana Krulec98b5b242018-08-10 15:03:23 -07001102 // TODO(akrulec): Part of the Injector should be refactored, so that it
1103 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001104 if (enable) {
1105 ALOGV("VSync Injections enabled");
1106 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001107 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001108 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001109 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001110 impl::EventThread::InterceptVSyncsCallback(),
1111 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001112 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001113 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001114 } else {
1115 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001116 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001117 }
1118
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001119 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001120 }));
1121
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001122 return NO_ERROR;
1123}
1124
1125status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001126 Mutex::Autolock _l(mStateLock);
1127
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001128 if (!mInjectVSyncs) {
1129 ALOGE("VSync Injections not enabled");
1130 return BAD_VALUE;
1131 }
1132 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1133 ALOGV("Injecting VSync inside SurfaceFlinger");
1134 mVSyncInjector->onInjectSyncEvent(when);
1135 }
1136 return NO_ERROR;
1137}
1138
Lloyd Pique755e3192018-01-31 16:46:15 -08001139status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1140 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001141 // Try to acquire a lock for 1s, fail gracefully
1142 const status_t err = mStateLock.timedLock(s2ns(1));
1143 const bool locked = (err == NO_ERROR);
1144 if (!locked) {
1145 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1146 return TIMED_OUT;
1147 }
1148
1149 outLayers->clear();
1150 mCurrentState.traverseInZOrder([&](Layer* layer) {
1151 outLayers->push_back(layer->getLayerDebugInfo());
1152 });
1153
1154 mStateLock.unlock();
1155 return NO_ERROR;
1156}
1157
Peiyong Lin0256f722018-08-31 15:45:10 -07001158status_t SurfaceFlinger::getCompositionPreference(Dataspace* outDataSpace,
1159 ui::PixelFormat* outPixelFormat) const {
1160 *outDataSpace = compositionDataSpace;
1161 *outPixelFormat = compositionPixelFormat;
1162 return NO_ERROR;
1163}
1164
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001165// ----------------------------------------------------------------------------
1166
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001167sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1168 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001169 if (mUseScheduler) {
1170 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1171 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1172 } else {
1173 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1174 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001175 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001176 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1177 return mSFEventThread->createEventConnection();
1178 } else {
1179 return mEventThread->createEventConnection();
1180 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001181 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001182}
1183
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001184// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001185
1186void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001187 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001188}
1189
1190void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001191 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001192}
1193
1194void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001195 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001196}
1197
1198void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001199 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001200 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001201}
1202
1203status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001204 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001205 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001206}
1207
1208status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001209 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001210 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001211 if (res == NO_ERROR) {
1212 msg->wait();
1213 }
1214 return res;
1215}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001216
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001217void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001218 do {
1219 waitForEvent();
1220 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001221}
1222
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001223void SurfaceFlinger::enableHardwareVsync() {
1224 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001225 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001226 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001227 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001228 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001229 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001230}
1231
Jesse Hall948fe0c2013-10-14 12:56:09 -07001232void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001233 Mutex::Autolock _l(mHWVsyncLock);
1234
Jesse Hall948fe0c2013-10-14 12:56:09 -07001235 if (makeAvailable) {
1236 mHWVsyncAvailable = true;
1237 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001238 // Hardware vsync is not currently available, so abort the resync
1239 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001240 return;
1241 }
1242
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001243 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1244 if (!getHwComposer().isConnected(displayId)) {
1245 return;
1246 }
1247
1248 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001249 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001250
Ana Krulece588e312018-09-18 12:32:24 -07001251 if (mUseScheduler) {
1252 mScheduler->setVsyncPeriod(period);
1253 } else {
1254 mPrimaryDispSync->reset();
1255 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001256
Ana Krulece588e312018-09-18 12:32:24 -07001257 if (!mPrimaryHWVsyncEnabled) {
1258 mPrimaryDispSync->beginResync();
1259 mEventControlThread->setVsyncEnabled(true);
1260 mPrimaryHWVsyncEnabled = true;
1261 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001262 }
1263}
1264
Jesse Hall948fe0c2013-10-14 12:56:09 -07001265void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001266 Mutex::Autolock _l(mHWVsyncLock);
1267 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001268 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001269 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001270 mPrimaryHWVsyncEnabled = false;
1271 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001272 if (makeUnavailable) {
1273 mHWVsyncAvailable = false;
1274 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001275}
1276
Tim Murray4a4e4a22016-04-19 16:29:23 +00001277void SurfaceFlinger::resyncWithRateLimit() {
1278 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001279
1280 // No explicit locking is needed here since EventThread holds a lock while calling this method
1281 static nsecs_t sLastResyncAttempted = 0;
1282 const nsecs_t now = systemTime();
1283 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001284 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001285 }
Dan Stoza57164302017-05-08 14:03:54 -07001286 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001287}
1288
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001289void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1290 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001291 ATRACE_NAME("SF onVsync");
1292
Steven Thomas3cfac282017-02-06 12:29:30 -08001293 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001294 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001295 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001296 return;
1297 }
1298
1299 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001300 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001301 return;
1302 }
1303
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001304 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1305 // For now, we don't do anything with external display vsyncs.
1306 return;
1307 }
1308
Ana Krulece588e312018-09-18 12:32:24 -07001309 if (mUseScheduler) {
1310 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001311 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001312 bool needsHwVsync = false;
1313 { // Scope for the lock
1314 Mutex::Autolock _l(mHWVsyncLock);
1315 if (mPrimaryHWVsyncEnabled) {
1316 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1317 }
1318 }
1319
1320 if (needsHwVsync) {
1321 enableHardwareVsync();
1322 } else {
1323 disableHardwareVsync(false);
1324 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001325 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001326}
1327
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001328void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001329 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1330 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001331}
1332
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001333void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001334 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001335 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001336 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001337
Lloyd Piqueba04e622017-12-14 17:11:26 -08001338 // Ignore events that do not have the right sequenceId.
1339 if (sequenceId != getBE().mComposerSequenceId) {
1340 return;
1341 }
1342
Steven Thomasb02664d2017-07-26 18:48:28 -07001343 // Only lock if we're not on the main thread. This function is normally
1344 // called on a hwbinder thread, but for the primary display it's called on
1345 // the main thread with the state lock already held, so don't attempt to
1346 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001347 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001348
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001349 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001350
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001351 if (std::this_thread::get_id() == mMainThreadId) {
1352 // Process all pending hot plug events immediately if we are on the main thread.
1353 processDisplayHotplugEventsLocked();
1354 }
1355
Lloyd Piqueba04e622017-12-14 17:11:26 -08001356 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001357}
1358
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001359void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001360 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001361 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001362 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001363 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001364 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001365}
1366
Dan Stoza9e56aa02015-11-02 13:00:03 -08001367void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001368 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001369 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001370 getHwComposer().setVsyncEnabled(disp,
1371 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001372}
1373
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001374// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001375void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001376 if (mUseScheduler) {
1377 mScheduler->disableHardwareVsync(true);
1378 } else {
1379 disableHardwareVsync(true);
1380 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001381 // Clear the drawing state so that the logic inside of
1382 // handleTransactionLocked will fire. It will determine the delta between
1383 // mCurrentState and mDrawingState and re-apply all changes when we make the
1384 // transition.
1385 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001386 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001387 mDisplays.clear();
1388}
1389
Steven Thomas050b2c82017-03-06 11:45:16 -08001390void SurfaceFlinger::updateVrFlinger() {
1391 if (!mVrFlinger)
1392 return;
1393 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001394 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001395 return;
1396 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001397
David Sodman105b7dc2017-11-04 20:28:14 -07001398 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001399 ALOGE("Vr flinger is only supported for remote hardware composer"
1400 " service connections. Ignoring request to transition to vr"
1401 " flinger.");
1402 mVrFlingerRequestsDisplay = false;
1403 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001404 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001405
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001406 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001407
Steven Thomas0123ac62018-07-12 11:32:34 -07001408 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001409 LOG_ALWAYS_FATAL_IF(!display);
1410 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001411 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1412 // called below. Clear the reference now so we don't accidentally use it
1413 // later.
1414 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001415
Steven Thomasb02664d2017-07-26 18:48:28 -07001416 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001417 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001418 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001419
Steven Thomasb02664d2017-07-26 18:48:28 -07001420 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001421 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001422 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1423 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001424 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001425
David Sodman105b7dc2017-11-04 20:28:14 -07001426 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1427 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001428
1429 if (vrFlingerRequestsDisplay) {
1430 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001431 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001432
1433 mVisibleRegionsDirty = true;
1434 invalidateHwcGeometry();
1435
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001436 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001437 display = getDefaultDisplayDeviceLocked();
1438 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001439 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001440
Steven Thomasb02664d2017-07-26 18:48:28 -07001441 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001442 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001443 const nsecs_t period = activeConfig->getVsyncPeriod();
1444 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001445
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001446 // The present fences returned from vr_hwc are not an accurate
1447 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001448 if (mUseScheduler) {
1449 mScheduler->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() || !hasSyncFramework);
1450 } else {
1451 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1452 !hasSyncFramework);
1453 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001454
Steven Thomasb02664d2017-07-26 18:48:28 -07001455 // Use phase of 0 since phase is not known.
1456 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001457 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1458 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001459
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001460 resyncToHardwareVsync(false);
1461
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001462 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001463 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001464}
1465
Mathias Agopian4fec8732012-06-29 14:12:52 -07001466void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001467 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001468 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001469 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001470 bool frameMissed = !mHadClientComposition &&
1471 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001472 (mPreviousPresentFence->getSignalTime() ==
1473 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001474 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001475 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001476 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001477 mTimeStats.incrementMissedFrames();
1478 if (mPropagateBackpressure) {
1479 signalLayerUpdate();
1480 break;
1481 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001482 }
Dan Stoza50182882016-07-08 12:02:20 -07001483
Steven Thomas050b2c82017-03-06 11:45:16 -08001484 // Now that we're going to make it to the handleMessageTransaction()
1485 // call below it's safe to call updateVrFlinger(), which will
1486 // potentially trigger a display handoff.
1487 updateVrFlinger();
1488
Dan Stoza6b9454d2014-11-07 16:00:59 -08001489 bool refreshNeeded = handleMessageTransaction();
1490 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001491 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001492 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001493 // Signal a refresh if a transaction modified the window state,
1494 // a new buffer was latched, or if HWC has requested a full
1495 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001496 signalRefresh();
1497 }
1498 break;
1499 }
1500 case MessageQueue::REFRESH: {
1501 handleMessageRefresh();
1502 break;
1503 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001504 }
1505}
1506
Dan Stoza6b9454d2014-11-07 16:00:59 -08001507bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001508 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001509 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001510 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001511 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001512 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001513 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001514}
1515
Mathias Agopian4fec8732012-06-29 14:12:52 -07001516void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001517 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001518
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001519 mRefreshPending = false;
1520
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001521 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001522 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001523 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001524 calculateWorkingSet();
David Sodman10a41ff2018-08-05 12:14:17 -07001525
David Sodmanfa9b2af2017-12-24 13:28:59 -08001526 for (const auto& [token, display] : mDisplays) {
David Sodman10a41ff2018-08-05 12:14:17 -07001527 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001528 beginFrame(display);
David Sodman10a41ff2018-08-05 12:14:17 -07001529 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
1530 setUpHWComposer(compositionInfo);
1531 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001532 prepareFrame(display);
1533 doDebugFlashRegions(display, repaintEverything);
1534 doComposition(display, repaintEverything);
1535 }
1536
Adrian Roos1e1a1282017-11-01 19:05:31 +01001537 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001538 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001539
1540 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001541 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001542
Dan Stozabfbffeb2016-07-21 14:49:33 -07001543 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001544 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001545 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001546 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001547 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001548
Alec Mouri86770e52018-09-24 22:40:58 +00001549 // Setup RenderEngine sync fences if native sync is supported.
1550 if (getBE().mRenderEngine->useNativeFenceSync()) {
1551 if (mHadClientComposition) {
1552 base::unique_fd flushFence(getRenderEngine().flush());
1553 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1554 getBE().flushFence = new Fence(std::move(flushFence));
1555 } else {
1556 // Cleanup for hygiene.
1557 getBE().flushFence = Fence::NO_FENCE;
1558 }
1559 }
1560
Jorim Jaggi90535212018-05-23 23:44:06 +02001561 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001562
David Sodman7e4ae112018-02-09 15:02:28 -08001563 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001564 for (const auto& [token, display] : mDisplays) {
1565 const auto displayId = display->getId();
David Sodman7e4ae112018-02-09 15:02:28 -08001566 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[displayId]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001567 compositionInfo.hwc.hwcLayer = nullptr;
1568 }
David Sodmanba340492018-08-05 21:51:33 -07001569 }
David Sodman7e4ae112018-02-09 15:02:28 -08001570
1571 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001572}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001573
David Sodmanfa9b2af2017-12-24 13:28:59 -08001574
1575bool SurfaceFlinger::handleMessageInvalidate() {
1576 ATRACE_CALL();
1577 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001578}
1579
David Sodman79bba0e2018-08-05 18:07:49 -07001580void SurfaceFlinger::calculateWorkingSet() {
1581 ATRACE_CALL();
1582 ALOGV(__FUNCTION__);
1583
David Sodman79bba0e2018-08-05 18:07:49 -07001584 // build the h/w work list
1585 if (CC_UNLIKELY(mGeometryInvalid)) {
1586 mGeometryInvalid = false;
1587 for (const auto& [token, display] : mDisplays) {
1588 const auto displayId = display->getId();
1589 if (displayId >= 0) {
1590 const Vector<sp<Layer>>& currentLayers(
1591 display->getVisibleLayersSortedByZ());
1592 for (size_t i = 0; i < currentLayers.size(); i++) {
1593 const auto& layer = currentLayers[i];
1594
1595 if (!layer->hasHwcLayer(displayId)) {
1596 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1597 layer->forceClientComposition(displayId);
1598 continue;
1599 }
1600 }
1601
1602 layer->setGeometry(display, i);
1603 if (mDebugDisableHWC || mDebugRegion) {
1604 layer->forceClientComposition(displayId);
1605 }
1606 }
1607 }
1608 }
1609 }
1610
1611 // Set the per-frame data
1612 for (const auto& [token, display] : mDisplays) {
1613 const auto displayId = display->getId();
1614 if (displayId < 0) {
1615 continue;
1616 }
1617
1618 if (mDrawingState.colorMatrixChanged) {
1619 display->setColorTransform(mDrawingState.colorMatrix);
1620 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1621 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1622 "display %d: %d", displayId, result);
1623 }
1624 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1625 if (layer->isHdrY410()) {
1626 layer->forceClientComposition(displayId);
1627 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1628 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1629 !display->hasHDR10Support()) {
1630 layer->forceClientComposition(displayId);
1631 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1632 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1633 !display->hasHLGSupport()) {
1634 layer->forceClientComposition(displayId);
1635 }
1636
Peiyong Lind3788632018-09-18 16:01:31 -07001637 // TODO(b/111562338) remove when composer 2.3 is shipped.
1638 if (layer->hasColorTransform()) {
1639 layer->forceClientComposition(displayId);
1640 }
1641
David Sodman79bba0e2018-08-05 18:07:49 -07001642 if (layer->getForceClientComposition(displayId)) {
1643 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1644 layer->setCompositionType(displayId, HWC2::Composition::Client);
1645 continue;
1646 }
1647
1648 layer->setPerFrameData(display);
1649 }
1650
Peiyong Lin13effd12018-07-24 17:01:47 -07001651 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001652 ColorMode colorMode;
1653 Dataspace dataSpace;
1654 RenderIntent renderIntent;
1655 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1656 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1657 }
1658 }
1659
1660 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001661
1662 for (const auto& [token, display] : mDisplays) {
David Sodman15fb96e2018-01-07 10:23:24 -08001663 const auto displayId = display->getId();
1664 getBE().mCompositionInfo[displayId].clear();
David Sodmanba340492018-08-05 21:51:33 -07001665 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1666 auto displayId = display->getId();
1667 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1668 if (!layer->setHwcLayer(displayId)) {
1669 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1670 }
David Sodman15fb96e2018-01-07 10:23:24 -08001671 layer->getBE().compositionInfo.hwc.displayId = displayId;
1672 getBE().mCompositionInfo[displayId].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001673 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1674 }
1675 }
David Sodman79bba0e2018-08-05 18:07:49 -07001676}
1677
David Sodmanfa9b2af2017-12-24 13:28:59 -08001678void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001679{
David Sodmanfb95bcc2017-12-22 15:45:30 -08001680 const auto displayId = display->getId();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001681 // is debugging enabled
1682 if (CC_LIKELY(!mDebugRegion))
1683 return;
1684
David Sodmanfa9b2af2017-12-24 13:28:59 -08001685 if (display->isPoweredOn()) {
1686 // transform the dirty region into this screen's coordinate space
1687 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1688 if (!dirtyRegion.isEmpty()) {
1689 // redraw the whole screen
1690 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001691
David Sodmanfa9b2af2017-12-24 13:28:59 -08001692 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001693 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001694 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001695
David Sodmanfa9b2af2017-12-24 13:28:59 -08001696 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001697 }
1698 }
1699
David Sodmanfa9b2af2017-12-24 13:28:59 -08001700 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001701
1702 if (mDebugRegion > 1) {
1703 usleep(mDebugRegion * 1000);
1704 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001705
David Sodmanfa9b2af2017-12-24 13:28:59 -08001706 if (display->isPoweredOn()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08001707 status_t result = display->prepareFrame(
1708 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001709 ALOGE_IF(result != NO_ERROR,
1710 "prepareFrame for display %d failed:"
1711 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001712 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001713 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001714}
1715
Adrian Roos1e1a1282017-11-01 19:05:31 +01001716void SurfaceFlinger::doTracing(const char* where) {
1717 ATRACE_CALL();
1718 ATRACE_NAME(where);
1719 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001720 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001721 }
1722}
1723
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001724void SurfaceFlinger::logLayerStats() {
1725 ATRACE_CALL();
1726 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001727 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001728 if (display->isPrimary()) {
1729 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001730 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001731 }
1732 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001733
1734 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001735 }
1736}
1737
David Sodman2b406362017-12-15 13:33:47 -08001738void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001739{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001740 ATRACE_CALL();
1741 ALOGV("preComposition");
1742
David Sodman2b406362017-12-15 13:33:47 -08001743 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1744
Mathias Agopiancd60f992012-08-16 16:28:27 -07001745 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001746 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001747 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001748 needExtraInvalidate = true;
1749 }
Robert Carr2047fae2016-11-28 14:09:09 -08001750 });
1751
Mathias Agopiancd60f992012-08-16 16:28:27 -07001752 if (needExtraInvalidate) {
1753 signalLayerUpdate();
1754 }
1755}
1756
Ana Krulece588e312018-09-18 12:32:24 -07001757void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1758 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001759 // Update queue of past composite+present times and determine the
1760 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001761 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001762 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001763 while (!getBE().mCompositePresentTimes.empty()) {
1764 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001765 // Cached values should have been updated before calling this method,
1766 // which helps avoid duplicate syscalls.
1767 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1768 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1769 break;
1770 }
1771 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001772 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001773 }
1774
1775 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001776 while (getBE().mCompositePresentTimes.size() > 16) {
1777 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001778 }
1779
Ana Krulece588e312018-09-18 12:32:24 -07001780 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001781}
1782
Ana Krulece588e312018-09-18 12:32:24 -07001783void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1784 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001785 // Integer division and modulo round toward 0 not -inf, so we need to
1786 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001787 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1788 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1789 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001790
Brian Andersond0010582017-03-07 13:20:31 -08001791 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1792 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001793 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001794 }
1795
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001796 // Snap the latency to a value that removes scheduling jitter from the
1797 // composition and present times, which often have >1ms of jitter.
1798 // Reducing jitter is important if an app attempts to extrapolate
1799 // something (such as user input) to an accurate diasplay time.
1800 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1801 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001802 nsecs_t bias = stats.vsyncPeriod / 2;
1803 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1804 nsecs_t snappedCompositeToPresentLatency =
1805 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001806
David Sodman99974d22017-11-28 12:04:33 -08001807 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001808 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1809 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001810 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001811}
1812
David Sodman2b406362017-12-15 13:33:47 -08001813void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001814{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001815 ATRACE_CALL();
1816 ALOGV("postComposition");
1817
Brian Anderson3546a3f2016-07-14 11:51:14 -07001818 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001819 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001820 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001821 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001822 }
1823
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001824 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001825 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001826
David Sodman73beded2017-11-15 11:56:06 -08001827 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001828 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001829 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001830 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001831 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001832 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001833 } else {
1834 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1835 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001836
David Sodman73beded2017-11-15 11:56:06 -08001837 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001838 mPreviousPresentFence =
1839 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1840 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001841 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001842
Ana Krulece588e312018-09-18 12:32:24 -07001843 DisplayStatInfo stats;
1844 if (mUseScheduler) {
1845 mScheduler->getDisplayStatInfo(&stats);
1846 } else {
1847 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1848 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
1849 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001850
David Sodman2b406362017-12-15 13:33:47 -08001851 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001852 // when we started doing work for this frame, but that should be okay
1853 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07001854 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001855 CompositorTiming compositorTiming;
1856 {
David Sodman99974d22017-11-28 12:04:33 -08001857 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1858 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001859 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001860
Robert Carr2047fae2016-11-28 14:09:09 -08001861 mDrawingState.traverseInZOrder([&](Layer* layer) {
1862 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001863 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001864 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001865 recordBufferingStats(layer->getName().string(),
1866 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001867 }
Robert Carr2047fae2016-11-28 14:09:09 -08001868 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001869
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001870 if (presentFenceTime->isValid()) {
Ana Krulece588e312018-09-18 12:32:24 -07001871 if (mUseScheduler) {
1872 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001873 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001874 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
1875 enableHardwareVsync();
1876 } else {
1877 disableHardwareVsync(false);
1878 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001879 }
1880 }
1881
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001882 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001883 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07001884 if (mUseScheduler) {
1885 mScheduler->enableHardwareVsync();
1886 } else {
1887 enableHardwareVsync();
1888 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001889 }
1890 }
1891
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001892 if (mAnimCompositionPending) {
1893 mAnimCompositionPending = false;
1894
Brian Anderson4e606e32017-03-16 15:34:57 -07001895 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001896 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001897 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001898 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001899 // The HWC doesn't support present fences, so use the refresh
1900 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001901 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001902 mAnimFrameTracker.setActualPresentTime(presentTime);
1903 }
1904 mAnimFrameTracker.advanceFrame();
1905 }
Dan Stozab90cf072015-03-05 11:05:59 -08001906
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001907 mTimeStats.incrementTotalFrames();
1908 if (mHadClientComposition) {
1909 mTimeStats.incrementClientCompositionFrames();
1910 }
1911
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001912 mTimeStats.setPresentFenceGlobal(presentFenceTime);
1913
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001914 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001915 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001916 return;
1917 }
1918
1919 nsecs_t currentTime = systemTime();
1920 if (mHasPoweredOff) {
1921 mHasPoweredOff = false;
1922 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001923 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001924 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001925 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1926 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001927 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001928 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001929 }
David Sodman4a36e932017-11-07 14:29:47 -08001930 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001931 }
David Sodman4a36e932017-11-07 14:29:47 -08001932 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001933
1934 {
1935 std::lock_guard lock(mTexturePoolMutex);
1936 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1937 if (refillCount > 0) {
1938 const size_t offset = mTexturePool.size();
1939 mTexturePool.resize(mTexturePoolSize);
1940 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1941 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1942 }
1943 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001944}
1945
1946void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001947 ATRACE_CALL();
1948 ALOGV("rebuildLayerStacks");
1949
Mathias Agopiancd60f992012-08-16 16:28:27 -07001950 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001951 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001952 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001953 mVisibleRegionsDirty = false;
1954 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001955
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001956 for (const auto& pair : mDisplays) {
1957 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001958 Region opaqueRegion;
1959 Region dirtyRegion;
1960 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001961 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001962 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001963 const Rect bounds = display->getBounds();
1964 if (display->isPoweredOn()) {
1965 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001966
Jeff Sharkey76488112017-02-27 14:15:18 -07001967 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001968 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001969 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001970 Region drawRegion(tr.transform(
1971 layer->visibleNonTransparentRegion));
1972 drawRegion.andSelf(bounds);
1973 if (!drawRegion.isEmpty()) {
1974 layersSortedByZ.add(layer);
1975 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001976 // Clear out the HWC layer if this layer was
1977 // previously visible, but no longer is
1978 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001979 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001980 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001981 // WM changes display->layerStack upon sleep/awake.
1982 // Here we make sure we delete the HWC layers even if
1983 // WM changed their layer stack.
1984 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001985 }
1986
1987 // If a layer is not going to get a release fence because
1988 // it is invisible, but it is also going to release its
1989 // old buffer, add it to the list of layers needing
1990 // fences.
1991 if (hwcLayerDestroyed) {
1992 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1993 mLayersWithQueuedFrames.cend(), layer);
1994 if (found != mLayersWithQueuedFrames.cend()) {
1995 layersNeedingFences.add(layer);
1996 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001997 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001998 });
1999 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002000 display->setVisibleLayersSortedByZ(layersSortedByZ);
2001 display->setLayersNeedingFences(layersNeedingFences);
2002 display->undefinedRegion.set(bounds);
2003 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2004 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002005 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002006 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002007}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002008
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002009// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002010// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002011// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002012// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002013// The returned HDR data space is one of
2014// - Dataspace::UNKNOWN
2015// - Dataspace::BT2020_HLG
2016// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002017Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2018 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07002019 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002020 *outHdrDataSpace = Dataspace::UNKNOWN;
2021
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002022 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002023 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002024 case Dataspace::V0_SCRGB:
2025 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002026 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002027 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002028 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002029 case Dataspace::BT2020_PQ:
2030 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002031 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002032 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002033 case Dataspace::BT2020_HLG:
2034 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002035 // When there's mixed PQ content and HLG content, we set the HDR
2036 // data space to be BT2020_PQ and convert HLG to PQ.
2037 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2038 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002039 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002040 break;
2041 default:
2042 break;
2043 }
Romain Guy54f154a2017-10-24 21:40:32 +01002044 }
2045
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002046 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002047}
2048
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002049// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002050void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2051 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002052 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2053 *outMode = ColorMode::NATIVE;
2054 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002055 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002056 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002057 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002058
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002059 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002060 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002061
Peiyong Lindfde5112018-06-05 10:58:41 -07002062 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002063 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002064 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002065 if (isHdr) {
2066 bestDataSpace = hdrDataSpace;
2067 }
2068
Chia-I Wu0d711262018-05-21 15:19:35 -07002069 RenderIntent intent;
2070 switch (mDisplayColorSetting) {
2071 case DisplayColorSetting::MANAGED:
2072 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002073 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002074 break;
2075 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002076 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002077 break;
2078 default: // vendor display color setting
2079 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2080 break;
2081 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002082
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002083 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002084}
2085
David Sodman10a41ff2018-08-05 12:14:17 -07002086void SurfaceFlinger::configureSidebandComposition(const CompositionInfo& compositionInfo) const
2087{
2088 HWC2::Error error;
2089 LOG_ALWAYS_FATAL_IF(compositionInfo.hwc.sidebandStream == nullptr,
2090 "CompositionType is sideband, but sideband stream is nullptr");
2091 error = (compositionInfo.hwc.hwcLayer)
2092 ->setSidebandStream(compositionInfo.hwc.sidebandStream->handle());
2093 if (error != HWC2::Error::None) {
2094 ALOGE("[SF] Failed to set sideband stream %p: %s (%d)",
2095 compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
2096 static_cast<int32_t>(error));
2097 }
2098}
2099
2100void SurfaceFlinger::configureHwcCommonData(const CompositionInfo& compositionInfo) const
2101{
2102 HWC2::Error error;
2103
2104 if (!compositionInfo.hwc.skipGeometry) {
2105 error = (compositionInfo.hwc.hwcLayer)->setBlendMode(compositionInfo.hwc.blendMode);
2106 ALOGE_IF(error != HWC2::Error::None,
2107 "[SF] Failed to set blend mode %s:"
2108 " %s (%d)",
2109 to_string(compositionInfo.hwc.blendMode).c_str(), to_string(error).c_str(),
2110 static_cast<int32_t>(error));
2111
2112 error = (compositionInfo.hwc.hwcLayer)->setDisplayFrame(compositionInfo.hwc.displayFrame);
2113 ALOGE_IF(error != HWC2::Error::None,
2114 "[SF] Failed to set the display frame [%d, %d, %d, %d] %s (%d)",
2115 compositionInfo.hwc.displayFrame.left,
2116 compositionInfo.hwc.displayFrame.right,
2117 compositionInfo.hwc.displayFrame.top,
2118 compositionInfo.hwc.displayFrame.bottom,
2119 to_string(error).c_str(), static_cast<int32_t>(error));
2120
2121 error = (compositionInfo.hwc.hwcLayer)->setSourceCrop(compositionInfo.hwc.sourceCrop);
2122 ALOGE_IF(error != HWC2::Error::None,
2123 "[SF] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: %s (%d)",
2124 compositionInfo.hwc.sourceCrop.left,
2125 compositionInfo.hwc.sourceCrop.right,
2126 compositionInfo.hwc.sourceCrop.top,
2127 compositionInfo.hwc.sourceCrop.bottom,
2128 to_string(error).c_str(), static_cast<int32_t>(error));
2129
2130 error = (compositionInfo.hwc.hwcLayer)->setPlaneAlpha(compositionInfo.hwc.alpha);
2131 ALOGE_IF(error != HWC2::Error::None,
2132 "[SF] Failed to set plane alpha %.3f: "
2133 "%s (%d)",
2134 compositionInfo.hwc.alpha,
2135 to_string(error).c_str(), static_cast<int32_t>(error));
2136
2137
2138 error = (compositionInfo.hwc.hwcLayer)->setZOrder(compositionInfo.hwc.z);
2139 ALOGE_IF(error != HWC2::Error::None,
2140 "[SF] Failed to set Z %u: %s (%d)",
2141 compositionInfo.hwc.z,
2142 to_string(error).c_str(), static_cast<int32_t>(error));
2143
2144 error = (compositionInfo.hwc.hwcLayer)
2145 ->setInfo(compositionInfo.hwc.type, compositionInfo.hwc.appId);
2146 ALOGE_IF(error != HWC2::Error::None,
2147 "[SF] Failed to set info (%d)",
2148 static_cast<int32_t>(error));
2149
2150 error = (compositionInfo.hwc.hwcLayer)->setTransform(compositionInfo.hwc.transform);
2151 ALOGE_IF(error != HWC2::Error::None,
2152 "[SF] Failed to set transform %s: "
2153 "%s (%d)",
2154 to_string(compositionInfo.hwc.transform).c_str(), to_string(error).c_str(),
2155 static_cast<int32_t>(error));
2156 }
2157
2158 error = (compositionInfo.hwc.hwcLayer)->setCompositionType(compositionInfo.compositionType);
2159 ALOGE_IF(error != HWC2::Error::None,
2160 "[SF] Failed to set composition type: %s (%d)",
2161 to_string(error).c_str(), static_cast<int32_t>(error));
2162
2163 error = (compositionInfo.hwc.hwcLayer)->setDataspace(compositionInfo.hwc.dataspace);
2164 ALOGE_IF(error != HWC2::Error::None,
2165 "[SF] Failed to set dataspace: %s (%d)",
2166 to_string(error).c_str(), static_cast<int32_t>(error));
2167
2168 error = (compositionInfo.hwc.hwcLayer)->setPerFrameMetadata(
2169 compositionInfo.hwc.supportedPerFrameMetadata, compositionInfo.hwc.hdrMetadata);
2170 ALOGE_IF(error != HWC2::Error::None && error != HWC2::Error::Unsupported,
2171 "[SF] Failed to set hdrMetadata: %s (%d)",
2172 to_string(error).c_str(), static_cast<int32_t>(error));
2173
2174 if (compositionInfo.compositionType == HWC2::Composition::SolidColor) {
2175 error = (compositionInfo.hwc.hwcLayer)->setColor(compositionInfo.hwc.color);
2176 ALOGE_IF(error != HWC2::Error::None,
2177 "[SF] Failed to set color: %s (%d)",
2178 to_string(error).c_str(), static_cast<int32_t>(error));
2179 }
2180
2181 error = (compositionInfo.hwc.hwcLayer)->setVisibleRegion(compositionInfo.hwc.visibleRegion);
2182 ALOGE_IF(error != HWC2::Error::None,
2183 "[SF] Failed to set visible region: %s (%d)",
2184 to_string(error).c_str(), static_cast<int32_t>(error));
2185
2186 error = (compositionInfo.hwc.hwcLayer)->setSurfaceDamage(compositionInfo.hwc.surfaceDamage);
2187 ALOGE_IF(error != HWC2::Error::None,
2188 "[SF] Failed to set surface damage: %s (%d)",
2189 to_string(error).c_str(), static_cast<int32_t>(error));
Peiyong Lind3788632018-09-18 16:01:31 -07002190
2191 error = (compositionInfo.hwc.hwcLayer)->setColorTransform(compositionInfo.hwc.colorTransform);
David Sodman10a41ff2018-08-05 12:14:17 -07002192}
2193
2194void SurfaceFlinger::configureDeviceComposition(const CompositionInfo& compositionInfo) const
2195{
2196 HWC2::Error error;
2197
2198 if (compositionInfo.hwc.fence) {
2199 error = (compositionInfo.hwc.hwcLayer)->setBuffer(compositionInfo.mBufferSlot,
2200 compositionInfo.mBuffer, compositionInfo.hwc.fence);
2201 ALOGE_IF(error != HWC2::Error::None,
2202 "[SF] Failed to set buffer: %s (%d)",
2203 to_string(error).c_str(), static_cast<int32_t>(error));
2204 }
2205}
2206
David Sodmanfa9b2af2017-12-24 13:28:59 -08002207void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002208{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002209 bool dirty = !display->getDirtyRegion(false).isEmpty();
2210 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2211 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002212
David Sodmanfa9b2af2017-12-24 13:28:59 -08002213 // If nothing has changed (!dirty), don't recompose.
2214 // If something changed, but we don't currently have any visible layers,
2215 // and didn't when we last did a composition, then skip it this time.
2216 // The second rule does two things:
2217 // - When all layers are removed from a display, we'll emit one black
2218 // frame, then nothing more until we get new layers.
2219 // - When a display is created with a private layer stack, we won't
2220 // emit any black frames until a layer is added to the layer stack.
2221 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002222
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002223 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2224 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002225 mustRecompose ? "doing" : "skipping",
2226 dirty ? "+" : "-",
2227 empty ? "+" : "-",
2228 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002229
David Sodmanfa9b2af2017-12-24 13:28:59 -08002230 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002231
David Sodmanfa9b2af2017-12-24 13:28:59 -08002232 if (mustRecompose) {
2233 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002234 }
2235}
2236
David Sodmanfa9b2af2017-12-24 13:28:59 -08002237void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002238{
David Sodmanfb95bcc2017-12-22 15:45:30 -08002239 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002240 if (!display->isPoweredOn()) {
2241 return;
David Sodman2b406362017-12-15 13:33:47 -08002242 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002243
David Sodmanfb95bcc2017-12-22 15:45:30 -08002244 status_t result = display->prepareFrame(
2245 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08002246 ALOGE_IF(result != NO_ERROR,
2247 "prepareFrame for display %d failed:"
2248 " %d (%s)",
2249 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002250}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002251
David Sodman10a41ff2018-08-05 12:14:17 -07002252void SurfaceFlinger::setUpHWComposer(const CompositionInfo& compositionInfo) {
2253 ATRACE_CALL();
2254 ALOGV("setUpHWComposer");
2255
2256 switch (compositionInfo.compositionType)
2257 {
2258 case HWC2::Composition::Invalid:
David Sodmana6d42332018-08-29 14:07:04 -07002259 break;
2260
David Sodman10a41ff2018-08-05 12:14:17 -07002261 case HWC2::Composition::Client:
David Sodmana6d42332018-08-29 14:07:04 -07002262 if (compositionInfo.hwc.hwcLayer) {
2263 auto error = (compositionInfo.hwc.hwcLayer)->
2264 setCompositionType(compositionInfo.compositionType);
2265 ALOGE_IF(error != HWC2::Error::None,
2266 "[SF] Failed to set composition type: %s (%d)",
2267 to_string(error).c_str(), static_cast<int32_t>(error));
2268 }
David Sodman10a41ff2018-08-05 12:14:17 -07002269 break;
2270
2271 case HWC2::Composition::Sideband:
2272 configureHwcCommonData(compositionInfo);
2273 configureSidebandComposition(compositionInfo);
2274 break;
2275
2276 case HWC2::Composition::SolidColor:
2277 configureHwcCommonData(compositionInfo);
2278 break;
2279
2280 case HWC2::Composition::Device:
2281 case HWC2::Composition::Cursor:
2282 configureHwcCommonData(compositionInfo);
2283 configureDeviceComposition(compositionInfo);
2284 break;
2285 }
2286}
2287
David Sodmanfa9b2af2017-12-24 13:28:59 -08002288void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002289 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002290 ALOGV("doComposition");
2291
David Sodmanfa9b2af2017-12-24 13:28:59 -08002292 if (display->isPoweredOn()) {
2293 // transform the dirty region into this screen's coordinate space
2294 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002295
David Sodmanfa9b2af2017-12-24 13:28:59 -08002296 // repaint the framebuffer (if needed)
2297 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002298
David Sodmanfa9b2af2017-12-24 13:28:59 -08002299 display->dirtyRegion.clear();
2300 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002301 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002302 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002303}
2304
David Sodmanfa9b2af2017-12-24 13:28:59 -08002305void SurfaceFlinger::postFrame()
2306{
2307 // |mStateLock| not needed as we are on the main thread
2308 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2309 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2310 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2311 logFrameStats();
2312 }
2313 }
2314}
2315
2316void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002317{
Mathias Agopian841cde52012-03-01 15:44:37 -08002318 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002319 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002320
David Sodmanfa9b2af2017-12-24 13:28:59 -08002321 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002322
David Sodmanfa9b2af2017-12-24 13:28:59 -08002323 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002324 const auto displayId = display->getId();
2325 if (displayId >= 0) {
2326 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002327 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002328 display->onSwapBuffersCompleted();
2329 display->makeCurrent();
David Sodman10a41ff2018-08-05 12:14:17 -07002330 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002331 sp<Fence> releaseFence = Fence::NO_FENCE;
Chia-I Wu7b549592017-11-15 09:14:57 -08002332 // The layer buffer from the previous frame (if any) is released
2333 // by HWC only when the release fence from this frame (if any) is
2334 // signaled. Always get the release fence from HWC first.
David Sodman10a41ff2018-08-05 12:14:17 -07002335 auto hwcLayer = compositionInfo.hwc.hwcLayer;
2336 if ((displayId >= 0) && hwcLayer) {
2337 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer.get());
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002338 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002339
2340 // If the layer was client composited in the previous frame, we
2341 // need to merge with the previous client target acquire fence.
2342 // Since we do not track that, always merge with the current
2343 // client target acquire fence when it is available, even though
2344 // this is suboptimal.
David Sodman10a41ff2018-08-05 12:14:17 -07002345 if (compositionInfo.compositionType == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002346 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002347 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002348 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002349
David Sodman10a41ff2018-08-05 12:14:17 -07002350 if (compositionInfo.layer) {
2351 compositionInfo.layer->onLayerDisplayed(releaseFence);
2352 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002353 }
Chia-I Wu83806892017-11-16 10:50:20 -08002354
2355 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002356 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002357 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002358 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002359 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002360 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002361 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002362 }
2363 }
2364
Dominik Laskowski7e045462018-05-30 13:02:02 -07002365 if (displayId >= 0) {
2366 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002367 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002368 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002369}
2370
Mathias Agopian87baae12012-07-31 12:38:26 -07002371void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002372{
Mathias Agopian841cde52012-03-01 15:44:37 -08002373 ATRACE_CALL();
2374
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002375 // here we keep a copy of the drawing state (that is the state that's
2376 // going to be overwritten by handleTransactionLocked()) outside of
2377 // mStateLock so that the side-effects of the State assignment
2378 // don't happen with mStateLock held (which can cause deadlocks).
2379 State drawingState(mDrawingState);
2380
Mathias Agopianca4d3602011-05-19 15:38:14 -07002381 Mutex::Autolock _l(mStateLock);
2382 const nsecs_t now = systemTime();
2383 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002384
Mathias Agopianca4d3602011-05-19 15:38:14 -07002385 // Here we're guaranteed that some transaction flags are set
2386 // so we can call handleTransactionLocked() unconditionally.
2387 // We call getTransactionFlags(), which will also clear the flags,
2388 // with mStateLock held to guarantee that mCurrentState won't change
2389 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002390
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002391 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002392 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002393 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002394
Mathias Agopianca4d3602011-05-19 15:38:14 -07002395 mLastTransactionTime = systemTime() - now;
2396 mDebugInTransaction = 0;
2397 invalidateHwcGeometry();
2398 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002399}
2400
Dominik Laskowski7e045462018-05-30 13:02:02 -07002401DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002402 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002403 // Figure out whether the event is for the primary display or an
2404 // external display by matching the Hwc display id against one for a
2405 // connected display. If we did not find a match, we then check what
2406 // displays are not already connected to determine the type. If we don't
2407 // have a connected primary display, we assume the new display is meant to
2408 // be the primary display, and then if we don't have an external display,
2409 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002410 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2411 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002412 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002413 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002414 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002415 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002416 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002417 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002418 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002419 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002420 return DisplayDevice::DISPLAY_EXTERNAL;
2421 }
2422
2423 return DisplayDevice::DISPLAY_ID_INVALID;
2424}
2425
Lloyd Piqueba04e622017-12-14 17:11:26 -08002426void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2427 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002428 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002429 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002430 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002431 continue;
2432 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002433
2434 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2435 ALOGE("External displays are not supported by the vr hardware composer.");
2436 continue;
2437 }
2438
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002439 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002440 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002441 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002442 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002443 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002444
2445 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002446 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002447 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002448 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002449 DisplayDeviceState info;
2450 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002451 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2452 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002453 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002454 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002455 mInterceptor->saveDisplayCreation(info);
2456 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002457 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002458 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002459
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002460 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002461 if (idx >= 0) {
2462 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002463 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002464 mCurrentState.displays.removeItemsAt(idx);
2465 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002466 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002467 }
2468
2469 processDisplayChangesLocked();
2470 }
2471
2472 mPendingHotplugEvents.clear();
2473}
2474
Lloyd Pique99d3da52018-01-22 17:48:03 -08002475sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002476 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002477 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002478 DisplayDeviceCreationArgs creationArgs(this, displayToken, state.type, displayId);
2479 creationArgs.isSecure = state.isSecure;
2480 creationArgs.displaySurface = dispSurface;
2481 creationArgs.hasWideColorGamut = false;
2482 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002483
Peiyong Lin13effd12018-07-24 17:01:47 -07002484 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002485 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002486 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002487 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002488 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002489 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002490
Dominik Laskowski7e045462018-05-30 13:02:02 -07002491 std::vector<RenderIntent> renderIntents =
2492 getHwComposer().getRenderIntents(displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002493 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002494 }
tangrobin6753a022018-08-10 10:58:54 +08002495 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002496
tangrobin6753a022018-08-10 10:58:54 +08002497 if (displayId >= 0) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002498 getHwComposer().getHdrCapabilities(displayId, &creationArgs.hdrCapabilities);
2499 creationArgs.supportedPerFrameMetadata =
2500 getHwComposer().getSupportedPerFrameMetadata(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002501 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002502
2503 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2504 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002505 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002506
2507 /*
2508 * Create our display's surface
2509 */
Peiyong Lin833074a2018-08-28 11:53:54 -07002510 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002511 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002512 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002513 renderSurface->setNativeWindow(nativeWindow.get());
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002514 creationArgs.displayWidth = renderSurface->getWidth();
2515 creationArgs.displayHeight = renderSurface->getHeight();
2516 creationArgs.renderSurface = std::move(renderSurface);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002517
2518 // Make sure that composition can never be stalled by a virtual display
2519 // consumer that isn't processing buffers fast enough. We have to do this
2520 // in two places:
2521 // * Here, in case the display is composed entirely by HWC.
2522 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2523 // window's swap interval in eglMakeCurrent, so they'll override the
2524 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002525 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002526 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2527 }
2528
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002529 creationArgs.displayInstallOrientation = state.type == DisplayDevice::DISPLAY_PRIMARY
2530 ? primaryDisplayOrientation
2531 : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002532
Lloyd Pique99d3da52018-01-22 17:48:03 -08002533 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002534 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002535
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002536 sp<DisplayDevice> display = new DisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002537
2538 if (maxFrameBufferAcquiredBuffers >= 3) {
2539 nativeWindowSurface->preallocateBuffers();
2540 }
2541
2542 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002543 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002544 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002545 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002546 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002547 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002548 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002549 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002550 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002551 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002552 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002553 display->setLayerStack(state.layerStack);
2554 display->setProjection(state.orientation, state.viewport, state.frame);
2555 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002556
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002557 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002558}
2559
Lloyd Pique347200f2017-12-14 17:00:15 -08002560void SurfaceFlinger::processDisplayChangesLocked() {
2561 // here we take advantage of Vector's copy-on-write semantics to
2562 // improve performance by skipping the transaction entirely when
2563 // know that the lists are identical
2564 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2565 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2566 if (!curr.isIdenticalTo(draw)) {
2567 mVisibleRegionsDirty = true;
2568 const size_t cc = curr.size();
2569 size_t dc = draw.size();
2570
2571 // find the displays that were removed
2572 // (ie: in drawing state but not in current state)
2573 // also handle displays that changed
2574 // (ie: displays that are in both lists)
2575 for (size_t i = 0; i < dc;) {
2576 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2577 if (j < 0) {
2578 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002579 // Call makeCurrent() on the primary display so we can
2580 // be sure that nothing associated with this display
2581 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002582 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2583 defaultDisplay->makeCurrent();
2584 }
2585 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2586 display->disconnect(getHwComposer());
2587 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002588 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002589 if (mUseScheduler) {
2590 mScheduler->hotplugReceived(mAppConnectionHandle,
2591 EventThread::DisplayType::Primary, false);
2592 } else {
2593 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2594 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002595 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002596 if (mUseScheduler) {
2597 mScheduler->hotplugReceived(mAppConnectionHandle,
2598 EventThread::DisplayType::External, false);
2599 } else {
2600 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2601 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002602 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002603 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002604 } else {
2605 // this display is in both lists. see if something changed.
2606 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002607 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002608 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2609 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2610 if (state_binder != draw_binder) {
2611 // changing the surface is like destroying and
2612 // recreating the DisplayDevice, so we just remove it
2613 // from the drawing state, so that it get re-added
2614 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002615 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2616 display->disconnect(getHwComposer());
2617 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002618 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002619 mDrawingState.displays.removeItemsAt(i);
2620 dc--;
2621 // at this point we must loop to the next item
2622 continue;
2623 }
2624
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002625 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002626 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002627 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002628 }
2629 if ((state.orientation != draw[i].orientation) ||
2630 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002631 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002632 }
2633 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002634 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002635 }
2636 }
2637 }
2638 ++i;
2639 }
2640
2641 // find displays that were added
2642 // (ie: in current state but not in drawing state)
2643 for (size_t i = 0; i < cc; i++) {
2644 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2645 const DisplayDeviceState& state(curr[i]);
2646
2647 sp<DisplaySurface> dispSurface;
2648 sp<IGraphicBufferProducer> producer;
2649 sp<IGraphicBufferProducer> bqProducer;
2650 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002651 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002652
Dominik Laskowski7e045462018-05-30 13:02:02 -07002653 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002654 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002655 // Virtual displays without a surface are dormant:
2656 // they have external state (layer stack, projection,
2657 // etc.) but no internal state (i.e. a DisplayDevice).
2658 if (state.surface != nullptr) {
2659 // Allow VR composer to use virtual displays.
2660 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2661 int width = 0;
2662 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2663 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2664 int height = 0;
2665 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2666 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2667 int intFormat = 0;
2668 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2669 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002670 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002671
Dominik Laskowski7e045462018-05-30 13:02:02 -07002672 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2673 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002674 }
2675
2676 // TODO: Plumb requested format back up to consumer
2677
2678 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002679 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002680 bqProducer, bqConsumer,
2681 state.displayName);
2682
2683 dispSurface = vds;
2684 producer = vds;
2685 }
2686 } else {
2687 ALOGE_IF(state.surface != nullptr,
2688 "adding a supported display, but rendering "
2689 "surface is provided (%p), ignoring it",
2690 state.surface.get());
2691
Dominik Laskowski7e045462018-05-30 13:02:02 -07002692 displayId = state.type;
2693 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002694 producer = bqProducer;
2695 }
2696
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002697 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002698 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002699 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002700 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002701 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002702 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002703 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002704 if (mUseScheduler) {
2705 mScheduler->hotplugReceived(mAppConnectionHandle,
2706 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002707 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002708 } else {
2709 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2710 true);
2711 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002712 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002713 if (mUseScheduler) {
2714 mScheduler->hotplugReceived(mAppConnectionHandle,
2715 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002716 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002717 } else {
2718 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2719 true);
2720 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002721 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002722 }
2723 }
2724 }
2725 }
2726 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002727
2728 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002729}
2730
Mathias Agopian87baae12012-07-31 12:38:26 -07002731void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002732{
Dan Stoza7dde5992015-05-22 09:51:44 -07002733 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002734 mCurrentState.traverseInZOrder([](Layer* layer) {
2735 layer->notifyAvailableFrames();
2736 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002737
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002738 /*
2739 * Traversal of the children
2740 * (perform the transaction for each of them if needed)
2741 */
2742
Mathias Agopian3559b072012-08-15 13:46:03 -07002743 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002744 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002745 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002746 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002747
2748 const uint32_t flags = layer->doTransaction(0);
2749 if (flags & Layer::eVisibleRegion)
2750 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002751 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002752 }
2753
2754 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002755 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002756 */
2757
Mathias Agopiane57f2922012-08-09 16:29:12 -07002758 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002759 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002760 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002761 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002762
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002763 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002764 // The transform hint might have changed for some layers
2765 // (either because a display has changed, or because a layer
2766 // as changed).
2767 //
2768 // Walk through all the layers in currentLayers,
2769 // and update their transform hint.
2770 //
2771 // If a layer is visible only on a single display, then that
2772 // display is used to calculate the hint, otherwise we use the
2773 // default display.
2774 //
2775 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2776 // the hint is set before we acquire a buffer from the surface texture.
2777 //
2778 // NOTE: layer transactions have taken place already, so we use their
2779 // drawing state. However, SurfaceFlinger's own transaction has not
2780 // happened yet, so we must use the current state layer list
2781 // (soon to become the drawing state list).
2782 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002783 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002784 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002785 bool first = true;
2786 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002787 // NOTE: we rely on the fact that layers are sorted by
2788 // layerStack first (so we don't have to traverse the list
2789 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002790 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002791 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002792 currentlayerStack = layerStack;
2793 // figure out if this layerstack is mirrored
2794 // (more than one display) if so, pick the default display,
2795 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002796 hintDisplay = nullptr;
2797 for (const auto& [token, display] : mDisplays) {
2798 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2799 if (hintDisplay) {
2800 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002801 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002802 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002803 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002804 }
2805 }
2806 }
2807 }
Chet Haase91d25932013-04-11 15:24:55 -07002808
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002809 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002810 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2811 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002812
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002813 // could be null when this layer is using a layerStack
2814 // that is not visible on any display. Also can occur at
2815 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002816 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002817 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002818
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002819 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002820 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002821 if (hintDisplay) {
2822 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002823 }
Robert Carr2047fae2016-11-28 14:09:09 -08002824
2825 first = false;
2826 });
Mathias Agopian84300952012-11-21 16:02:13 -08002827 }
2828
2829
Mathias Agopian3559b072012-08-15 13:46:03 -07002830 /*
2831 * Perform our own transaction if needed
2832 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002833
2834 if (mLayersAdded) {
2835 mLayersAdded = false;
2836 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002837 mVisibleRegionsDirty = true;
2838 }
2839
2840 // some layers might have been removed, so
2841 // we need to update the regions they're exposing.
2842 if (mLayersRemoved) {
2843 mLayersRemoved = false;
2844 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002845 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002846 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002847 // this layer is not visible anymore
2848 // TODO: we could traverse the tree from front to back and
2849 // compute the actual visible region
2850 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002851 Region visibleReg;
2852 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002853 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002854 }
Robert Carr2047fae2016-11-28 14:09:09 -08002855 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002856 }
2857
2858 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002859
2860 updateCursorAsync();
2861}
2862
2863void SurfaceFlinger::updateCursorAsync()
2864{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002865 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002866 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002867 continue;
2868 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002869
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002870 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2871 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002872 }
2873 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002874}
2875
2876void SurfaceFlinger::commitTransaction()
2877{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002878 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002879 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002880 for (const auto& l : mLayersPendingRemoval) {
2881 recordBufferingStats(l->getName().string(),
2882 l->getOccupancyHistory(true));
2883 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002884 }
2885 mLayersPendingRemoval.clear();
2886 }
2887
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002888 // If this transaction is part of a window animation then the next frame
2889 // we composite should be considered an animation as well.
2890 mAnimCompositionPending = mAnimTransactionPending;
2891
Mathias Agopian4fec8732012-06-29 14:12:52 -07002892 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002893 // clear the "changed" flags in current state
2894 mCurrentState.colorMatrixChanged = false;
2895
Robert Carr1f0a16a2016-10-24 16:27:39 -07002896 mDrawingState.traverseInZOrder([](Layer* layer) {
2897 layer->commitChildList();
2898 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002899 mTransactionPending = false;
2900 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002901 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002902}
2903
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002904void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2905 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002906 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002907 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002908
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002909 Region aboveOpaqueLayers;
2910 Region aboveCoveredLayers;
2911 Region dirty;
2912
Mathias Agopian87baae12012-07-31 12:38:26 -07002913 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002914
Robert Carr2047fae2016-11-28 14:09:09 -08002915 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002916 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002917 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002918
Jesse Hall01e29052013-02-19 16:13:35 -08002919 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002920 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002921 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002922 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002923
Mathias Agopianab028732010-03-16 16:41:46 -07002924 /*
2925 * opaqueRegion: area of a surface that is fully opaque.
2926 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002927 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002928
2929 /*
2930 * visibleRegion: area of a surface that is visible on screen
2931 * and not fully transparent. This is essentially the layer's
2932 * footprint minus the opaque regions above it.
2933 * Areas covered by a translucent surface are considered visible.
2934 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002935 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002936
2937 /*
2938 * coveredRegion: area of a surface that is covered by all
2939 * visible regions above it (which includes the translucent areas).
2940 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002941 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002942
Jesse Halla8026d22012-09-25 13:25:04 -07002943 /*
2944 * transparentRegion: area of a surface that is hinted to be completely
2945 * transparent. This is only used to tell when the layer has no visible
2946 * non-transparent regions and can be removed from the layer list. It
2947 * does not affect the visibleRegion of this layer or any layers
2948 * beneath it. The hint may not be correct if apps don't respect the
2949 * SurfaceView restrictions (which, sadly, some don't).
2950 */
2951 Region transparentRegion;
2952
Mathias Agopianab028732010-03-16 16:41:46 -07002953
2954 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002955 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002956 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002957 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002958 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002959 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002960 if (!visibleRegion.isEmpty()) {
2961 // Remove the transparent area from the visible region
2962 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002963 if (tr.preserveRects()) {
2964 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002965 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002966 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002967 // transformation too complex, can't do the
2968 // transparent region optimization.
2969 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002970 }
Mathias Agopianab028732010-03-16 16:41:46 -07002971 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002972
Mathias Agopianab028732010-03-16 16:41:46 -07002973 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002974 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002975 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002976 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002977 // the opaque region is the layer's footprint
2978 opaqueRegion = visibleRegion;
2979 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002980 }
2981 }
2982
Robert Carre5f4f692018-01-12 13:12:28 -08002983 if (visibleRegion.isEmpty()) {
2984 layer->clearVisibilityRegions();
2985 return;
2986 }
2987
Mathias Agopianab028732010-03-16 16:41:46 -07002988 // Clip the covered region to the visible region
2989 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2990
2991 // Update aboveCoveredLayers for next (lower) layer
2992 aboveCoveredLayers.orSelf(visibleRegion);
2993
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002994 // subtract the opaque region covered by the layers above us
2995 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002996
2997 // compute this layer's dirty region
2998 if (layer->contentDirty) {
2999 // we need to invalidate the whole region
3000 dirty = visibleRegion;
3001 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003002 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003003 layer->contentDirty = false;
3004 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003005 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003006 * the exposed region consists of two components:
3007 * 1) what's VISIBLE now and was COVERED before
3008 * 2) what's EXPOSED now less what was EXPOSED before
3009 *
3010 * note that (1) is conservative, we start with the whole
3011 * visible region but only keep what used to be covered by
3012 * something -- which mean it may have been exposed.
3013 *
3014 * (2) handles areas that were not covered by anything but got
3015 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003016 */
Mathias Agopianab028732010-03-16 16:41:46 -07003017 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003018 const Region oldVisibleRegion = layer->visibleRegion;
3019 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003020 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3021 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003022 }
3023 dirty.subtractSelf(aboveOpaqueLayers);
3024
3025 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003026 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003027
Mathias Agopianab028732010-03-16 16:41:46 -07003028 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003029 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003030
Jesse Halla8026d22012-09-25 13:25:04 -07003031 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003032 layer->setVisibleRegion(visibleRegion);
3033 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003034 layer->setVisibleNonTransparentRegion(
3035 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003036 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003037
Mathias Agopian87baae12012-07-31 12:38:26 -07003038 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003039}
3040
Chia-I Wuab0c3192017-08-01 11:29:00 -07003041void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003042 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003043 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
3044 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003045 }
3046 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003047}
3048
Dan Stoza6b9454d2014-11-07 16:00:59 -08003049bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003050{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003051 ALOGV("handlePageFlip");
3052
Brian Andersond6927fb2016-07-23 23:37:30 -07003053 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003054
Mathias Agopian4fec8732012-06-29 14:12:52 -07003055 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003056 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003057 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003058
3059 // Store the set of layers that need updates. This set must not change as
3060 // buffers are being latched, as this could result in a deadlock.
3061 // Example: Two producers share the same command stream and:
3062 // 1.) Layer 0 is latched
3063 // 2.) Layer 0 gets a new frame
3064 // 2.) Layer 1 gets a new frame
3065 // 3.) Layer 1 is latched.
3066 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3067 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003068 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003069 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003070 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003071 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3072 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003073 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003074 } else {
3075 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003076 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003077 } else {
3078 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003079 }
Robert Carr2047fae2016-11-28 14:09:09 -08003080 });
3081
Dan Stoza9e56aa02015-11-02 13:00:03 -08003082 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri86770e52018-09-24 22:40:58 +00003083 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
Dan Stozaee44edd2015-03-23 15:50:23 -07003084 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003085 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07003086 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06003087 newDataLatched = true;
3088 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003089 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003090
Alec Mouri86770e52018-09-24 22:40:58 +00003091 // Clear the renderengine fence here...
3092 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3093 // clear instead of sp::clear.
3094 getBE().flushFence = Fence::NO_FENCE;
3095
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003096 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003097
3098 // If we will need to wake up at some time in the future to deal with a
3099 // queued frame that shouldn't be displayed during this vsync period, wake
3100 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003101 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003102 signalLayerUpdate();
3103 }
3104
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003105 // enter boot animation on first buffer latch
3106 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3107 ALOGI("Enter boot animation");
3108 mBootStage = BootStage::BOOTANIMATION;
3109 }
3110
Dan Stoza6b9454d2014-11-07 16:00:59 -08003111 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003112 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003113}
3114
Mathias Agopianad456f92011-01-13 17:53:01 -08003115void SurfaceFlinger::invalidateHwcGeometry()
3116{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003117 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003118}
3119
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003120void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
3121 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003122 // We only need to actually compose the display if:
3123 // 1) It is being handled by hardware composer, which may need this to
3124 // keep its virtual display state machine in sync, or
3125 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07003126 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08003127 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003128 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003129 return;
3130 }
3131
Dan Stoza9e56aa02015-11-02 13:00:03 -08003132 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003133 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003134
3135 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003136 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003137}
3138
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003139bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003140 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003141
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003142 const Region bounds(display->bounds());
3143 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003144 const auto displayId = display->getId();
3145 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003146 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003147
Peiyong Lind3788632018-09-18 16:01:31 -07003148 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003149 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003150 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003151
Dan Stoza9e56aa02015-11-02 13:00:03 -08003152 if (hasClientComposition) {
3153 ALOGV("hasClientComposition");
3154
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003155 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003156 if (display->hasWideColorGamut()) {
3157 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003158 }
3159 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003160 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003161 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003162
Dominik Laskowski7e045462018-05-30 13:02:02 -07003163 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003164 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3165 HWC2::Capability::SkipClientColorTransform);
3166
Peiyong Lind3788632018-09-18 16:01:31 -07003167 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003168 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3169 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003170 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003171 }
3172
Chia-I Wud49d6692018-06-27 07:17:41 +08003173 // The current enhanced saturation matrix is designed to enhance Display P3,
3174 // thus we only apply this matrix when the render intent is not colorimetric
3175 // and the output color space is Display P3.
3176 needsEnhancedColorMatrix =
3177 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3178 outputDataspace == Dataspace::DISPLAY_P3);
3179 if (needsEnhancedColorMatrix) {
3180 colorMatrix *= mEnhancedSaturationMatrix;
3181 }
3182
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003183 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003184 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003185 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003186 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003187
3188 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003189 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3190 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3191 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003192 }
3193 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003194 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003195
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003196 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003197 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003198 // when using overlays, we assume a fully transparent framebuffer
3199 // NOTE: we could reduce how much we need to clear, for instance
3200 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003201 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003202 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003203 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003204 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003205 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003206 // we're left with the letterbox region
3207 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003208 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003209
3210 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003211 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003212
Mathias Agopianb9494d52012-04-18 02:28:45 -07003213 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003214 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003215 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003216 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003217 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003218 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003219
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003220 const Rect& bounds = display->getBounds();
3221 const Rect& scissor = display->getScissor();
3222 if (scissor != bounds) {
3223 // scissor doesn't match the screen's dimensions, so we
3224 // need to clear everything outside of it and enable
3225 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003226
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003227 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003228 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003229 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003230 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003231
Mathias Agopian85d751c2012-08-29 16:59:24 -07003232 /*
3233 * and then, render the layers targeted at the framebuffer
3234 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003235
Dan Stoza9e56aa02015-11-02 13:00:03 -08003236 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003237 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003238 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003239 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003240 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003241 displayTransform.transform(layer->visibleRegion)));
3242 ALOGV("Layer: %s", layer->getName().string());
3243 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003244 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003245 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003246 case HWC2::Composition::Cursor:
3247 case HWC2::Composition::Device:
3248 case HWC2::Composition::Sideband:
3249 case HWC2::Composition::SolidColor: {
David Sodmanc1498e62018-09-12 14:36:26 -07003250 const Layer::State& state(layer->getDrawingState());
3251 if (layer->getClearClientTarget(displayId) && !firstLayer &&
3252 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3253 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003254 // never clear the very first layer since we're
3255 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003256 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003257 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003258 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003259 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003260 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003261 if (layer->hasColorTransform()) {
3262 mat4 tmpMatrix;
3263 if (applyColorMatrix) {
3264 tmpMatrix = mDrawingState.colorMatrix;
3265 }
3266 tmpMatrix *= layer->getColorTransform();
3267 if (needsEnhancedColorMatrix) {
3268 tmpMatrix *= mEnhancedSaturationMatrix;
3269 }
3270 getRenderEngine().setColorTransform(tmpMatrix);
3271 } else {
3272 getRenderEngine().setColorTransform(colorMatrix);
3273 }
David Sodmanc1498e62018-09-12 14:36:26 -07003274 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003275 break;
3276 }
3277 default:
3278 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003279 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003280 } else {
3281 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003282 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003283 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003284 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003285
Peiyong Lind3788632018-09-18 16:01:31 -07003286 // Clear color transform matrix at the end of the frame.
3287 getRenderEngine().setColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003288
Mathias Agopianf45c5102012-10-24 16:29:17 -07003289 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003290 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003291 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003292}
3293
Chia-I Wu28e3a252018-09-07 12:05:02 -07003294void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003295 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003296 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003297}
3298
Dan Stoza7d89d062015-04-30 13:29:25 -07003299status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003300 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003301 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003302 const sp<Layer>& lbc,
3303 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003304{
Dan Stoza7d89d062015-04-30 13:29:25 -07003305 // add this layer to the current state list
3306 {
3307 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003308 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003309 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3310 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003311 return NO_MEMORY;
3312 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003313 if (parent == nullptr) {
3314 mCurrentState.layersSortedByZ.add(lbc);
3315 } else {
Rob Carr4bba3702018-10-08 21:53:30 +00003316 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003317 ALOGE("addClientLayer called with a removed parent");
3318 return NAME_NOT_FOUND;
3319 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003320 parent->addChild(lbc);
3321 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003322
Yiwei Zhang243b3782018-05-15 17:40:04 -07003323 if (gbc != nullptr) {
3324 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3325 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3326 mMaxGraphicBufferProducerListSize,
3327 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3328 mGraphicBufferProducerList.size(),
3329 mMaxGraphicBufferProducerListSize, mNumLayers);
3330 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003331 mLayersAdded = true;
3332 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003333 }
3334
Mathias Agopian96f08192010-06-02 23:28:45 -07003335 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003336 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003337
Dan Stoza7d89d062015-04-30 13:29:25 -07003338 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003339}
3340
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003341status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003342 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003343 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3344}
Robert Carr7f9b8992017-03-10 11:08:39 -08003345
chaviwca27f252018-02-06 16:46:39 -08003346status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3347 bool topLevelOnly) {
Rob Carr4bba3702018-10-08 21:53:30 +00003348 if (layer->isPendingRemoval()) {
chaviw8b3871a2017-11-01 17:41:01 -07003349 return NO_ERROR;
3350 }
3351
Robert Carr1f0a16a2016-10-24 16:27:39 -07003352 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003353 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003354 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003355 if (topLevelOnly) {
3356 return NO_ERROR;
3357 }
Rob Carr4bba3702018-10-08 21:53:30 +00003358
3359 sp<Layer> ancestor = p;
3360 while (ancestor->getParent() != nullptr) {
3361 ancestor = ancestor->getParent();
3362 }
3363 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3364 ALOGE("removeLayer called with a layer whose parent has been removed");
3365 return NAME_NOT_FOUND;
3366 }
3367
Chia-I Wufae51c42017-06-15 12:53:59 -07003368 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003369 } else {
3370 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003371 }
3372
Rob Carr4bba3702018-10-08 21:53:30 +00003373 // As a matter of normal operation, the LayerCleaner will produce a second
3374 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3375 // so we will succeed in promoting it, but it's already been removed
3376 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3377 // otherwise something has gone wrong and we are leaking the layer.
3378 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
3379 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3380 layer->getName().string(),
3381 (p != nullptr) ? p->getName().string() : "no-parent");
3382 return BAD_VALUE;
3383 } else if (index < 0) {
3384 return NO_ERROR;
3385 }
3386
Chia-I Wuc6657022017-08-15 11:18:17 -07003387 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003388 mLayersPendingRemoval.add(layer);
3389 mLayersRemoved = true;
Rob Carr4bba3702018-10-08 21:53:30 +00003390 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003391 setTransactionFlags(eTransactionNeeded);
3392 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003393}
3394
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003395uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003396 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003397}
3398
Mathias Agopian3f844832013-08-07 21:24:32 -07003399uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003400 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003401}
3402
Mathias Agopian3f844832013-08-07 21:24:32 -07003403uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003404 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003405}
3406
3407uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003408 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003409 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003410 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003411 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003412 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003413 }
3414 return old;
3415}
3416
chaviwca27f252018-02-06 16:46:39 -08003417bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3418 for (const ComposerState& state : states) {
3419 // Here we need to check that the interface we're given is indeed
3420 // one of our own. A malicious client could give us a nullptr
3421 // IInterface, or one of its own or even one of our own but a
3422 // different type. All these situations would cause us to crash.
3423 if (state.client == nullptr) {
3424 return true;
3425 }
3426
3427 sp<IBinder> binder = IInterface::asBinder(state.client);
3428 if (binder == nullptr) {
3429 return true;
3430 }
3431
3432 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3433 return true;
3434 }
3435 }
3436 return false;
3437}
3438
Mathias Agopian8b33f032012-07-24 20:43:54 -07003439void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003440 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003441 const Vector<DisplayState>& displays,
3442 uint32_t flags)
3443{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003444 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003445 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003446 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003447
chaviwca27f252018-02-06 16:46:39 -08003448 if (containsAnyInvalidClientState(states)) {
3449 return;
3450 }
3451
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003452 if (flags & eAnimation) {
3453 // For window updates that are part of an animation we must wait for
3454 // previous animation "frames" to be handled.
3455 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003456 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003457 if (CC_UNLIKELY(err != NO_ERROR)) {
3458 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003459 // caller after a few seconds.
3460 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3461 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003462 mAnimTransactionPending = false;
3463 break;
3464 }
3465 }
3466 }
3467
chaviwca27f252018-02-06 16:46:39 -08003468 for (const DisplayState& display : displays) {
3469 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003470 }
3471
chaviwca27f252018-02-06 16:46:39 -08003472 for (const ComposerState& state : states) {
3473 transactionFlags |= setClientStateLocked(state);
3474 }
3475
3476 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3477 // as destroyed should only occur after setting all other states. This is to allow for a
3478 // child re-parent to happen before marking its original parent as destroyed (which would
3479 // then mark the child as destroyed).
3480 for (const ComposerState& state : states) {
3481 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003482 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003483
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003484 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3485 // anyway. This can be used as a flush mechanism for previous async transactions.
3486 // Empty animation transaction can be used to simulate back-pressure, so also force a
3487 // transaction for empty animation transactions.
3488 if (transactionFlags == 0 &&
3489 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003490 transactionFlags = eTransactionNeeded;
3491 }
3492
Mathias Agopian386aa982011-11-07 21:58:03 -08003493 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003494 if (mInterceptor->isEnabled()) {
3495 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003496 }
Irvel468051e2016-06-13 16:44:44 -07003497
Mathias Agopian386aa982011-11-07 21:58:03 -08003498 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003499 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3500 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003501 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003502
3503 // if this is a synchronous transaction, wait for it to take effect
3504 // before returning.
3505 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003506 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003507 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003508 if (flags & eAnimation) {
3509 mAnimTransactionPending = true;
3510 }
3511 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003512 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3513 if (CC_UNLIKELY(err != NO_ERROR)) {
3514 // just in case something goes wrong in SF, return to the
3515 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003516 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3517 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003518 break;
3519 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003520 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003521 }
3522}
3523
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003524uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3525 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3526 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003527
Mathias Agopiane57f2922012-08-09 16:29:12 -07003528 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003529 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3530
3531 const uint32_t what = s.what;
3532 if (what & DisplayState::eSurfaceChanged) {
3533 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3534 state.surface = s.surface;
3535 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003536 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003537 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003538 if (what & DisplayState::eLayerStackChanged) {
3539 if (state.layerStack != s.layerStack) {
3540 state.layerStack = s.layerStack;
3541 flags |= eDisplayTransactionNeeded;
3542 }
3543 }
3544 if (what & DisplayState::eDisplayProjectionChanged) {
3545 if (state.orientation != s.orientation) {
3546 state.orientation = s.orientation;
3547 flags |= eDisplayTransactionNeeded;
3548 }
3549 if (state.frame != s.frame) {
3550 state.frame = s.frame;
3551 flags |= eDisplayTransactionNeeded;
3552 }
3553 if (state.viewport != s.viewport) {
3554 state.viewport = s.viewport;
3555 flags |= eDisplayTransactionNeeded;
3556 }
3557 }
3558 if (what & DisplayState::eDisplaySizeChanged) {
3559 if (state.width != s.width) {
3560 state.width = s.width;
3561 flags |= eDisplayTransactionNeeded;
3562 }
3563 if (state.height != s.height) {
3564 state.height = s.height;
3565 flags |= eDisplayTransactionNeeded;
3566 }
3567 }
3568
Mathias Agopiane57f2922012-08-09 16:29:12 -07003569 return flags;
3570}
3571
Robert Carrd4ae7f32018-06-07 16:10:57 -07003572bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3573 IPCThreadState* ipc = IPCThreadState::self();
3574 const int pid = ipc->getCallingPid();
3575 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003576 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003577 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003578 return false;
3579 }
3580 return true;
3581}
3582
chaviwca27f252018-02-06 16:46:39 -08003583uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3584 const layer_state_t& s = composerState.state;
3585 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3586
Mathias Agopian13127d82013-03-05 17:47:11 -08003587 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003588 if (layer == nullptr) {
3589 return 0;
3590 }
3591
Rob Carr4bba3702018-10-08 21:53:30 +00003592 if (layer->isPendingRemoval()) {
chaviw8b3871a2017-11-01 17:41:01 -07003593 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3594 return 0;
3595 }
3596
3597 uint32_t flags = 0;
3598
3599 const uint32_t what = s.what;
3600 bool geometryAppliesWithResize =
3601 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003602
3603 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3604 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003605 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003606 layer->pushPendingState();
3607 }
3608
chaviw8b3871a2017-11-01 17:41:01 -07003609 if (what & layer_state_t::ePositionChanged) {
3610 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3611 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003612 }
chaviw8b3871a2017-11-01 17:41:01 -07003613 }
3614 if (what & layer_state_t::eLayerChanged) {
3615 // NOTE: index needs to be calculated before we update the state
3616 const auto& p = layer->getParent();
3617 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003618 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003619 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003620 mCurrentState.layersSortedByZ.removeAt(idx);
3621 mCurrentState.layersSortedByZ.add(layer);
3622 // we need traversal (state changed)
3623 // AND transaction (list changed)
3624 flags |= eTransactionNeeded|eTraversalNeeded;
3625 }
chaviw8b3871a2017-11-01 17:41:01 -07003626 } else {
3627 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003628 flags |= eTransactionNeeded|eTraversalNeeded;
3629 }
3630 }
chaviw8b3871a2017-11-01 17:41:01 -07003631 }
3632 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003633 // NOTE: index needs to be calculated before we update the state
3634 const auto& p = layer->getParent();
3635 if (p == nullptr) {
3636 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3637 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3638 mCurrentState.layersSortedByZ.removeAt(idx);
3639 mCurrentState.layersSortedByZ.add(layer);
3640 // we need traversal (state changed)
3641 // AND transaction (list changed)
3642 flags |= eTransactionNeeded|eTraversalNeeded;
3643 }
3644 } else {
3645 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3646 flags |= eTransactionNeeded|eTraversalNeeded;
3647 }
chaviw8b3871a2017-11-01 17:41:01 -07003648 }
3649 }
3650 if (what & layer_state_t::eSizeChanged) {
3651 if (layer->setSize(s.w, s.h)) {
3652 flags |= eTraversalNeeded;
3653 }
3654 }
3655 if (what & layer_state_t::eAlphaChanged) {
3656 if (layer->setAlpha(s.alpha))
3657 flags |= eTraversalNeeded;
3658 }
3659 if (what & layer_state_t::eColorChanged) {
3660 if (layer->setColor(s.color))
3661 flags |= eTraversalNeeded;
3662 }
Peiyong Lind3788632018-09-18 16:01:31 -07003663 if (what & layer_state_t::eColorTransformChanged) {
3664 if (layer->setColorTransform(s.colorTransform)) {
3665 flags |= eTraversalNeeded;
3666 }
3667 }
chaviw8b3871a2017-11-01 17:41:01 -07003668 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003669 // TODO: b/109894387
3670 //
3671 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3672 // rotation. To see the problem observe that if we have a square parent, and a child
3673 // of the same size, then we rotate the child 45 degrees around it's center, the child
3674 // must now be cropped to a non rectangular 8 sided region.
3675 //
3676 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3677 // private API, and the WindowManager only uses rotation in one case, which is on a top
3678 // level layer in which cropping is not an issue.
3679 //
3680 // However given that abuse of rotation matrices could lead to surfaces extending outside
3681 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3682 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3683 // transformations.
3684 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003685 flags |= eTraversalNeeded;
3686 }
3687 if (what & layer_state_t::eTransparentRegionChanged) {
3688 if (layer->setTransparentRegionHint(s.transparentRegion))
3689 flags |= eTraversalNeeded;
3690 }
3691 if (what & layer_state_t::eFlagsChanged) {
3692 if (layer->setFlags(s.flags, s.mask))
3693 flags |= eTraversalNeeded;
3694 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003695 if (what & layer_state_t::eCropChanged_legacy) {
3696 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003697 flags |= eTraversalNeeded;
3698 }
chaviw8b3871a2017-11-01 17:41:01 -07003699 if (what & layer_state_t::eLayerStackChanged) {
3700 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3701 // We only allow setting layer stacks for top level layers,
3702 // everything else inherits layer stack from its parent.
3703 if (layer->hasParent()) {
3704 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3705 layer->getName().string());
3706 } else if (idx < 0) {
3707 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3708 "that also does not appear in the top level layer list. Something"
3709 " has gone wrong.", layer->getName().string());
3710 } else if (layer->setLayerStack(s.layerStack)) {
3711 mCurrentState.layersSortedByZ.removeAt(idx);
3712 mCurrentState.layersSortedByZ.add(layer);
3713 // we need traversal (state changed)
3714 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003715 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003716 }
3717 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003718 if (what & layer_state_t::eDeferTransaction_legacy) {
3719 if (s.barrierHandle_legacy != nullptr) {
3720 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3721 } else if (s.barrierGbp_legacy != nullptr) {
3722 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003723 if (authenticateSurfaceTextureLocked(gbp)) {
3724 const auto& otherLayer =
3725 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003726 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003727 } else {
3728 ALOGE("Attempt to defer transaction to to an"
3729 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003730 }
3731 }
chaviw8b3871a2017-11-01 17:41:01 -07003732 // We don't trigger a traversal here because if no other state is
3733 // changed, we don't want this to cause any more work
3734 }
3735 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003736 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003737 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003738 if (!hadParent) {
3739 mCurrentState.layersSortedByZ.remove(layer);
3740 }
chaviw8b3871a2017-11-01 17:41:01 -07003741 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003742 }
chaviw8b3871a2017-11-01 17:41:01 -07003743 }
3744 if (what & layer_state_t::eReparentChildren) {
3745 if (layer->reparentChildren(s.reparentHandle)) {
3746 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003747 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003748 }
chaviw8b3871a2017-11-01 17:41:01 -07003749 if (what & layer_state_t::eDetachChildren) {
3750 layer->detachChildren();
3751 }
3752 if (what & layer_state_t::eOverrideScalingModeChanged) {
3753 layer->setOverrideScalingMode(s.overrideScalingMode);
3754 // We don't trigger a traversal here because if no other state is
3755 // changed, we don't want this to cause any more work
3756 }
Marissa Wall61c58622018-07-18 10:12:20 -07003757 if (what & layer_state_t::eTransformChanged) {
3758 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3759 }
3760 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3761 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3762 flags |= eTraversalNeeded;
3763 }
3764 if (what & layer_state_t::eCropChanged) {
3765 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3766 }
3767 if (what & layer_state_t::eBufferChanged) {
3768 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3769 }
3770 if (what & layer_state_t::eAcquireFenceChanged) {
3771 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3772 }
3773 if (what & layer_state_t::eDataspaceChanged) {
3774 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3775 }
3776 if (what & layer_state_t::eHdrMetadataChanged) {
3777 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3778 }
3779 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3780 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3781 }
3782 if (what & layer_state_t::eApiChanged) {
3783 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3784 }
3785 if (what & layer_state_t::eSidebandStreamChanged) {
3786 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3787 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003788 return flags;
3789}
3790
chaviwca27f252018-02-06 16:46:39 -08003791void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3792 const layer_state_t& state = composerState.state;
3793 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3794
3795 sp<Layer> layer(client->getLayerUser(state.surface));
3796 if (layer == nullptr) {
3797 return;
3798 }
3799
Rob Carr4bba3702018-10-08 21:53:30 +00003800 if (layer->isPendingRemoval()) {
chaviwca27f252018-02-06 16:46:39 -08003801 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3802 return;
3803 }
3804
3805 if (state.what & layer_state_t::eDestroySurface) {
3806 removeLayerLocked(mStateLock, layer);
3807 }
3808}
3809
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003810status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003811 const String8& name,
3812 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003813 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003814 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003815 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003816{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003817 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003818 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003819 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003820 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003821 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003822
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003823 status_t result = NO_ERROR;
3824
3825 sp<Layer> layer;
3826
Cody Northropbc755282017-03-31 12:00:08 -06003827 String8 uniqueName = getUniqueLayerName(name);
3828
Mathias Agopian3165cc22012-08-08 19:42:09 -07003829 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003830 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003831 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3832 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003833
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003834 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003835 case ISurfaceComposerClient::eFXSurfaceBufferState:
3836 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3837 break;
chaviw13fdc492017-06-27 12:40:18 -07003838 case ISurfaceComposerClient::eFXSurfaceColor:
3839 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003840 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003841 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003842 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003843 case ISurfaceComposerClient::eFXSurfaceContainer:
3844 result = createContainerLayer(client,
3845 uniqueName, w, h, flags,
3846 handle, &layer);
3847 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003848 default:
3849 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003850 break;
3851 }
3852
Dan Stoza7d89d062015-04-30 13:29:25 -07003853 if (result != NO_ERROR) {
3854 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003855 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003856
Chia-I Wuab0c3192017-08-01 11:29:00 -07003857 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3858 // TODO b/64227542
3859 if (windowType == 441731) {
3860 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3861 layer->setPrimaryDisplayOnly();
3862 }
3863
Albert Chaulk479c60c2017-01-27 14:21:34 -05003864 layer->setInfo(windowType, ownerUid);
3865
Robert Carr1f0a16a2016-10-24 16:27:39 -07003866 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003867 if (result != NO_ERROR) {
3868 return result;
3869 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003870 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003871
3872 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003873 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003874}
3875
Cody Northropbc755282017-03-31 12:00:08 -06003876String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3877{
3878 bool matchFound = true;
3879 uint32_t dupeCounter = 0;
3880
3881 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3882 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3883
Dan Stoza436ccf32018-06-21 12:10:12 -07003884 // Grab the state lock since we're accessing mCurrentState
3885 Mutex::Autolock lock(mStateLock);
3886
Cody Northropbc755282017-03-31 12:00:08 -06003887 // Loop over layers until we're sure there is no matching name
3888 while (matchFound) {
3889 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003890 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003891 if (layer->getName() == uniqueName) {
3892 matchFound = true;
3893 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3894 }
3895 });
3896 }
3897
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003898 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3899 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003900
3901 return uniqueName;
3902}
3903
Marissa Wallfd668622018-05-10 10:21:13 -07003904status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3905 uint32_t w, uint32_t h, uint32_t flags,
3906 PixelFormat& format, sp<IBinder>* handle,
3907 sp<IGraphicBufferProducer>* gbp,
3908 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003909 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003910 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003911 case PIXEL_FORMAT_TRANSPARENT:
3912 case PIXEL_FORMAT_TRANSLUCENT:
3913 format = PIXEL_FORMAT_RGBA_8888;
3914 break;
3915 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003916 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003917 break;
3918 }
3919
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003920 sp<BufferQueueLayer> layer =
3921 new BufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003922 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003923 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003924 *handle = layer->getHandle();
3925 *gbp = layer->getProducer();
3926 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003927 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003928
Marissa Wallfd668622018-05-10 10:21:13 -07003929 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003930 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003931}
3932
Marissa Wall61c58622018-07-18 10:12:20 -07003933status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3934 uint32_t w, uint32_t h, uint32_t flags,
3935 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003936 sp<BufferStateLayer> layer =
3937 new BufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003938 *handle = layer->getHandle();
3939 *outLayer = layer;
3940
3941 return NO_ERROR;
3942}
3943
chaviw13fdc492017-06-27 12:40:18 -07003944status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003945 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003946 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003947{
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003948 *outLayer = new ColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003949 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003950 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003951}
3952
Robert Carr6b3f6c52018-08-13 13:05:17 -07003953status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3954 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3955 sp<IBinder>* handle, sp<Layer>* outLayer)
3956{
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003957 *outLayer = new ContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003958 *handle = (*outLayer)->getHandle();
3959 return NO_ERROR;
3960}
3961
3962
Mathias Agopianac9fa422013-02-11 16:40:36 -08003963status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003964{
Robert Carr9524cb32017-02-13 11:32:32 -08003965 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003966 status_t err = NO_ERROR;
3967 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003968 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003969 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003970 err = removeLayer(l);
3971 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3972 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003973 }
3974 return err;
3975}
3976
Rob Carr4bba3702018-10-08 21:53:30 +00003977status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
3978{
3979 // called by ~LayerCleaner() when all references to the IBinder (handle)
3980 // are gone
3981 sp<Layer> l = layer.promote();
3982 if (l == nullptr) {
3983 // The layer has already been removed, carry on
3984 return NO_ERROR;
3985 }
3986 // If we have a parent, then we can continue to live as long as it does.
3987 return removeLayer(l, true);
3988}
3989
Mathias Agopianb60314a2012-04-10 22:09:54 -07003990// ---------------------------------------------------------------------------
3991
Andy McFadden13a082e2012-08-24 10:16:42 -07003992void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003993 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3994 if (!displayToken) return;
3995
Jesse Hall01e29052013-02-19 16:13:35 -08003996 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003997 Vector<ComposerState> state;
3998 Vector<DisplayState> displays;
3999 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004000 d.what = DisplayState::eDisplayProjectionChanged |
4001 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004002 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08004003 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004004 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004005 d.frame.makeInvalid();
4006 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004007 d.width = 0;
4008 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004009 displays.add(d);
4010 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004011
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004012 const auto display = getDisplayDevice(displayToken);
4013 if (!display) return;
4014
4015 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
4016
4017 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08004018 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07004019 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004020
Brian Andersond0010582017-03-07 13:20:31 -08004021 // Use phase of 0 since phase is not known.
4022 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07004023 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
4024 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004025}
4026
4027void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004028 // Async since we may be called from the main thread.
4029 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004030}
4031
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004032void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
4033 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004034 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004035 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07004036
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004037 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004038 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004039 return;
4040 }
4041
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004042 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004043 ALOGW("Trying to set power mode for virtual display");
4044 return;
4045 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004046
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004047 display->setPowerMode(mode);
4048
Lloyd Pique4dccc412018-01-22 17:21:36 -08004049 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07004050 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004051 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07004052 if (idx < 0) {
4053 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
4054 return;
4055 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07004056 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07004057 }
4058
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004059 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004060 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004061 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004062 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004063 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004064 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004065 if (mUseScheduler) {
4066 mScheduler->onScreenAcquired(mAppConnectionHandle);
4067 } else {
4068 mEventThread->onScreenAcquired();
4069 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004070 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004071 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004072
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004073 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004074 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004075 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004076
4077 struct sched_param param = {0};
4078 param.sched_priority = 1;
4079 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4080 ALOGW("Couldn't set SCHED_FIFO on display on");
4081 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004082 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004083 // Turn off the display
4084 struct sched_param param = {0};
4085 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4086 ALOGW("Couldn't set SCHED_OTHER on display off");
4087 }
4088
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004089 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004090 if (mUseScheduler) {
4091 mScheduler->disableHardwareVsync(true);
4092 } else {
4093 disableHardwareVsync(true); // also cancels any in-progress resync
4094 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004095 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004096 if (mUseScheduler) {
4097 mScheduler->onScreenReleased(mAppConnectionHandle);
4098 } else {
4099 mEventThread->onScreenReleased();
4100 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004101 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004102
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004103 getHwComposer().setPowerMode(type, mode);
4104 mVisibleRegionsDirty = true;
4105 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004106 } else if (mode == HWC_POWER_MODE_DOZE ||
4107 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004108 // Update display while dozing
4109 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004110 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004111 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004112 if (mUseScheduler) {
4113 mScheduler->onScreenAcquired(mAppConnectionHandle);
4114 } else {
4115 mEventThread->onScreenAcquired();
4116 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004117 resyncToHardwareVsync(true);
4118 }
4119 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4120 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004121 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004122 if (mUseScheduler) {
4123 mScheduler->disableHardwareVsync(true);
4124 } else {
4125 disableHardwareVsync(true); // also cancels any in-progress resync
4126 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004127 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004128 if (mUseScheduler) {
4129 mScheduler->onScreenReleased(mAppConnectionHandle);
4130 } else {
4131 mEventThread->onScreenReleased();
4132 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004133 }
4134 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004135 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004136 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004137 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004138 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004139
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004140 if (display->isPrimary()) {
4141 mTimeStats.setPowerMode(mode);
4142 }
4143
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004144 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004145}
4146
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004147void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004148 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004149 const auto display = getDisplayDevice(displayToken);
4150 if (!display) {
4151 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4152 displayToken.get());
4153 } else if (display->isVirtual()) {
4154 ALOGW("Attempt to set power mode %d for virtual display", mode);
4155 } else {
4156 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004157 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004158 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004159}
4160
4161// ---------------------------------------------------------------------------
4162
Lloyd Pique755e3192018-01-31 16:46:15 -08004163status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4164 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004165 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004166
Mathias Agopianbd115332013-04-18 16:41:04 -07004167 IPCThreadState* ipc = IPCThreadState::self();
4168 const int pid = ipc->getCallingPid();
4169 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004170
Mathias Agopianbd115332013-04-18 16:41:04 -07004171 if ((uid != AID_SHELL) &&
4172 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004173 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004174 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004175 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004176 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004177 // (this would indicate SF is stuck, but we want to be able to
4178 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004179 status_t err = mStateLock.timedLock(s2ns(1));
4180 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004181 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004182 result.appendFormat(
4183 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4184 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004185 }
4186
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004187 bool dumpAll = true;
4188 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004189 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004190
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004191 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004192 if ((index < numArgs) &&
4193 (args[index] == String16("--list"))) {
4194 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004195 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004196 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004197 }
4198
4199 if ((index < numArgs) &&
4200 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004201 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004202 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004203 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004204 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004205
4206 if ((index < numArgs) &&
4207 (args[index] == String16("--latency-clear"))) {
4208 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004209 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004210 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004211 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004212
4213 if ((index < numArgs) &&
4214 (args[index] == String16("--dispsync"))) {
4215 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004216 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004217 dumpAll = false;
4218 }
Dan Stozab90cf072015-03-05 11:05:59 -08004219
4220 if ((index < numArgs) &&
4221 (args[index] == String16("--static-screen"))) {
4222 index++;
4223 dumpStaticScreenStats(result);
4224 dumpAll = false;
4225 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004226
4227 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004228 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004229 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004230 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004231 dumpAll = false;
4232 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004233
4234 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4235 index++;
4236 dumpWideColorInfo(result);
4237 dumpAll = false;
4238 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004239
4240 if ((index < numArgs) &&
4241 (args[index] == String16("--enable-layer-stats"))) {
4242 index++;
4243 mLayerStats.enable();
4244 dumpAll = false;
4245 }
4246
4247 if ((index < numArgs) &&
4248 (args[index] == String16("--disable-layer-stats"))) {
4249 index++;
4250 mLayerStats.disable();
4251 dumpAll = false;
4252 }
4253
4254 if ((index < numArgs) &&
4255 (args[index] == String16("--clear-layer-stats"))) {
4256 index++;
4257 mLayerStats.clear();
4258 dumpAll = false;
4259 }
4260
4261 if ((index < numArgs) &&
4262 (args[index] == String16("--dump-layer-stats"))) {
4263 index++;
4264 mLayerStats.dump(result);
4265 dumpAll = false;
4266 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004267
4268 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004269 (args[index] == String16("--frame-composition"))) {
4270 index++;
4271 dumpFrameCompositionInfo(result);
4272 dumpAll = false;
4273 }
4274
4275 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004276 (args[index] == String16("--display-identification"))) {
4277 index++;
4278 dumpDisplayIdentificationData(result);
4279 dumpAll = false;
4280 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004281
4282 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4283 index++;
4284 mTimeStats.parseArgs(asProto, args, index, result);
4285 dumpAll = false;
4286 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004287 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004288
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004289 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004290 if (asProto) {
4291 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4292 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4293 } else {
4294 dumpAllLocked(args, index, result);
4295 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004296 }
4297
Mathias Agopian9795c422009-08-26 16:36:26 -07004298 if (locked) {
4299 mStateLock.unlock();
4300 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004301 }
4302 write(fd, result.string(), result.size());
4303 return NO_ERROR;
4304}
4305
Dan Stozac7014012014-02-14 15:03:43 -08004306void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4307 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004308{
Robert Carr2047fae2016-11-28 14:09:09 -08004309 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004310 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004311 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004312}
4313
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004314void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004315 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004316{
4317 String8 name;
4318 if (index < args.size()) {
4319 name = String8(args[index]);
4320 index++;
4321 }
4322
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004323 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4324 getHwComposer().isConnected(displayId)) {
4325 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4326 const nsecs_t period = activeConfig->getVsyncPeriod();
4327 result.appendFormat("%" PRId64 "\n", period);
4328 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004329
4330 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004331 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004332 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004333 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004334 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004335 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004336 }
Robert Carr2047fae2016-11-28 14:09:09 -08004337 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004338 }
4339}
4340
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004341void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004342 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004343{
4344 String8 name;
4345 if (index < args.size()) {
4346 name = String8(args[index]);
4347 index++;
4348 }
4349
Robert Carr2047fae2016-11-28 14:09:09 -08004350 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004351 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004352 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004353 }
Robert Carr2047fae2016-11-28 14:09:09 -08004354 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004355
Svetoslavd85084b2014-03-20 10:28:31 -07004356 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004357}
4358
Jamie Gennis6547ff42013-07-16 20:12:42 -07004359// This should only be called from the main thread. Otherwise it would need
4360// the lock and should use mCurrentState rather than mDrawingState.
4361void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004362 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004363 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004364 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004365
4366 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4367}
4368
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004369void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004370{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004371 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004372
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004373 if (isLayerTripleBufferingDisabled())
4374 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004375
4376 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004377 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004378 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004379 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004380 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4381 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004382 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004383}
4384
Dan Stozab90cf072015-03-05 11:05:59 -08004385void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4386{
4387 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004388 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4389 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004390 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004391 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004392 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4393 b + 1, bucketTimeSec, percent);
4394 }
David Sodman4a36e932017-11-07 14:29:47 -08004395 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004396 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004397 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004398 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004399 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004400}
4401
Dan Stozae77c7662016-05-13 11:37:28 -07004402void SurfaceFlinger::recordBufferingStats(const char* layerName,
4403 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004404 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4405 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004406 for (const auto& segment : history) {
4407 if (!segment.usedThirdBuffer) {
4408 stats.twoBufferTime += segment.totalTime;
4409 }
4410 if (segment.occupancyAverage < 1.0f) {
4411 stats.doubleBufferedTime += segment.totalTime;
4412 } else if (segment.occupancyAverage < 2.0f) {
4413 stats.tripleBufferedTime += segment.totalTime;
4414 }
4415 ++stats.numSegments;
4416 stats.totalTime += segment.totalTime;
4417 }
4418}
4419
Brian Andersond6927fb2016-07-23 23:37:30 -07004420void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4421 result.appendFormat("Layer frame timestamps:\n");
4422
4423 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4424 const size_t count = currentLayers.size();
4425 for (size_t i=0 ; i<count ; i++) {
4426 currentLayers[i]->dumpFrameEvents(result);
4427 }
4428}
4429
Dan Stozae77c7662016-05-13 11:37:28 -07004430void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4431 result.append("Buffering stats:\n");
4432 result.append(" [Layer name] <Active time> <Two buffer> "
4433 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004434 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004435 typedef std::tuple<std::string, float, float, float> BufferTuple;
4436 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004437 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004438 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004439 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004440 if (stats.numSegments == 0) {
4441 continue;
4442 }
4443 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4444 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4445 stats.totalTime;
4446 float doubleBufferRatio = static_cast<float>(
4447 stats.doubleBufferedTime) / stats.totalTime;
4448 float tripleBufferRatio = static_cast<float>(
4449 stats.tripleBufferedTime) / stats.totalTime;
4450 sorted.insert({activeTime, {name, twoBufferRatio,
4451 doubleBufferRatio, tripleBufferRatio}});
4452 }
4453 for (const auto& sortedPair : sorted) {
4454 float activeTime = sortedPair.first;
4455 const BufferTuple& values = sortedPair.second;
4456 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4457 std::get<0>(values).c_str(), activeTime,
4458 std::get<1>(values), std::get<2>(values),
4459 std::get<3>(values));
4460 }
4461 result.append("\n");
4462}
4463
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004464void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004465 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004466 const int32_t displayId = display->getId();
4467 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4468 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004469 continue;
4470 }
4471
Dominik Laskowski7e045462018-05-30 13:02:02 -07004472 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004473 uint8_t port;
4474 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004475 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004476 result.append("no identification data\n");
4477 continue;
4478 }
4479
4480 if (!isEdid(data)) {
4481 result.append("unknown identification data: ");
4482 for (uint8_t byte : data) {
4483 result.appendFormat("%x ", byte);
4484 }
4485 result.append("\n");
4486 continue;
4487 }
4488
4489 const auto edid = parseEdid(data);
4490 if (!edid) {
4491 result.append("invalid EDID: ");
4492 for (uint8_t byte : data) {
4493 result.appendFormat("%x ", byte);
4494 }
4495 result.append("\n");
4496 continue;
4497 }
4498
4499 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4500 result.append(edid->displayName.data(), edid->displayName.length());
4501 result.append("\"\n");
4502 }
4503 result.append("\n");
4504}
4505
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004506void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004507 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4508 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004509 result.appendFormat("DisplayColorSetting: %s\n",
4510 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004511
4512 // TODO: print out if wide-color mode is active or not
4513
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004514 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004515 const int32_t displayId = display->getId();
4516 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004517 continue;
4518 }
4519
Dominik Laskowski7e045462018-05-30 13:02:02 -07004520 result.appendFormat("Display %d color modes:\n", displayId);
4521 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004522 for (auto&& mode : modes) {
4523 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4524 }
4525
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004526 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004527 result.appendFormat(" Current color mode: %s (%d)\n",
4528 decodeColorMode(currentMode).c_str(), currentMode);
4529 }
4530 result.append("\n");
4531}
4532
David Sodman7e4ae112018-02-09 15:02:28 -08004533void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4534 std::string stringResult;
4535
4536 for (const auto& [token, display] : mDisplays) {
4537 const auto displayId = display->getId();
4538 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
4539 continue;
4540 }
4541
4542 const auto& compositionInfoIt = getBE().mEndOfFrameCompositionInfo.find(displayId);
4543 if (compositionInfoIt == getBE().mEndOfFrameCompositionInfo.end()) {
4544 break;
4545 }
4546 const auto& compositionInfoList = compositionInfoIt->second;
4547 stringResult += base::StringPrintf("Display: %d\n", displayId);
4548 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4549 for (const auto& compositionInfo : compositionInfoList) {
4550 compositionInfo.dump(stringResult, nullptr);
4551 stringResult += base::StringPrintf("\n");
4552 }
4553 }
4554
4555 result.append(stringResult.c_str());
4556}
4557
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004558LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004559 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004560 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4561 const State& state = useDrawing ? mDrawingState : mCurrentState;
4562 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004563 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004564 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004565 });
4566
4567 return layersProto;
4568}
4569
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004570LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004571 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004572
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004573 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004574 resolution->set_w(display.getWidth());
4575 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004576
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004577 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4578 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4579 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004580
Dominik Laskowski7e045462018-05-30 13:02:02 -07004581 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004582 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004583 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004584 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004585 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004586 }
4587 });
4588
4589 return layersProto;
4590}
4591
Mathias Agopian74d211a2013-04-22 16:55:35 +02004592void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4593 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004594{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004595 bool colorize = false;
4596 if (index < args.size()
4597 && (args[index] == String16("--color"))) {
4598 colorize = true;
4599 index++;
4600 }
4601
4602 Colorizer colorizer(colorize);
4603
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004604 // figure out if we're stuck somewhere
4605 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004606 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004607 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4608
4609 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004610 * Dump library configuration.
4611 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004612
4613 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004614 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004615 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004616 appendSfConfigString(result);
4617 appendUiConfigString(result);
4618 appendGuiConfigString(result);
4619 result.append("\n");
4620
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004621 result.append("\nDisplay identification data:\n");
4622 dumpDisplayIdentificationData(result);
4623
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004624 result.append("\nWide-Color information:\n");
4625 dumpWideColorInfo(result);
4626
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004627 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004628 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004629 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004630 result.append(SyncFeatures::getInstance().toString());
4631 result.append("\n");
4632
Andy McFadden41d67d72014-04-25 16:58:34 -07004633 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004634 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004635 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004636
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004637 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4638 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004639 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4640 getHwComposer().isConnected(displayId)) {
4641 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004642 result.appendFormat("Display %d: "
4643 "app phase %" PRId64 " ns, "
4644 "sf phase %" PRId64 " ns, "
4645 "early app phase %" PRId64 " ns, "
4646 "early sf phase %" PRId64 " ns, "
4647 "early app gl phase %" PRId64 " ns, "
4648 "early sf gl phase %" PRId64 " ns, "
4649 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4650 displayId,
4651 vsyncPhaseOffsetNs,
4652 sfVsyncPhaseOffsetNs,
4653 appEarlyOffset,
4654 sfEarlyOffset,
4655 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004656 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004657 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004658 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004659 result.append("\n");
4660
Dan Stozab90cf072015-03-05 11:05:59 -08004661 // Dump static screen stats
4662 result.append("\n");
4663 dumpStaticScreenStats(result);
4664 result.append("\n");
4665
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004666 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4667
Dan Stozae77c7662016-05-13 11:37:28 -07004668 dumpBufferingStats(result);
4669
Andy McFadden4803b742012-09-24 19:07:20 -07004670 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004671 * Dump the visible layer list
4672 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004673 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004674 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004675 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4676 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004677 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004678
Chia-I Wu2f884132018-09-13 15:17:58 -07004679 {
4680 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4681 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4682 result.append(LayerProtoParser::layerTreeToString(layerTree).c_str());
4683 result.append("\n");
4684 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004685
David Sodman7e4ae112018-02-09 15:02:28 -08004686 result.append("\nFrame-Composition information:\n");
4687 dumpFrameCompositionInfo(result);
4688 result.append("\n");
4689
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004690 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004691 * Dump Display state
4692 */
4693
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004694 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004695 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004696 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004697 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004698 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004699 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004700 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004701
4702 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004703 * Dump SurfaceFlinger global state
4704 */
4705
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004706 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004707 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004708 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004709
Mathias Agopian888c8222012-08-04 21:10:38 -07004710 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004711 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004712
David Sodmanbc815282017-11-05 18:57:52 -08004713 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004714
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004715 if (display) {
4716 display->undefinedRegion.dump(result, "undefinedRegion");
4717 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4718 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004719 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004720 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004721 " gpu_to_cpu_unsupported : %d\n",
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004722 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004723
4724 if (display) {
4725 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4726 result.appendFormat(" refresh-rate : %f fps\n"
4727 " x-dpi : %f\n"
4728 " y-dpi : %f\n",
4729 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4730 activeConfig->getDpiY());
4731 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004732
Mathias Agopian74d211a2013-04-22 16:55:35 +02004733 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004734 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004735
Ana Krulec98b5b242018-08-10 15:03:23 -07004736 result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004737 /*
4738 * VSYNC state
4739 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004740 if (mUseScheduler) {
4741 mScheduler->dump(mAppConnectionHandle, result);
4742 } else {
4743 mEventThread->dump(result);
4744 }
Dan Stozae22aec72016-08-01 13:20:59 -07004745 result.append("\n");
4746
4747 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004748 * Tracing state
4749 */
4750 mTracing.dump(result);
4751 result.append("\n");
4752
4753 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004754 * HWC layer minidump
4755 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004756 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004757 const int32_t displayId = display->getId();
4758 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004759 continue;
4760 }
4761
Dominik Laskowski7e045462018-05-30 13:02:02 -07004762 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004763 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004764 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004765 result.append("\n");
4766 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004767
4768 /*
4769 * Dump HWComposer state
4770 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004771 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004772 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004773 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004774 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004775 result.appendFormat(" h/w composer %s\n",
4776 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004777 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004778
4779 /*
4780 * Dump gralloc state
4781 */
4782 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4783 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004784
4785 /*
4786 * Dump VrFlinger state if in use.
4787 */
4788 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4789 result.append("VrFlinger state:\n");
4790 result.append(mVrFlinger->Dump().c_str());
4791 result.append("\n");
4792 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004793}
4794
Dominik Laskowski7e045462018-05-30 13:02:02 -07004795const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004796 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004797 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004798 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004799 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004800 }
4801 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004802
4803 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4804 static const Vector<sp<Layer>> empty;
4805 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004806}
4807
Keun young Park63f165f2012-08-31 10:53:36 -07004808bool SurfaceFlinger::startDdmConnection()
4809{
4810 void* libddmconnection_dso =
4811 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4812 if (!libddmconnection_dso) {
4813 return false;
4814 }
4815 void (*DdmConnection_start)(const char* name);
4816 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004817 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004818 if (!DdmConnection_start) {
4819 dlclose(libddmconnection_dso);
4820 return false;
4821 }
4822 (*DdmConnection_start)(getServiceName());
4823 return true;
4824}
4825
Chia-I Wu28f320b2018-05-03 11:02:56 -07004826void SurfaceFlinger::updateColorMatrixLocked() {
4827 mat4 colorMatrix;
4828 if (mGlobalSaturationFactor != 1.0f) {
4829 // Rec.709 luma coefficients
4830 float3 luminance{0.213f, 0.715f, 0.072f};
4831 luminance *= 1.0f - mGlobalSaturationFactor;
4832 mat4 saturationMatrix = mat4(
4833 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4834 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4835 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4836 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4837 );
4838 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4839 } else {
4840 colorMatrix = mClientColorMatrix * mDaltonizer();
4841 }
4842
4843 if (mCurrentState.colorMatrix != colorMatrix) {
4844 mCurrentState.colorMatrix = colorMatrix;
4845 mCurrentState.colorMatrixChanged = true;
4846 setTransactionFlags(eTransactionNeeded);
4847 }
4848}
4849
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004850status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004851#pragma clang diagnostic push
4852#pragma clang diagnostic error "-Wswitch-enum"
4853 switch (static_cast<ISurfaceComposerTag>(code)) {
4854 // These methods should at minimum make sure that the client requested
4855 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004856 case BOOT_FINISHED:
4857 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004858 case CREATE_CONNECTION:
4859 case CREATE_DISPLAY:
4860 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004861 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004862 case GET_ACTIVE_COLOR_MODE:
4863 case GET_ANIMATION_FRAME_STATS:
4864 case GET_HDR_CAPABILITIES:
4865 case SET_ACTIVE_CONFIG:
4866 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004867 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004868 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004869 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4870 IPCThreadState* ipc = IPCThreadState::self();
4871 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4872 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004873 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004874 }
Robert Carr1db73f62016-12-21 12:58:51 -08004875 return OK;
4876 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004877 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004878 IPCThreadState* ipc = IPCThreadState::self();
4879 const int pid = ipc->getCallingPid();
4880 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004881 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4882 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004883 return PERMISSION_DENIED;
4884 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004885 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004886 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004887 // Used by apps to hook Choreographer to SurfaceFlinger.
4888 case CREATE_DISPLAY_EVENT_CONNECTION:
4889 // The following calls are currently used by clients that do not
4890 // request necessary permissions. However, they do not expose any secret
4891 // information, so it is OK to pass them.
4892 case AUTHENTICATE_SURFACE:
4893 case GET_ACTIVE_CONFIG:
4894 case GET_BUILT_IN_DISPLAY:
4895 case GET_DISPLAY_COLOR_MODES:
4896 case GET_DISPLAY_CONFIGS:
4897 case GET_DISPLAY_STATS:
4898 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4899 // Calling setTransactionState is safe, because you need to have been
4900 // granted a reference to Client* and Handle* to do anything with it.
4901 case SET_TRANSACTION_STATE:
4902 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004903 case CREATE_SCOPED_CONNECTION:
4904 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004905 return OK;
4906 }
4907 case CAPTURE_LAYERS:
4908 case CAPTURE_SCREEN: {
4909 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004910 IPCThreadState* ipc = IPCThreadState::self();
4911 const int pid = ipc->getCallingPid();
4912 const int uid = ipc->getCallingUid();
4913 if ((uid != AID_GRAPHICS) &&
4914 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4915 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4916 return PERMISSION_DENIED;
4917 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004918 return OK;
4919 }
4920 // The following codes are deprecated and should never be allowed to access SF.
4921 case CONNECT_DISPLAY_UNUSED:
4922 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4923 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4924 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004925 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004926 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004927
4928 // These codes are used for the IBinder protocol to either interrogate the recipient
4929 // side of the transaction for its canonical interface descriptor or to dump its state.
4930 // We let them pass by default.
4931 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4932 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4933 code == IBinder::SYSPROPS_TRANSACTION) {
4934 return OK;
4935 }
4936 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4937 // in onTransact verifies that the user is root, and has access to use SF.
4938 if (code >= 1000 && code <= 1029) {
4939 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4940 return OK;
4941 }
4942 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4943 return PERMISSION_DENIED;
4944#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004945}
4946
Ana Krulec13be8ad2018-08-21 02:43:56 +00004947status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4948 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004949 status_t credentialCheck = CheckTransactCodeCredentials(code);
4950 if (credentialCheck != OK) {
4951 return credentialCheck;
4952 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004953
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004954 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4955 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004956 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004957 IPCThreadState* ipc = IPCThreadState::self();
4958 const int uid = ipc->getCallingUid();
4959 if (CC_UNLIKELY(uid != AID_SYSTEM
4960 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004961 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004962 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004963 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004964 return PERMISSION_DENIED;
4965 }
4966 int n;
4967 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004968 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004969 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004970 return NO_ERROR;
4971 case 1002: // SHOW_UPDATES
4972 n = data.readInt32();
4973 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004974 invalidateHwcGeometry();
4975 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004976 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004977 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004978 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004979 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004980 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004981 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004982 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004983 setTransactionFlags(
4984 eTransactionNeeded|
4985 eDisplayTransactionNeeded|
4986 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004987 return NO_ERROR;
4988 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004989 case 1006:{ // send empty update
4990 signalRefresh();
4991 return NO_ERROR;
4992 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004993 case 1008: // toggle use of hw composer
4994 n = data.readInt32();
4995 mDebugDisableHWC = n ? 1 : 0;
4996 invalidateHwcGeometry();
4997 repaintEverything();
4998 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004999 case 1009: // toggle use of transform hint
5000 n = data.readInt32();
5001 mDebugDisableTransformHint = n ? 1 : 0;
5002 invalidateHwcGeometry();
5003 repaintEverything();
5004 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005005 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005006 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005007 reply->writeInt32(0);
5008 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005009 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005010 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005011 return NO_ERROR;
5012 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005013 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005014 if (!display) {
5015 return NAME_NOT_FOUND;
5016 }
5017
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005018 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005019 return NO_ERROR;
5020 }
5021 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005022 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005023 // daltonize
5024 n = data.readInt32();
5025 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005026 case 1:
5027 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5028 break;
5029 case 2:
5030 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5031 break;
5032 case 3:
5033 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5034 break;
5035 default:
5036 mDaltonizer.setType(ColorBlindnessType::None);
5037 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005038 }
5039 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005040 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005041 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005042 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005043 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005044
5045 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005046 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005047 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005048 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005049 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005050 // apply a color matrix
5051 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005052 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005053 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005054 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005055 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005056 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005057 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005058 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005059 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005060 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005061 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005062
5063 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5064 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005065 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005066 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5067 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5068 }
5069
Chia-I Wu28f320b2018-05-03 11:02:56 -07005070 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005071 return NO_ERROR;
5072 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005073 // This is an experimental interface
5074 // Needs to be shifted to proper binder interface when we productize
5075 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005076 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005077 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005078 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005079 return NO_ERROR;
5080 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005081 case 1017: {
5082 n = data.readInt32();
5083 mForceFullDamage = static_cast<bool>(n);
5084 return NO_ERROR;
5085 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005086 case 1018: { // Modify Choreographer's phase offset
5087 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005088 if (mUseScheduler) {
5089 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5090 } else {
5091 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5092 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005093 return NO_ERROR;
5094 }
5095 case 1019: { // Modify SurfaceFlinger's phase offset
5096 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005097 if (mUseScheduler) {
5098 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5099 } else {
5100 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5101 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005102 return NO_ERROR;
5103 }
Irvel468051e2016-06-13 16:44:44 -07005104 case 1020: { // Layer updates interceptor
5105 n = data.readInt32();
5106 if (n) {
5107 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005108 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005109 }
5110 else{
5111 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005112 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005113 }
5114 return NO_ERROR;
5115 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005116 case 1021: { // Disable HWC virtual displays
5117 n = data.readInt32();
5118 mUseHwcVirtualDisplays = !n;
5119 return NO_ERROR;
5120 }
Romain Guy0147a172017-06-01 13:53:56 -07005121 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005122 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005123 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005124
Chia-I Wu28f320b2018-05-03 11:02:56 -07005125 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005126 return NO_ERROR;
5127 }
Romain Guy54f154a2017-10-24 21:40:32 +01005128 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005129 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005130 invalidateHwcGeometry();
5131 repaintEverything();
5132 return NO_ERROR;
5133 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005134 // TODO(b/111505327): Find out whether the usage of 1024 can switch to 1030,
5135 // deprecate 1024 if they can.
5136 case 1024: { // Does device have wide color gamut display?
Romain Guy54f154a2017-10-24 21:40:32 +01005137 reply->writeBool(hasWideColorDisplay);
5138 return NO_ERROR;
5139 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005140 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005141 n = data.readInt32();
5142 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005143 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005144 mTracing.enable();
5145 doTracing("tracing.enable");
5146 reply->writeInt32(NO_ERROR);
5147 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005148 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005149 status_t err = mTracing.disable();
5150 reply->writeInt32(err);
5151 }
5152 return NO_ERROR;
5153 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005154 case 1026: { // Get layer tracing status
5155 reply->writeBool(mTracing.isEnabled());
5156 return NO_ERROR;
5157 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005158 // Is a DisplayColorSetting supported?
5159 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005160 const auto display = getDefaultDisplayDevice();
5161 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005162 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005163 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005164
5165 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5166 switch (setting) {
5167 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005168 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005169 break;
5170 case DisplayColorSetting::UNMANAGED:
5171 reply->writeBool(true);
5172 break;
5173 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005174 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005175 break;
5176 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005177 reply->writeBool(
5178 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005179 break;
5180 }
5181 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005182 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005183 // Is VrFlinger active?
5184 case 1028: {
5185 Mutex::Autolock _l(mStateLock);
5186 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5187 return NO_ERROR;
5188 }
David Sodman6d46c1e2018-07-13 12:59:48 -07005189 case 1029: {
5190 // Code 1029 is an experimental feature that allows applications to
5191 // simulate a high frequency panel by setting a multiplier and divisor
5192 // on the VSYNC-sf clock. If either the multiplier or divisor are
David Sodman44b5de02018-08-21 16:28:53 -07005193 // 0, then the code simply return the current multiplier and divisor.
5194 HWC2::Device::FrequencyScaler frequencyScaler;
5195 frequencyScaler.multiplier = data.readInt32();
5196 frequencyScaler.divisor = data.readInt32();
David Sodman6d46c1e2018-07-13 12:59:48 -07005197
David Sodman44b5de02018-08-21 16:28:53 -07005198 if ((frequencyScaler.multiplier == 0) || (frequencyScaler.divisor == 0)) {
5199 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5200 reply->writeInt32(frequencyScaler.multiplier);
5201 reply->writeInt32(frequencyScaler.divisor);
5202 return NO_ERROR;
David Sodman6d46c1e2018-07-13 12:59:48 -07005203 }
5204
David Sodman44b5de02018-08-21 16:28:53 -07005205 if ((frequencyScaler.multiplier == 1) && (frequencyScaler.divisor == 1)) {
Ana Krulece588e312018-09-18 12:32:24 -07005206 if (mUseScheduler) {
5207 mScheduler->enableHardwareVsync();
5208 } else {
5209 enableHardwareVsync();
5210 }
David Sodman6d46c1e2018-07-13 12:59:48 -07005211 } else {
Ana Krulece588e312018-09-18 12:32:24 -07005212 if (mUseScheduler) {
5213 mScheduler->disableHardwareVsync(true);
5214 } else {
5215 disableHardwareVsync(true);
5216 }
David Sodman6d46c1e2018-07-13 12:59:48 -07005217 }
David Sodman44b5de02018-08-21 16:28:53 -07005218 mPrimaryDispSync->scalePeriod(frequencyScaler);
5219 getBE().mHwc->setDisplayFrequencyScaleParameters(frequencyScaler);
David Sodman6d46c1e2018-07-13 12:59:48 -07005220
David Sodman44b5de02018-08-21 16:28:53 -07005221 ATRACE_INT("PeriodMultiplier", frequencyScaler.multiplier);
5222 ATRACE_INT("PeriodDivisor", frequencyScaler.divisor);
5223
5224 const hwc2_display_t hwcDisplayId = getBE().mHwc->getActiveConfig(
5225 DisplayDevice::DISPLAY_PRIMARY)->getDisplayId();
5226
5227 onHotplugReceived(getBE().mComposerSequenceId,
5228 hwcDisplayId, HWC2::Connection::Disconnected);
5229 onHotplugReceived(getBE().mComposerSequenceId,
5230 hwcDisplayId, HWC2::Connection::Connected);
5231 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5232 reply->writeInt32(frequencyScaler.multiplier);
5233 reply->writeInt32(frequencyScaler.divisor);
5234
David Sodman6d46c1e2018-07-13 12:59:48 -07005235 return NO_ERROR;
5236 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005237 // Is device color managed?
5238 case 1030: {
5239 reply->writeBool(useColorManagement);
5240 return NO_ERROR;
5241 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005242 }
5243 }
5244 return err;
5245}
5246
Steven Thomas6d8110b2017-08-31 18:24:21 -07005247void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005248 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005249 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005250}
5251
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005252// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5253class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005254public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005255 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5256 ~WindowDisconnector() {
5257 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005258 }
5259
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005260private:
5261 ANativeWindow* mWindow;
5262 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005263};
5264
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005265status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
5266 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005267 uint32_t reqWidth, uint32_t reqHeight,
5268 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005269 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005270 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005271
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005272 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005273
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005274 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5275
Chia-I Wu20261cb2018-08-23 12:55:44 -07005276 sp<DisplayDevice> display;
5277 {
5278 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005279
Chia-I Wu20261cb2018-08-23 12:55:44 -07005280 display = getDisplayDeviceLocked(displayToken);
5281 if (!display) return BAD_VALUE;
5282
Chia-I Wu8730ba82018-08-29 09:25:59 -07005283 // ignore sourceCrop (i.e., use the projected logical display
5284 // viewport) until the framework is fixed
5285 sourceCrop.clear();
Chia-I Wucb023152018-08-28 12:57:23 -07005286
5287 // set the requested width/height to the logical display viewport size
5288 // by default
5289 if (reqWidth == 0 || reqHeight == 0) {
5290 reqWidth = uint32_t(display->getViewport().width());
5291 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005292 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005293 }
5294
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005295 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005296
5297 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005298 display, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005299 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005300}
5301
5302status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08005303 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005304 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005305 ATRACE_CALL();
5306
5307 class LayerRenderArea : public RenderArea {
5308 public:
Robert Carr578038f2018-03-09 12:25:24 -08005309 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
5310 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
Chia-I Wu9d1abea2018-08-23 13:44:43 -07005311 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08005312 mLayer(layer),
5313 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005314 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005315 mFlinger(flinger),
5316 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005317 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005318 Rect getBounds() const override {
5319 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005320 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005321 }
Marissa Wall61c58622018-07-18 10:12:20 -07005322 int getHeight() const override {
5323 return mLayer->getActiveHeight(mLayer->getDrawingState());
5324 }
5325 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005326 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005327 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005328 Rect getSourceCrop() const override {
5329 if (mCrop.isEmpty()) {
5330 return getBounds();
5331 } else {
5332 return mCrop;
5333 }
5334 }
Robert Carr578038f2018-03-09 12:25:24 -08005335 class ReparentForDrawing {
5336 public:
5337 const sp<Layer>& oldParent;
5338 const sp<Layer>& newParent;
5339
5340 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5341 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005342 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005343 }
Robert Carr15eae092018-03-23 13:43:53 -07005344 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005345 };
5346
5347 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005348 const Rect sourceCrop = getSourceCrop();
5349 // no need to check rotation because there is none
5350 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5351 sourceCrop.height() != getReqHeight();
5352
Robert Carr578038f2018-03-09 12:25:24 -08005353 if (!mChildrenOnly) {
5354 mTransform = mLayer->getTransform().inverse();
5355 drawLayers();
5356 } else {
5357 Rect bounds = getBounds();
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005358 screenshotParentLayer = new ContainerLayer(
5359 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5360 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005361
5362 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5363 drawLayers();
5364 }
5365 }
chaviwa76b2712017-09-20 12:02:26 -07005366
chaviwa76b2712017-09-20 12:02:26 -07005367 private:
chaviw7206d492017-11-10 16:16:12 -08005368 const sp<Layer> mLayer;
5369 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005370
5371 // In the "childrenOnly" case we reparent the children to a screenshot
5372 // layer which has no properties set and which does not draw.
5373 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005374 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005375 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005376
5377 SurfaceFlinger* mFlinger;
5378 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005379 };
5380
5381 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5382 auto parent = layerHandle->owner.promote();
5383
Rob Carr4bba3702018-10-08 21:53:30 +00005384 if (parent == nullptr || parent->isPendingRemoval()) {
chaviw7206d492017-11-10 16:16:12 -08005385 ALOGE("captureLayers called with a removed parent");
5386 return NAME_NOT_FOUND;
5387 }
5388
Robert Carr578038f2018-03-09 12:25:24 -08005389 const int uid = IPCThreadState::self()->getCallingUid();
5390 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5391 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5392 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5393 return PERMISSION_DENIED;
5394 }
5395
chaviw7206d492017-11-10 16:16:12 -08005396 Rect crop(sourceCrop);
5397 if (sourceCrop.width() <= 0) {
5398 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005399 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005400 }
5401
5402 if (sourceCrop.height() <= 0) {
5403 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005404 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005405 }
5406
5407 int32_t reqWidth = crop.width() * frameScale;
5408 int32_t reqHeight = crop.height() * frameScale;
5409
Chia-I Wu20261cb2018-08-23 12:55:44 -07005410 // really small crop or frameScale
5411 if (reqWidth <= 0) {
5412 reqWidth = 1;
5413 }
5414 if (reqHeight <= 0) {
5415 reqHeight = 1;
5416 }
5417
Robert Carr578038f2018-03-09 12:25:24 -08005418 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005419
Robert Carr578038f2018-03-09 12:25:24 -08005420 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005421 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5422 if (!layer->isVisible()) {
5423 return;
Robert Carr578038f2018-03-09 12:25:24 -08005424 } else if (childrenOnly && layer == parent.get()) {
5425 return;
chaviwa76b2712017-09-20 12:02:26 -07005426 }
5427 visitor(layer);
5428 });
5429 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005430 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005431}
5432
5433status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5434 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005435 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005436 bool useIdentityTransform) {
5437 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005438
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005439 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5440 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5441 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5442 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005443
5444 // This mutex protects syncFd and captureResult for communication of the return values from the
5445 // main thread back to this Binder thread
5446 std::mutex captureMutex;
5447 std::condition_variable captureCondition;
5448 std::unique_lock<std::mutex> captureLock(captureMutex);
5449 int syncFd = -1;
5450 std::optional<status_t> captureResult;
5451
Robert Carr03480e22018-01-04 16:02:06 -08005452 const int uid = IPCThreadState::self()->getCallingUid();
5453 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5454
Dominik Laskowski8c001672018-05-30 16:52:06 -07005455 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005456 // If there is a refresh pending, bug out early and tell the binder thread to try again
5457 // after the refresh.
5458 if (mRefreshPending) {
5459 ATRACE_NAME("Skipping screenshot for now");
5460 std::unique_lock<std::mutex> captureLock(captureMutex);
5461 captureResult = std::make_optional<status_t>(EAGAIN);
5462 captureCondition.notify_one();
5463 return;
5464 }
5465
5466 status_t result = NO_ERROR;
5467 int fd = -1;
5468 {
5469 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005470 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005471 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5472 useIdentityTransform, forSystem, &fd);
5473 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005474 }
5475
5476 {
5477 std::unique_lock<std::mutex> captureLock(captureMutex);
5478 syncFd = fd;
5479 captureResult = std::make_optional<status_t>(result);
5480 captureCondition.notify_one();
5481 }
5482 });
5483
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005484 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005485 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005486 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005487 while (*captureResult == EAGAIN) {
5488 captureResult.reset();
5489 result = postMessageAsync(message);
5490 if (result != NO_ERROR) {
5491 return result;
5492 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005493 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005494 }
5495 result = *captureResult;
5496 }
5497
5498 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005499 sync_wait(syncFd, -1);
5500 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005501 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005502
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005503 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005504}
5505
chaviwa76b2712017-09-20 12:02:26 -07005506void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005507 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005508 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005509 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005510
Lloyd Pique144e1162017-12-20 16:44:52 -08005511 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005512
chaviwa76b2712017-09-20 12:02:26 -07005513 const auto reqWidth = renderArea.getReqWidth();
5514 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005515 const auto sourceCrop = renderArea.getSourceCrop();
5516 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005517
Chia-I Wu36574d92018-05-16 10:54:36 -07005518 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5519 engine.setOutputDataSpace(Dataspace::SRGB);
5520 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005521
Mathias Agopian180f10d2013-04-10 22:55:41 -07005522 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005523 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005524
5525 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005526 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005527 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005528
chaviw50da5042018-04-09 13:49:37 -07005529 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005530 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005531 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005532
chaviwa76b2712017-09-20 12:02:26 -07005533 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005534 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005535 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005536 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005537 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005538}
5539
chaviwa76b2712017-09-20 12:02:26 -07005540status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5541 TraverseLayersFunction traverseLayers,
5542 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005543 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005544 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005545 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005546 ATRACE_CALL();
5547
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005548 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005549
5550 traverseLayers([&](Layer* layer) {
5551 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5552 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005553
Robert Carr03480e22018-01-04 16:02:06 -08005554 // We allow the system server to take screenshots of secure layers for
5555 // use in situations like the Screen-rotation animation and place
5556 // the impetus on WindowManager to not persist them.
5557 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005558 ALOGW("FB is protected: PERMISSION_DENIED");
5559 return PERMISSION_DENIED;
5560 }
5561
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005562 // this binds the given EGLImage as a framebuffer for the
5563 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005564 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005565 if (bufferBond.getStatus() != NO_ERROR) {
5566 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005567 return INVALID_OPERATION;
5568 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005569
Dan Stozaabcda352017-06-01 14:37:39 -07005570 // this will in fact render into our dequeued buffer
5571 // via an FBO, which means we didn't have to create
5572 // an EGLSurface and therefore we're not
5573 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005574 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005575
Alec Mouri492bc572018-09-11 21:40:04 +00005576 base::unique_fd syncFd = getRenderEngine().flush();
5577 if (syncFd < 0) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005578 getRenderEngine().finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005579 }
Alec Mouri492bc572018-09-11 21:40:04 +00005580 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005581
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005582 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005583}
5584
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005585// ---------------------------------------------------------------------------
5586
Dan Stoza412903f2017-04-27 13:42:17 -07005587void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5588 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005589}
5590
Dan Stoza412903f2017-04-27 13:42:17 -07005591void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5592 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005593}
5594
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005595void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005596 const LayerVector::Visitor& visitor) {
5597 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005598 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005599 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005600 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005601 continue;
5602 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005603 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005604 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005605 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005606 return;
5607 }
chaviwa76b2712017-09-20 12:02:26 -07005608 if (!layer->isVisible()) {
5609 return;
5610 }
5611 visitor(layer);
5612 });
5613 }
5614}
5615
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005616}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005617
Lloyd Pique074e8122018-07-26 12:57:23 -07005618
Mathias Agopian3f844832013-08-07 21:24:32 -07005619#if defined(__gl_h_)
5620#error "don't include gl/gl.h in this file"
5621#endif
5622
5623#if defined(__gl2_h_)
5624#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005625#endif