blob: 9410cdb64c2b609ae9a8fcd9211b6579c8db01e5 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Chia-I Wud49d6692018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070050#include <renderengine/RenderEngine.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070051#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070066#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070067#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020070#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080072#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080073#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070077#include "NativeWindowSurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070081#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070082#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070083#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070084#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070086#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070087#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070088#include "Scheduler/EventControlThread.h"
89#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070090#include "Scheduler/InjectVSyncSource.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070091#include "Scheduler/Scheduler.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070092
Mathias Agopianff2ed702013-09-01 21:36:12 -070093#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070094
David Sodman7e4ae112018-02-09 15:02:28 -080095#include "android-base/stringprintf.h"
96
Jiyong Park4b20c2e2017-01-14 19:45:11 +090097#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080098#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -070099#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800100#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900101#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900102
chaviw1d044282017-09-27 12:19:28 -0700103#include <layerproto/LayerProtoParser.h>
104
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800105#define DISPLAY_COUNT 1
106
107namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700108
Jaesoo Lee43518572017-01-23 19:03:16 +0900109using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900110using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700111using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700112using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700113using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700114using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900115
Steven Thomasb02664d2017-07-26 18:48:28 -0700116namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700117
118#pragma clang diagnostic push
119#pragma clang diagnostic error "-Wswitch-enum"
120
121bool isWideColorMode(const ColorMode colorMode) {
122 switch (colorMode) {
123 case ColorMode::DISPLAY_P3:
124 case ColorMode::ADOBE_RGB:
125 case ColorMode::DCI_P3:
126 case ColorMode::BT2020:
127 case ColorMode::BT2100_PQ:
128 case ColorMode::BT2100_HLG:
129 return true;
130 case ColorMode::NATIVE:
131 case ColorMode::STANDARD_BT601_625:
132 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
133 case ColorMode::STANDARD_BT601_525:
134 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
135 case ColorMode::STANDARD_BT709:
136 case ColorMode::SRGB:
137 return false;
138 }
139 return false;
140}
141
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700142ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
143 switch (rotation) {
144 case ISurfaceComposer::eRotateNone:
145 return ui::Transform::ROT_0;
146 case ISurfaceComposer::eRotate90:
147 return ui::Transform::ROT_90;
148 case ISurfaceComposer::eRotate180:
149 return ui::Transform::ROT_180;
150 case ISurfaceComposer::eRotate270:
151 return ui::Transform::ROT_270;
152 }
153 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
154 return ui::Transform::ROT_0;
155}
156
Peiyong Linfca547f2018-07-09 13:03:33 -0700157#pragma clang diagnostic pop
158
Steven Thomasb02664d2017-07-26 18:48:28 -0700159class ConditionalLock {
160public:
161 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
162 if (lock) {
163 mMutex.lock();
164 }
165 }
166 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
167private:
168 Mutex& mMutex;
169 bool mLocked;
170};
Peiyong Linfca547f2018-07-09 13:03:33 -0700171
Steven Thomasb02664d2017-07-26 18:48:28 -0700172} // namespace anonymous
173
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800174// ---------------------------------------------------------------------------
175
Mathias Agopian99b49842011-06-27 16:05:52 -0700176const String16 sHardwareTest("android.permission.HARDWARE_TEST");
177const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
178const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
179const String16 sDump("android.permission.DUMP");
180
181// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800182int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
183int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700184int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700185bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800186uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800187bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800188bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800189int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800190// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600191bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700192int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700193bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700194bool SurfaceFlinger::useContextPriority;
Peiyong Lin0256f722018-08-31 15:45:10 -0700195Dataspace SurfaceFlinger::compositionDataSpace = Dataspace::V0_SRGB;
196ui::PixelFormat SurfaceFlinger::compositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700197
Kalle Raitaa099a242017-01-11 11:17:29 -0800198std::string getHwcServiceName() {
199 char value[PROPERTY_VALUE_MAX] = {};
200 property_get("debug.sf.hwc_service_name", value, "default");
201 ALOGI("Using HWComposer service: '%s'", value);
202 return std::string(value);
203}
204
205bool useTrebleTestingOverride() {
206 char value[PROPERTY_VALUE_MAX] = {};
207 property_get("debug.sf.treble_testing_override", value, "false");
208 ALOGI("Treble testing override: '%s'", value);
209 return std::string(value) == "true";
210}
211
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800212std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
213 switch(displayColorSetting) {
214 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700215 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800216 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700217 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800218 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700219 return std::string("Enhanced");
220 default:
221 return std::string("Unknown ") +
222 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800223 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800224}
225
David Sodmanbc815282017-11-05 18:57:52 -0800226SurfaceFlingerBE::SurfaceFlingerBE()
227 : mHwcServiceName(getHwcServiceName()),
228 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800229 mFrameBuckets(),
230 mTotalTime(0),
231 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800232 mComposerSequenceId(0) {
233}
234
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800235SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800236 : BnSurfaceComposer(),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700237 mTransactionPending(false),
238 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700239 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700240 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800241 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700242 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800243 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800244 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800245 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800246 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800247 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700248 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700249 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700250 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700251 mDebugInTransaction(0),
252 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700253 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700254 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700255 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800256 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800257 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800258 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700259 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800260 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800261 mCreateBufferQueue(&BufferQueue::createBufferQueue),
Lloyd Pique22098362018-09-13 11:46:49 -0700262 mCreateNativeWindowSurface(&surfaceflinger::impl::createNativeWindowSurface) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800263
264SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800265 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800266
267 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
268 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
269
270 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
271 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
272
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800273 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
274 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800275
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700276 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
277 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
278
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700279 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
280 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
281
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800282 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
283 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
284
Steven Thomas050b2c82017-03-06 11:45:16 -0800285 // Vr flinger is only enabled on Daydream ready devices.
286 useVrFlinger = getBool< ISurfaceFlingerConfigs,
287 &ISurfaceFlingerConfigs::useVrFlinger>(false);
288
Fabien Sanglard1971b632017-03-10 14:50:03 -0800289 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
290 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
291
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600292 hasWideColorDisplay =
293 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700294 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700295 getBool<V1_2::ISurfaceFlingerConfigs,
296 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
297
298 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
299 if (surfaceFlingerConfigsServiceV1_2) {
300 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
301 [&](Dataspace tmpDataSpace, ui::PixelFormat tmpPixelFormat) {
302 compositionDataSpace = tmpDataSpace;
303 compositionPixelFormat = tmpPixelFormat;
304 });
305 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600306
Peiyong Linb3839ad2018-09-05 15:37:19 -0700307 useContextPriority = getBool<ISurfaceFlingerConfigs,
308 &ISurfaceFlingerConfigs::useContextPriority>(true);
309
Iris Chang7501ed62018-04-30 14:45:42 +0800310 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700311 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
312 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800313 V1_1::DisplayOrientation::ORIENTATION_0);
314
315 switch (primaryDisplayOrientation) {
316 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700317 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800318 break;
319 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700320 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800321 break;
322 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700323 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800324 break;
325 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700326 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800327 break;
328 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700329 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800330
Lloyd Pique41be5d22018-06-21 13:11:48 -0700331 // Note: We create a local temporary with the real DispSync implementation
332 // type temporarily so we can initialize it with the configured values,
333 // before storing it for more generic use using the interface type.
334 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
335 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
336 SurfaceFlinger::dispSyncPresentTimeOffset);
337 mPrimaryDispSync = std::move(primaryDispSync);
Saurabh Shahf4174532017-07-13 10:45:07 -0700338
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800339 // debugging stuff...
340 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700341
Mathias Agopianb4b17302013-03-20 18:36:41 -0700342 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700343 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700344
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800345 property_get("debug.sf.showupdates", value, "0");
346 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700347
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700348 property_get("debug.sf.ddms", value, "0");
349 mDebugDDMS = atoi(value);
350 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700351 if (!startDdmConnection()) {
352 // start failed, and DDMS debugging not enabled
353 mDebugDDMS = 0;
354 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700355 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700356 ALOGI_IF(mDebugRegion, "showupdates enabled");
357 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700358
359 property_get("debug.sf.disable_backpressure", value, "0");
360 mPropagateBackpressure = !atoi(value);
361 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700362
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800363 property_get("debug.sf.enable_hwc_vds", value, "0");
364 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800365 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800366
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800367 property_get("ro.sf.disable_triple_buffer", value, "1");
368 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800369 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700370
Yiwei Zhang243b3782018-05-15 17:40:04 -0700371 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700372 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
373 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
374
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200375 property_get("debug.sf.early_phase_offset_ns", value, "-1");
376 const int earlySfOffsetNs = atoi(value);
377
378 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
379 const int earlyGlSfOffsetNs = atoi(value);
380
381 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
382 const int earlyAppOffsetNs = atoi(value);
383
384 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
385 const int earlyGlAppOffsetNs = atoi(value);
386
Ana Krulec98b5b242018-08-10 15:03:23 -0700387 property_get("debug.sf.use_scheduler", value, "0");
388 mUseScheduler = atoi(value);
389
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200390 const VSyncModulator::Offsets earlyOffsets =
391 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
392 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
393 const VSyncModulator::Offsets earlyGlOffsets =
394 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
395 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
396 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
397 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700398
Romain Guy11d63f42017-07-20 12:47:14 -0700399 // We should be reading 'persist.sys.sf.color_saturation' here
400 // but since /data may be encrypted, we need to wait until after vold
401 // comes online to attempt to read the property. The property is
402 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800403
404 if (useTrebleTestingOverride()) {
405 // Without the override SurfaceFlinger cannot connect to HIDL
406 // services that are not listed in the manifests. Considered
407 // deriving the setting from the set service name, but it
408 // would be brittle if the name that's not 'default' is used
409 // for production purposes later on.
410 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
411 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800412}
413
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800414void SurfaceFlinger::onFirstRef()
415{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800416 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800417}
418
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800419SurfaceFlinger::~SurfaceFlinger()
420{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800421}
422
Dan Stozac7014012014-02-14 15:03:43 -0800423void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800424{
425 // the window manager died on us. prepare its eulogy.
426
Andy McFadden13a082e2012-08-24 10:16:42 -0700427 // restore initial conditions (default device unblank, etc)
428 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800429
430 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700431 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800432}
433
Robert Carr1db73f62016-12-21 12:58:51 -0800434static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700435 status_t err = client->initCheck();
436 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800437 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800438 }
Robert Carr1db73f62016-12-21 12:58:51 -0800439 return nullptr;
440}
441
442sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
443 return initClient(new Client(this));
444}
445
446sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
447 const sp<IGraphicBufferProducer>& gbp) {
448 if (authenticateSurfaceTexture(gbp) == false) {
449 return nullptr;
450 }
451 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
452 if (layer == nullptr) {
453 return nullptr;
454 }
455
456 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800457}
458
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700459sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
460 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700461{
462 class DisplayToken : public BBinder {
463 sp<SurfaceFlinger> flinger;
464 virtual ~DisplayToken() {
465 // no more references, this display must be terminated
466 Mutex::Autolock _l(flinger->mStateLock);
467 flinger->mCurrentState.displays.removeItem(this);
468 flinger->setTransactionFlags(eDisplayTransactionNeeded);
469 }
470 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700471 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700472 : flinger(flinger) {
473 }
474 };
475
476 sp<BBinder> token = new DisplayToken(this);
477
478 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700479 DisplayDeviceState info;
480 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700481 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700482 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700483 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800484 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700485 return token;
486}
487
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700488void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700489 Mutex::Autolock _l(mStateLock);
490
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700491 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700492 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700493 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700494 return;
495 }
496
497 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700498 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700499 ALOGE("destroyDisplay called for non-virtual display");
500 return;
501 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700502 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700503 mCurrentState.displays.removeItemsAt(idx);
504 setTransactionFlags(eDisplayTransactionNeeded);
505}
506
Mathias Agopiane57f2922012-08-09 16:29:12 -0700507sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700508 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700509 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800510 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700511 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700512 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700513}
514
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800515void SurfaceFlinger::bootFinished()
516{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700517 if (mStartPropertySetThread->join() != NO_ERROR) {
518 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800519 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800520 const nsecs_t now = systemTime();
521 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000522 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700523
524 // wait patiently for the window manager death
525 const String16 name("window");
526 sp<IBinder> window(defaultServiceManager()->getService(name));
527 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700528 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700529 }
530
Steven Thomas050b2c82017-03-06 11:45:16 -0800531 if (mVrFlinger) {
532 mVrFlinger->OnBootFinished();
533 }
534
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700535 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700536 // formerly we would just kill the process, but we now ask it to exit so it
537 // can choose where to stop the animation.
538 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700539
540 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
541 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
542 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700543
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800544 postMessageAsync(new LambdaMessage([this] {
545 readPersistentProperties();
546 mBootStage = BootStage::FINISHED;
547 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800548}
549
Dan Stoza436ccf32018-06-21 12:10:12 -0700550uint32_t SurfaceFlinger::getNewTexture() {
551 {
552 std::lock_guard lock(mTexturePoolMutex);
553 if (!mTexturePool.empty()) {
554 uint32_t name = mTexturePool.back();
555 mTexturePool.pop_back();
556 ATRACE_INT("TexturePoolSize", mTexturePool.size());
557 return name;
558 }
559
560 // The pool was too small, so increase it for the future
561 ++mTexturePoolSize;
562 }
563
564 // The pool was empty, so we need to get a new texture name directly using a
565 // blocking call to the main thread
566 uint32_t name = 0;
567 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
568 return name;
569}
570
Mathias Agopian3f844832013-08-07 21:24:32 -0700571void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700572 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700573}
574
Wei Wangf9b05ee2017-07-19 20:59:39 -0700575// Do not call property_set on main thread which will be blocked by init
576// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700577void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700578 ALOGI( "SurfaceFlinger's main thread ready to run. "
579 "Initializing graphics H/W...");
580
Thierry Strudel2924d012017-08-14 15:19:37 -0700581 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900582
Steven Thomasb02664d2017-07-26 18:48:28 -0700583 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800584
Steven Thomasb02664d2017-07-26 18:48:28 -0700585 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700586 if (mUseScheduler) {
587 mScheduler = std::make_unique<Scheduler>();
588 mAppConnectionHandle =
589 mScheduler->createConnection("appConnection", mPrimaryDispSync.get(),
590 SurfaceFlinger::vsyncPhaseOffsetNs,
591 [this] { resyncWithRateLimit(); },
592 impl::EventThread::InterceptVSyncsCallback());
593 mSfConnectionHandle =
594 mScheduler->createConnection("sfConnection", mPrimaryDispSync.get(),
595 SurfaceFlinger::sfVsyncPhaseOffsetNs,
596 [this] { resyncWithRateLimit(); },
597 [this](nsecs_t timestamp) {
598 mInterceptor->saveVSyncEvent(timestamp);
599 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800600
Ana Krulec98b5b242018-08-10 15:03:23 -0700601 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700602 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
603 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700604 } else {
605 mEventThreadSource =
606 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
607 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
608 mEventThread =
609 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
610 [this] { resyncWithRateLimit(); },
611 impl::EventThread::InterceptVSyncsCallback(),
612 "appEventThread");
613 mSfEventThreadSource =
614 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
615 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
616
617 mSFEventThread =
618 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
619 [this] { resyncWithRateLimit(); },
620 [this](nsecs_t timestamp) {
621 mInterceptor->saveVSyncEvent(timestamp);
622 },
623 "sfEventThread");
624 mEventQueue->setEventThread(mSFEventThread.get());
625 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
626 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800627
Steven Thomasb02664d2017-07-26 18:48:28 -0700628 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700629 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700630 renderEngineFeature |= (useColorManagement ?
631 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700632 renderEngineFeature |= (useContextPriority ?
633 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700634
635 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
636 getBE().mRenderEngine =
Peiyong Linf11f39b2018-09-05 14:37:41 -0700637 renderengine::RenderEngine::create(static_cast<int32_t>(compositionPixelFormat),
638 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800639 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700640
641 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
642 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800643 getBE().mHwc.reset(
644 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700645 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800646 // Process any initial hotplug and resulting display changes.
647 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700648 const auto display = getDefaultDisplayDeviceLocked();
649 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
650 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
651 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800652
Lloyd Piquefcd86612017-12-14 17:15:36 -0800653 // make the default display GLContext current so that we can create textures
654 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700655 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800656
Steven Thomas050b2c82017-03-06 11:45:16 -0800657 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700658 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700659 // This callback is called from the vr flinger dispatch thread. We
660 // need to call signalTransaction(), which requires holding
661 // mStateLock when we're not on the main thread. Acquiring
662 // mStateLock from the vr flinger dispatch thread might trigger a
663 // deadlock in surface flinger (see b/66916578), so post a message
664 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700665 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700666 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
667 mVrFlingerRequestsDisplay = requestDisplay;
668 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700669 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800670 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700671 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
672 getHwComposer()
673 .getHwcDisplayId(display->getId())
674 .value_or(0),
675 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800676 if (!mVrFlinger) {
677 ALOGE("Failed to start vrflinger");
678 }
679 }
680
Lloyd Pique379adc12018-01-22 17:31:47 -0800681 mEventControlThread = std::make_unique<impl::EventControlThread>(
682 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700683
Mathias Agopian92a979a2012-08-02 18:32:23 -0700684 // initialize our drawing state
685 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700686
Andy McFadden13a082e2012-08-24 10:16:42 -0700687 // set initial conditions (e.g. unblank default device)
688 initializeDisplays();
689
David Sodmanbc815282017-11-05 18:57:52 -0800690 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700691
Wei Wangf9b05ee2017-07-19 20:59:39 -0700692 // Inform native graphics APIs whether the present timestamp is supported:
693 if (getHwComposer().hasCapability(
694 HWC2::Capability::PresentFenceIsNotReliable)) {
695 mStartPropertySetThread = new StartPropertySetThread(false);
696 } else {
697 mStartPropertySetThread = new StartPropertySetThread(true);
698 }
699
700 if (mStartPropertySetThread->Start() != NO_ERROR) {
701 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800702 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800703
Chia-I Wud49d6692018-06-27 07:17:41 +0800704 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
705 // is used to saturate legacy sRGB content. However, to make sure the same color under
706 // Display P3 will be saturated to the same color, we intentionally break the API spec
707 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
708 // such saturation matrix on Display P3 is understood fully, the API should always return
709 // identify matrix.
710 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
711 Dataspace::SRGB_LINEAR);
712
713 // we will apply this on Display P3.
714 if (mEnhancedSaturationMatrix != mat4()) {
715 ColorSpace srgb(ColorSpace::sRGB());
716 ColorSpace displayP3(ColorSpace::DisplayP3());
717 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
718 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
719 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
720 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800721
Dan Stoza9e56aa02015-11-02 13:00:03 -0800722 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700723}
724
Romain Guy11d63f42017-07-20 12:47:14 -0700725void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700726 Mutex::Autolock _l(mStateLock);
727
Romain Guy11d63f42017-07-20 12:47:14 -0700728 char value[PROPERTY_VALUE_MAX];
729
730 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800731 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700732 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800733 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100734
735 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700736 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700737}
738
Mathias Agopiana67e4182012-06-19 17:26:12 -0700739void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800740 // Start boot animation service by setting a property mailbox
741 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700742 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800743 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700744 if (mStartPropertySetThread->join() != NO_ERROR) {
745 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800746 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700747}
748
Mathias Agopian875d8e12013-06-07 15:35:48 -0700749size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800750 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700751}
752
Mathias Agopian875d8e12013-06-07 15:35:48 -0700753size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800754 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700755}
756
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800757// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800758
Jamie Gennis582270d2011-08-17 18:19:00 -0700759bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800760 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800761 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800762 return authenticateSurfaceTextureLocked(bufferProducer);
763}
764
765bool SurfaceFlinger::authenticateSurfaceTextureLocked(
766 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800767 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800768 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800769}
770
Brian Anderson6b376712017-04-04 10:51:39 -0700771status_t SurfaceFlinger::getSupportedFrameTimestamps(
772 std::vector<FrameEvent>* outSupported) const {
773 *outSupported = {
774 FrameEvent::REQUESTED_PRESENT,
775 FrameEvent::ACQUIRE,
776 FrameEvent::LATCH,
777 FrameEvent::FIRST_REFRESH_START,
778 FrameEvent::LAST_REFRESH_START,
779 FrameEvent::GPU_COMPOSITION_DONE,
780 FrameEvent::DEQUEUE_READY,
781 FrameEvent::RELEASE,
782 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700783 ConditionalLock _l(mStateLock,
784 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700785 if (!getHwComposer().hasCapability(
786 HWC2::Capability::PresentFenceIsNotReliable)) {
787 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
788 }
789 return NO_ERROR;
790}
791
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700792status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
793 Vector<DisplayInfo>* configs) {
794 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700795 return BAD_VALUE;
796 }
797
Jesse Hall692c7232012-11-08 15:41:56 -0800798 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700799 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
800 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700801 type = i;
802 break;
803 }
804 }
805
806 if (type < 0) {
807 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700808 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700809
Mathias Agopian8b736f12012-08-13 17:54:26 -0700810 // TODO: Not sure if display density should handled by SF any longer
811 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700812 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700813 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700814 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800815 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700816 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700817 }
818 return density;
819 }
820 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700821 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700822 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700823 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700824 return getDensityFromProperty("ro.sf.lcd_density"); }
825 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700826
Dan Stoza7f7da322014-05-02 15:26:25 -0700827 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700828
Steven Thomas6d8110b2017-08-31 18:24:21 -0700829 ConditionalLock _l(mStateLock,
830 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800831 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700832 DisplayInfo info = DisplayInfo();
833
Dan Stoza9e56aa02015-11-02 13:00:03 -0800834 float xdpi = hwConfig->getDpiX();
835 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700836
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700837 info.w = hwConfig->getWidth();
838 info.h = hwConfig->getHeight();
839 // Default display viewport to display width and height
840 info.viewportW = info.w;
841 info.viewportH = info.h;
842
Dan Stoza7f7da322014-05-02 15:26:25 -0700843 if (type == DisplayDevice::DISPLAY_PRIMARY) {
844 // The density of the device is provided by a build property
845 float density = Density::getBuildDensity() / 160.0f;
846 if (density == 0) {
847 // the build doesn't provide a density -- this is wrong!
848 // use xdpi instead
849 ALOGE("ro.sf.lcd_density must be defined as a build property");
850 density = xdpi / 160.0f;
851 }
852 if (Density::getEmuDensity()) {
853 // if "qemu.sf.lcd_density" is specified, it overrides everything
854 xdpi = ydpi = density = Density::getEmuDensity();
855 density /= 160.0f;
856 }
857 info.density = density;
858
859 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700860 const auto display = getDefaultDisplayDeviceLocked();
861 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700862
863 // This is for screenrecord
864 const Rect viewport = display->getViewport();
865 if (viewport.isValid()) {
866 info.viewportW = uint32_t(viewport.getWidth());
867 info.viewportH = uint32_t(viewport.getHeight());
868 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700869 } else {
870 // TODO: where should this value come from?
871 static const int TV_DENSITY = 213;
872 info.density = TV_DENSITY / 160.0f;
873 info.orientation = 0;
874 }
875
Dan Stoza7f7da322014-05-02 15:26:25 -0700876 info.xdpi = xdpi;
877 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800878 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900879 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800880
Andy McFadden91b2ca82014-06-13 14:04:23 -0700881 // This is how far in advance a buffer must be queued for
882 // presentation at a given time. If you want a buffer to appear
883 // on the screen at time N, you must submit the buffer before
884 // (N - presentationDeadline).
885 //
886 // Normally it's one full refresh period (to give SF a chance to
887 // latch the buffer), but this can be reduced by configuring a
888 // DispSync offset. Any additional delays introduced by the hardware
889 // composer or panel must be accounted for here.
890 //
891 // We add an additional 1ms to allow for processing time and
892 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800893 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800894 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700895
896 // All non-virtual displays are currently considered secure.
897 info.secure = true;
898
Iris Chang7501ed62018-04-30 14:45:42 +0800899 if (type == DisplayDevice::DISPLAY_PRIMARY &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700900 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800901 std::swap(info.w, info.h);
902 }
903
Michael Wright28f24d02016-07-12 13:30:53 -0700904 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700905 }
906
Dan Stoza7f7da322014-05-02 15:26:25 -0700907 return NO_ERROR;
908}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700909
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700910status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
911 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700912 return BAD_VALUE;
913 }
914
915 // FIXME for now we always return stats for the primary display
916 memset(stats, 0, sizeof(*stats));
Lloyd Pique41be5d22018-06-21 13:11:48 -0700917 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
918 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700919 return NO_ERROR;
920}
921
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700922int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
923 const auto display = getDisplayDevice(displayToken);
924 if (!display) {
925 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800926 return BAD_VALUE;
927 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700928
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700929 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700930}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700931
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700932void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
933 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700934 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700935 return;
936 }
937
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700938 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700939 ALOGW("Trying to set config for virtual display");
940 return;
941 }
942
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700943 display->setActiveConfig(mode);
944 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700945}
946
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700947status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700948 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700949 Vector<DisplayInfo> configs;
950 getDisplayConfigs(displayToken, &configs);
951 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
952 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
953 configs.size());
954 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700955 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700956 const auto display = getDisplayDevice(displayToken);
957 if (!display) {
958 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
959 displayToken.get());
960 } else if (display->isVirtual()) {
961 ALOGW("Attempt to set active config %d for virtual display", mode);
962 } else {
963 setActiveConfigInternal(display, mode);
964 }
965 }));
966
Mathias Agopian888c8222012-08-04 21:10:38 -0700967 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700968}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700969status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
970 Vector<ColorMode>* outColorModes) {
971 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700972 return BAD_VALUE;
973 }
974
Michael Wright28f24d02016-07-12 13:30:53 -0700975 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700976 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
977 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700978 type = i;
979 break;
980 }
981 }
982
983 if (type < 0) {
984 return type;
985 }
986
Peiyong Lina52f0292018-03-14 17:26:31 -0700987 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700988 {
989 ConditionalLock _l(mStateLock,
990 std::this_thread::get_id() != mMainThreadId);
991 modes = getHwComposer().getColorModes(type);
992 }
Michael Wright28f24d02016-07-12 13:30:53 -0700993 outColorModes->clear();
994 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
995
996 return NO_ERROR;
997}
998
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700999ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1000 if (const auto display = getDisplayDevice(displayToken)) {
1001 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001002 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001003 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001004}
1005
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001006void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1007 Dataspace dataSpace, RenderIntent renderIntent) {
1008 ColorMode currentMode = display->getActiveColorMode();
1009 Dataspace currentDataSpace = display->getCompositionDataSpace();
1010 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001011
Peiyong Lin38e9a562018-04-10 16:24:20 -07001012 if (mode == currentMode && dataSpace == currentDataSpace &&
1013 renderIntent == currentRenderIntent) {
1014 return;
1015 }
1016
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001017 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001018 ALOGW("Trying to set config for virtual display");
1019 return;
1020 }
1021
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001022 display->setActiveColorMode(mode);
1023 display->setCompositionDataSpace(dataSpace);
1024 display->setActiveRenderIntent(renderIntent);
1025 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001026
1027 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001028 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1029 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001030}
1031
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001032status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001033 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001034 Vector<ColorMode> modes;
1035 getDisplayColorModes(displayToken, &modes);
1036 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1037 if (mode < ColorMode::NATIVE || !exists) {
1038 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1039 decodeColorMode(mode).c_str(), mode, displayToken.get());
1040 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001041 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001042 const auto display = getDisplayDevice(displayToken);
1043 if (!display) {
1044 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1045 decodeColorMode(mode).c_str(), mode, displayToken.get());
1046 } else if (display->isVirtual()) {
1047 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1048 decodeColorMode(mode).c_str(), mode);
1049 } else {
1050 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1051 RenderIntent::COLORIMETRIC);
1052 }
1053 }));
1054
Michael Wright28f24d02016-07-12 13:30:53 -07001055 return NO_ERROR;
1056}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001057
Svetoslavd85084b2014-03-20 10:28:31 -07001058status_t SurfaceFlinger::clearAnimationFrameStats() {
1059 Mutex::Autolock _l(mStateLock);
1060 mAnimFrameTracker.clearStats();
1061 return NO_ERROR;
1062}
1063
1064status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1065 Mutex::Autolock _l(mStateLock);
1066 mAnimFrameTracker.getStats(outStats);
1067 return NO_ERROR;
1068}
1069
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001070status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1071 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001072 Mutex::Autolock _l(mStateLock);
1073
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001074 const auto display = getDisplayDeviceLocked(displayToken);
1075 if (!display) {
1076 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001077 return BAD_VALUE;
1078 }
1079
Peiyong Linfb069302018-04-25 14:34:31 -07001080 // At this point the DisplayDeivce should already be set up,
1081 // meaning the luminance information is already queried from
1082 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001083 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001084 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1085 capabilities.getDesiredMaxLuminance(),
1086 capabilities.getDesiredMaxAverageLuminance(),
1087 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001088
1089 return NO_ERROR;
1090}
1091
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001092status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001093 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001094 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001095
Chia-I Wu90f669f2017-10-05 14:24:41 -07001096 if (mInjectVSyncs == enable) {
1097 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001098 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001099
Ana Krulec98b5b242018-08-10 15:03:23 -07001100 // TODO(akrulec): Part of the Injector should be refactored, so that it
1101 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001102 if (enable) {
1103 ALOGV("VSync Injections enabled");
1104 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001105 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001106 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001107 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001108 impl::EventThread::InterceptVSyncsCallback(),
1109 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001110 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001111 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001112 } else {
1113 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001114 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001115 }
1116
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001117 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001118 }));
1119
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001120 return NO_ERROR;
1121}
1122
1123status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001124 Mutex::Autolock _l(mStateLock);
1125
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001126 if (!mInjectVSyncs) {
1127 ALOGE("VSync Injections not enabled");
1128 return BAD_VALUE;
1129 }
1130 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1131 ALOGV("Injecting VSync inside SurfaceFlinger");
1132 mVSyncInjector->onInjectSyncEvent(when);
1133 }
1134 return NO_ERROR;
1135}
1136
Lloyd Pique755e3192018-01-31 16:46:15 -08001137status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1138 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001139 // Try to acquire a lock for 1s, fail gracefully
1140 const status_t err = mStateLock.timedLock(s2ns(1));
1141 const bool locked = (err == NO_ERROR);
1142 if (!locked) {
1143 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1144 return TIMED_OUT;
1145 }
1146
1147 outLayers->clear();
1148 mCurrentState.traverseInZOrder([&](Layer* layer) {
1149 outLayers->push_back(layer->getLayerDebugInfo());
1150 });
1151
1152 mStateLock.unlock();
1153 return NO_ERROR;
1154}
1155
Peiyong Lin0256f722018-08-31 15:45:10 -07001156status_t SurfaceFlinger::getCompositionPreference(Dataspace* outDataSpace,
1157 ui::PixelFormat* outPixelFormat) const {
1158 *outDataSpace = compositionDataSpace;
1159 *outPixelFormat = compositionPixelFormat;
1160 return NO_ERROR;
1161}
1162
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001163// ----------------------------------------------------------------------------
1164
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001165sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1166 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001167 if (mUseScheduler) {
1168 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1169 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1170 } else {
1171 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1172 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001173 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001174 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1175 return mSFEventThread->createEventConnection();
1176 } else {
1177 return mEventThread->createEventConnection();
1178 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001179 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001180}
1181
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001182// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001183
1184void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001185 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001186}
1187
1188void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001189 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001190}
1191
1192void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001193 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001194}
1195
1196void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001197 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001198 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001199}
1200
1201status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001202 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001203 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001204}
1205
1206status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001207 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001208 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001209 if (res == NO_ERROR) {
1210 msg->wait();
1211 }
1212 return res;
1213}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001214
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001215void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001216 do {
1217 waitForEvent();
1218 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001219}
1220
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001221void SurfaceFlinger::enableHardwareVsync() {
1222 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001223 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001224 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001225 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001226 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001227 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001228}
1229
Jesse Hall948fe0c2013-10-14 12:56:09 -07001230void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001231 Mutex::Autolock _l(mHWVsyncLock);
1232
Jesse Hall948fe0c2013-10-14 12:56:09 -07001233 if (makeAvailable) {
1234 mHWVsyncAvailable = true;
1235 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001236 // Hardware vsync is not currently available, so abort the resync
1237 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001238 return;
1239 }
1240
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001241 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1242 if (!getHwComposer().isConnected(displayId)) {
1243 return;
1244 }
1245
1246 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001247 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001248
Lloyd Pique41be5d22018-06-21 13:11:48 -07001249 mPrimaryDispSync->reset();
1250 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001251
1252 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001253 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001254 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001255 mPrimaryHWVsyncEnabled = true;
1256 }
1257}
1258
Jesse Hall948fe0c2013-10-14 12:56:09 -07001259void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001260 Mutex::Autolock _l(mHWVsyncLock);
1261 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001262 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001263 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001264 mPrimaryHWVsyncEnabled = false;
1265 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001266 if (makeUnavailable) {
1267 mHWVsyncAvailable = false;
1268 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001269}
1270
Tim Murray4a4e4a22016-04-19 16:29:23 +00001271void SurfaceFlinger::resyncWithRateLimit() {
1272 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001273
1274 // No explicit locking is needed here since EventThread holds a lock while calling this method
1275 static nsecs_t sLastResyncAttempted = 0;
1276 const nsecs_t now = systemTime();
1277 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001278 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001279 }
Dan Stoza57164302017-05-08 14:03:54 -07001280 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001281}
1282
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001283void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1284 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001285 ATRACE_NAME("SF onVsync");
1286
Steven Thomas3cfac282017-02-06 12:29:30 -08001287 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001288 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001289 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001290 return;
1291 }
1292
1293 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001294 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001295 return;
1296 }
1297
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001298 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1299 // For now, we don't do anything with external display vsyncs.
1300 return;
1301 }
1302
Jamie Gennisd1700752013-10-14 12:22:52 -07001303 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001304
Jamie Gennisd1700752013-10-14 12:22:52 -07001305 { // Scope for the lock
1306 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001307 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001308 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001309 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001310 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001311
1312 if (needsHwVsync) {
1313 enableHardwareVsync();
1314 } else {
1315 disableHardwareVsync(false);
1316 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001317}
1318
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001319void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001320 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1321 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001322}
1323
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001324void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001325 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001326 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001327 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001328
Lloyd Piqueba04e622017-12-14 17:11:26 -08001329 // Ignore events that do not have the right sequenceId.
1330 if (sequenceId != getBE().mComposerSequenceId) {
1331 return;
1332 }
1333
Steven Thomasb02664d2017-07-26 18:48:28 -07001334 // Only lock if we're not on the main thread. This function is normally
1335 // called on a hwbinder thread, but for the primary display it's called on
1336 // the main thread with the state lock already held, so don't attempt to
1337 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001338 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001339
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001340 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001341
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001342 if (std::this_thread::get_id() == mMainThreadId) {
1343 // Process all pending hot plug events immediately if we are on the main thread.
1344 processDisplayHotplugEventsLocked();
1345 }
1346
Lloyd Piqueba04e622017-12-14 17:11:26 -08001347 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001348}
1349
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001350void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001351 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001352 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001353 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001354 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001355 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001356}
1357
Dan Stoza9e56aa02015-11-02 13:00:03 -08001358void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001359 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001360 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001361 getHwComposer().setVsyncEnabled(disp,
1362 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001363}
1364
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001365// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001366void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001367 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001368 // Clear the drawing state so that the logic inside of
1369 // handleTransactionLocked will fire. It will determine the delta between
1370 // mCurrentState and mDrawingState and re-apply all changes when we make the
1371 // transition.
1372 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001373 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001374 mDisplays.clear();
1375}
1376
Steven Thomas050b2c82017-03-06 11:45:16 -08001377void SurfaceFlinger::updateVrFlinger() {
1378 if (!mVrFlinger)
1379 return;
1380 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001381 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001382 return;
1383 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001384
David Sodman105b7dc2017-11-04 20:28:14 -07001385 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001386 ALOGE("Vr flinger is only supported for remote hardware composer"
1387 " service connections. Ignoring request to transition to vr"
1388 " flinger.");
1389 mVrFlingerRequestsDisplay = false;
1390 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001391 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001392
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001393 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001394
Steven Thomas0123ac62018-07-12 11:32:34 -07001395 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001396 LOG_ALWAYS_FATAL_IF(!display);
1397 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001398 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1399 // called below. Clear the reference now so we don't accidentally use it
1400 // later.
1401 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001402
Steven Thomasb02664d2017-07-26 18:48:28 -07001403 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001404 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001405 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001406
Steven Thomasb02664d2017-07-26 18:48:28 -07001407 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001408 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001409 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1410 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001411 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001412
David Sodman105b7dc2017-11-04 20:28:14 -07001413 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1414 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001415
1416 if (vrFlingerRequestsDisplay) {
1417 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001418 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001419
1420 mVisibleRegionsDirty = true;
1421 invalidateHwcGeometry();
1422
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001423 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001424 display = getDefaultDisplayDeviceLocked();
1425 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001426 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001427
Steven Thomasb02664d2017-07-26 18:48:28 -07001428 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001429 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001430 const nsecs_t period = activeConfig->getVsyncPeriod();
1431 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001432
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001433 // The present fences returned from vr_hwc are not an accurate
1434 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001435 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1436 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001437
Steven Thomasb02664d2017-07-26 18:48:28 -07001438 // Use phase of 0 since phase is not known.
1439 // Use latency of 0, which will snap to the ideal latency.
1440 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001441
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001442 resyncToHardwareVsync(false);
1443
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001444 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001445 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001446}
1447
Mathias Agopian4fec8732012-06-29 14:12:52 -07001448void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001449 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001450 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001451 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001452 bool frameMissed = !mHadClientComposition &&
1453 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001454 (mPreviousPresentFence->getSignalTime() ==
1455 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001456 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001457 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001458 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001459 mTimeStats.incrementMissedFrames();
1460 if (mPropagateBackpressure) {
1461 signalLayerUpdate();
1462 break;
1463 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001464 }
Dan Stoza50182882016-07-08 12:02:20 -07001465
Steven Thomas050b2c82017-03-06 11:45:16 -08001466 // Now that we're going to make it to the handleMessageTransaction()
1467 // call below it's safe to call updateVrFlinger(), which will
1468 // potentially trigger a display handoff.
1469 updateVrFlinger();
1470
Dan Stoza6b9454d2014-11-07 16:00:59 -08001471 bool refreshNeeded = handleMessageTransaction();
1472 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001473 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001474 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001475 // Signal a refresh if a transaction modified the window state,
1476 // a new buffer was latched, or if HWC has requested a full
1477 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001478 signalRefresh();
1479 }
1480 break;
1481 }
1482 case MessageQueue::REFRESH: {
1483 handleMessageRefresh();
1484 break;
1485 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001486 }
1487}
1488
Dan Stoza6b9454d2014-11-07 16:00:59 -08001489bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001490 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001491 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001492 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001493 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001494 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001495 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001496}
1497
Mathias Agopian4fec8732012-06-29 14:12:52 -07001498void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001499 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001500
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001501 mRefreshPending = false;
1502
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001503 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001504 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001505 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001506 calculateWorkingSet();
David Sodman10a41ff2018-08-05 12:14:17 -07001507
David Sodmanfa9b2af2017-12-24 13:28:59 -08001508 for (const auto& [token, display] : mDisplays) {
David Sodman10a41ff2018-08-05 12:14:17 -07001509 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001510 beginFrame(display);
David Sodman10a41ff2018-08-05 12:14:17 -07001511 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
1512 setUpHWComposer(compositionInfo);
1513 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001514 prepareFrame(display);
1515 doDebugFlashRegions(display, repaintEverything);
1516 doComposition(display, repaintEverything);
1517 }
1518
Adrian Roos1e1a1282017-11-01 19:05:31 +01001519 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001520 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001521
1522 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001523 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001524
Dan Stozabfbffeb2016-07-21 14:49:33 -07001525 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001526 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001527 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001528 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001529 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001530
Jorim Jaggi90535212018-05-23 23:44:06 +02001531 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001532
David Sodman7e4ae112018-02-09 15:02:28 -08001533 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001534 for (const auto& [token, display] : mDisplays) {
1535 const auto displayId = display->getId();
David Sodman7e4ae112018-02-09 15:02:28 -08001536 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[displayId]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001537 compositionInfo.hwc.hwcLayer = nullptr;
1538 }
David Sodmanba340492018-08-05 21:51:33 -07001539 }
David Sodman7e4ae112018-02-09 15:02:28 -08001540
1541 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001542}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001543
David Sodmanfa9b2af2017-12-24 13:28:59 -08001544
1545bool SurfaceFlinger::handleMessageInvalidate() {
1546 ATRACE_CALL();
1547 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001548}
1549
David Sodman79bba0e2018-08-05 18:07:49 -07001550void SurfaceFlinger::calculateWorkingSet() {
1551 ATRACE_CALL();
1552 ALOGV(__FUNCTION__);
1553
David Sodman79bba0e2018-08-05 18:07:49 -07001554 // build the h/w work list
1555 if (CC_UNLIKELY(mGeometryInvalid)) {
1556 mGeometryInvalid = false;
1557 for (const auto& [token, display] : mDisplays) {
1558 const auto displayId = display->getId();
1559 if (displayId >= 0) {
1560 const Vector<sp<Layer>>& currentLayers(
1561 display->getVisibleLayersSortedByZ());
1562 for (size_t i = 0; i < currentLayers.size(); i++) {
1563 const auto& layer = currentLayers[i];
1564
1565 if (!layer->hasHwcLayer(displayId)) {
1566 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1567 layer->forceClientComposition(displayId);
1568 continue;
1569 }
1570 }
1571
1572 layer->setGeometry(display, i);
1573 if (mDebugDisableHWC || mDebugRegion) {
1574 layer->forceClientComposition(displayId);
1575 }
1576 }
1577 }
1578 }
1579 }
1580
1581 // Set the per-frame data
1582 for (const auto& [token, display] : mDisplays) {
1583 const auto displayId = display->getId();
1584 if (displayId < 0) {
1585 continue;
1586 }
1587
1588 if (mDrawingState.colorMatrixChanged) {
1589 display->setColorTransform(mDrawingState.colorMatrix);
1590 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1591 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1592 "display %d: %d", displayId, result);
1593 }
1594 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1595 if (layer->isHdrY410()) {
1596 layer->forceClientComposition(displayId);
1597 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1598 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1599 !display->hasHDR10Support()) {
1600 layer->forceClientComposition(displayId);
1601 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1602 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1603 !display->hasHLGSupport()) {
1604 layer->forceClientComposition(displayId);
1605 }
1606
1607 if (layer->getForceClientComposition(displayId)) {
1608 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1609 layer->setCompositionType(displayId, HWC2::Composition::Client);
1610 continue;
1611 }
1612
1613 layer->setPerFrameData(display);
1614 }
1615
Peiyong Lin13effd12018-07-24 17:01:47 -07001616 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001617 ColorMode colorMode;
1618 Dataspace dataSpace;
1619 RenderIntent renderIntent;
1620 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1621 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1622 }
1623 }
1624
1625 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001626
1627 for (const auto& [token, display] : mDisplays) {
David Sodman15fb96e2018-01-07 10:23:24 -08001628 const auto displayId = display->getId();
1629 getBE().mCompositionInfo[displayId].clear();
David Sodmanba340492018-08-05 21:51:33 -07001630 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1631 auto displayId = display->getId();
1632 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1633 if (!layer->setHwcLayer(displayId)) {
1634 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1635 }
David Sodman15fb96e2018-01-07 10:23:24 -08001636 layer->getBE().compositionInfo.hwc.displayId = displayId;
1637 getBE().mCompositionInfo[displayId].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001638 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1639 }
1640 }
David Sodman79bba0e2018-08-05 18:07:49 -07001641}
1642
David Sodmanfa9b2af2017-12-24 13:28:59 -08001643void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001644{
David Sodmanfb95bcc2017-12-22 15:45:30 -08001645 const auto displayId = display->getId();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001646 // is debugging enabled
1647 if (CC_LIKELY(!mDebugRegion))
1648 return;
1649
David Sodmanfa9b2af2017-12-24 13:28:59 -08001650 if (display->isPoweredOn()) {
1651 // transform the dirty region into this screen's coordinate space
1652 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1653 if (!dirtyRegion.isEmpty()) {
1654 // redraw the whole screen
1655 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001656
David Sodmanfa9b2af2017-12-24 13:28:59 -08001657 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001658 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001659 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001660
David Sodmanfa9b2af2017-12-24 13:28:59 -08001661 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001662 }
1663 }
1664
David Sodmanfa9b2af2017-12-24 13:28:59 -08001665 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001666
1667 if (mDebugRegion > 1) {
1668 usleep(mDebugRegion * 1000);
1669 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001670
David Sodmanfa9b2af2017-12-24 13:28:59 -08001671 if (display->isPoweredOn()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08001672 status_t result = display->prepareFrame(
1673 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001674 ALOGE_IF(result != NO_ERROR,
1675 "prepareFrame for display %d failed:"
1676 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001677 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001678 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001679}
1680
Adrian Roos1e1a1282017-11-01 19:05:31 +01001681void SurfaceFlinger::doTracing(const char* where) {
1682 ATRACE_CALL();
1683 ATRACE_NAME(where);
1684 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001685 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001686 }
1687}
1688
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001689void SurfaceFlinger::logLayerStats() {
1690 ATRACE_CALL();
1691 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001692 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001693 if (display->isPrimary()) {
1694 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001695 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001696 }
1697 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001698
1699 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001700 }
1701}
1702
David Sodman2b406362017-12-15 13:33:47 -08001703void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001704{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001705 ATRACE_CALL();
1706 ALOGV("preComposition");
1707
David Sodman2b406362017-12-15 13:33:47 -08001708 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1709
Mathias Agopiancd60f992012-08-16 16:28:27 -07001710 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001711 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001712 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001713 needExtraInvalidate = true;
1714 }
Robert Carr2047fae2016-11-28 14:09:09 -08001715 });
1716
Mathias Agopiancd60f992012-08-16 16:28:27 -07001717 if (needExtraInvalidate) {
1718 signalLayerUpdate();
1719 }
1720}
1721
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001722void SurfaceFlinger::updateCompositorTiming(
1723 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1724 std::shared_ptr<FenceTime>& presentFenceTime) {
1725 // Update queue of past composite+present times and determine the
1726 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001727 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001728 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001729 while (!getBE().mCompositePresentTimes.empty()) {
1730 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001731 // Cached values should have been updated before calling this method,
1732 // which helps avoid duplicate syscalls.
1733 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1734 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1735 break;
1736 }
1737 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001738 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001739 }
1740
1741 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001742 while (getBE().mCompositePresentTimes.size() > 16) {
1743 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001744 }
1745
Brian Andersond0010582017-03-07 13:20:31 -08001746 setCompositorTimingSnapped(
1747 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1748}
1749
1750void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1751 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001752 // Integer division and modulo round toward 0 not -inf, so we need to
1753 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001754 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001755 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1756 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1757
Brian Andersond0010582017-03-07 13:20:31 -08001758 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1759 if (idealLatency <= 0) {
1760 idealLatency = vsyncInterval;
1761 }
1762
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001763 // Snap the latency to a value that removes scheduling jitter from the
1764 // composition and present times, which often have >1ms of jitter.
1765 // Reducing jitter is important if an app attempts to extrapolate
1766 // something (such as user input) to an accurate diasplay time.
1767 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1768 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001769 nsecs_t bias = vsyncInterval / 2;
1770 int64_t extraVsyncs =
1771 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1772 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1773 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001774
David Sodman99974d22017-11-28 12:04:33 -08001775 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1776 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1777 getBE().mCompositorTiming.interval = vsyncInterval;
1778 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001779}
1780
David Sodman2b406362017-12-15 13:33:47 -08001781void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001782{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001783 ATRACE_CALL();
1784 ALOGV("postComposition");
1785
Brian Anderson3546a3f2016-07-14 11:51:14 -07001786 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001787 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001788 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001789 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001790 }
1791
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001792 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001793 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001794
David Sodman73beded2017-11-15 11:56:06 -08001795 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001796 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001797 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001798 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001799 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001800 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001801 } else {
1802 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1803 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001804
David Sodman73beded2017-11-15 11:56:06 -08001805 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001806 mPreviousPresentFence =
1807 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1808 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001809 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001810
Lloyd Pique41be5d22018-06-21 13:11:48 -07001811 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1812 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001813
David Sodman2b406362017-12-15 13:33:47 -08001814 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001815 // when we started doing work for this frame, but that should be okay
1816 // since updateCompositorTiming has snapping logic.
1817 updateCompositorTiming(
David Sodman2b406362017-12-15 13:33:47 -08001818 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001819 CompositorTiming compositorTiming;
1820 {
David Sodman99974d22017-11-28 12:04:33 -08001821 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1822 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001823 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001824
Robert Carr2047fae2016-11-28 14:09:09 -08001825 mDrawingState.traverseInZOrder([&](Layer* layer) {
1826 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001827 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001828 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001829 recordBufferingStats(layer->getName().string(),
1830 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001831 }
Robert Carr2047fae2016-11-28 14:09:09 -08001832 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001833
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001834 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001835 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001836 enableHardwareVsync();
1837 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001838 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001839 }
1840 }
1841
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001842 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001843 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001844 enableHardwareVsync();
1845 }
1846 }
1847
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001848 if (mAnimCompositionPending) {
1849 mAnimCompositionPending = false;
1850
Brian Anderson4e606e32017-03-16 15:34:57 -07001851 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001852 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001853 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001854 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001855 // The HWC doesn't support present fences, so use the refresh
1856 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001857 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001858 mAnimFrameTracker.setActualPresentTime(presentTime);
1859 }
1860 mAnimFrameTracker.advanceFrame();
1861 }
Dan Stozab90cf072015-03-05 11:05:59 -08001862
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001863 mTimeStats.incrementTotalFrames();
1864 if (mHadClientComposition) {
1865 mTimeStats.incrementClientCompositionFrames();
1866 }
1867
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001868 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001869 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001870 return;
1871 }
1872
1873 nsecs_t currentTime = systemTime();
1874 if (mHasPoweredOff) {
1875 mHasPoweredOff = false;
1876 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001877 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001878 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001879 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1880 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001881 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001882 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001883 }
David Sodman4a36e932017-11-07 14:29:47 -08001884 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001885 }
David Sodman4a36e932017-11-07 14:29:47 -08001886 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001887
1888 {
1889 std::lock_guard lock(mTexturePoolMutex);
1890 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1891 if (refillCount > 0) {
1892 const size_t offset = mTexturePool.size();
1893 mTexturePool.resize(mTexturePoolSize);
1894 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1895 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1896 }
1897 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001898}
1899
1900void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001901 ATRACE_CALL();
1902 ALOGV("rebuildLayerStacks");
1903
Mathias Agopiancd60f992012-08-16 16:28:27 -07001904 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001905 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001906 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001907 mVisibleRegionsDirty = false;
1908 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001909
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001910 for (const auto& pair : mDisplays) {
1911 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001912 Region opaqueRegion;
1913 Region dirtyRegion;
1914 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001915 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001916 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001917 const Rect bounds = display->getBounds();
1918 if (display->isPoweredOn()) {
1919 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001920
Jeff Sharkey76488112017-02-27 14:15:18 -07001921 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001922 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001923 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001924 Region drawRegion(tr.transform(
1925 layer->visibleNonTransparentRegion));
1926 drawRegion.andSelf(bounds);
1927 if (!drawRegion.isEmpty()) {
1928 layersSortedByZ.add(layer);
1929 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001930 // Clear out the HWC layer if this layer was
1931 // previously visible, but no longer is
1932 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001933 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001934 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001935 // WM changes display->layerStack upon sleep/awake.
1936 // Here we make sure we delete the HWC layers even if
1937 // WM changed their layer stack.
1938 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001939 }
1940
1941 // If a layer is not going to get a release fence because
1942 // it is invisible, but it is also going to release its
1943 // old buffer, add it to the list of layers needing
1944 // fences.
1945 if (hwcLayerDestroyed) {
1946 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1947 mLayersWithQueuedFrames.cend(), layer);
1948 if (found != mLayersWithQueuedFrames.cend()) {
1949 layersNeedingFences.add(layer);
1950 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001951 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001952 });
1953 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001954 display->setVisibleLayersSortedByZ(layersSortedByZ);
1955 display->setLayersNeedingFences(layersNeedingFences);
1956 display->undefinedRegion.set(bounds);
1957 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1958 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001959 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001960 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001961}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001962
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001963// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001964// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001965// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001966// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001967// The returned HDR data space is one of
1968// - Dataspace::UNKNOWN
1969// - Dataspace::BT2020_HLG
1970// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001971Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1972 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001973 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001974 *outHdrDataSpace = Dataspace::UNKNOWN;
1975
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001976 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001977 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001978 case Dataspace::V0_SCRGB:
1979 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001980 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001981 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001982 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001983 case Dataspace::BT2020_PQ:
1984 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001985 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001986 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001987 case Dataspace::BT2020_HLG:
1988 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001989 // When there's mixed PQ content and HLG content, we set the HDR
1990 // data space to be BT2020_PQ and convert HLG to PQ.
1991 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1992 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001993 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001994 break;
1995 default:
1996 break;
1997 }
Romain Guy54f154a2017-10-24 21:40:32 +01001998 }
1999
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002000 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002001}
2002
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002003// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002004void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2005 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002006 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2007 *outMode = ColorMode::NATIVE;
2008 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002009 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002010 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002011 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002012
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002013 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002014 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002015
Peiyong Lindfde5112018-06-05 10:58:41 -07002016 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002017 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002018 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002019 if (isHdr) {
2020 bestDataSpace = hdrDataSpace;
2021 }
2022
Chia-I Wu0d711262018-05-21 15:19:35 -07002023 RenderIntent intent;
2024 switch (mDisplayColorSetting) {
2025 case DisplayColorSetting::MANAGED:
2026 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002027 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002028 break;
2029 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002030 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002031 break;
2032 default: // vendor display color setting
2033 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2034 break;
2035 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002036
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002037 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002038}
2039
David Sodman10a41ff2018-08-05 12:14:17 -07002040void SurfaceFlinger::configureSidebandComposition(const CompositionInfo& compositionInfo) const
2041{
2042 HWC2::Error error;
2043 LOG_ALWAYS_FATAL_IF(compositionInfo.hwc.sidebandStream == nullptr,
2044 "CompositionType is sideband, but sideband stream is nullptr");
2045 error = (compositionInfo.hwc.hwcLayer)
2046 ->setSidebandStream(compositionInfo.hwc.sidebandStream->handle());
2047 if (error != HWC2::Error::None) {
2048 ALOGE("[SF] Failed to set sideband stream %p: %s (%d)",
2049 compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
2050 static_cast<int32_t>(error));
2051 }
2052}
2053
2054void SurfaceFlinger::configureHwcCommonData(const CompositionInfo& compositionInfo) const
2055{
2056 HWC2::Error error;
2057
2058 if (!compositionInfo.hwc.skipGeometry) {
2059 error = (compositionInfo.hwc.hwcLayer)->setBlendMode(compositionInfo.hwc.blendMode);
2060 ALOGE_IF(error != HWC2::Error::None,
2061 "[SF] Failed to set blend mode %s:"
2062 " %s (%d)",
2063 to_string(compositionInfo.hwc.blendMode).c_str(), to_string(error).c_str(),
2064 static_cast<int32_t>(error));
2065
2066 error = (compositionInfo.hwc.hwcLayer)->setDisplayFrame(compositionInfo.hwc.displayFrame);
2067 ALOGE_IF(error != HWC2::Error::None,
2068 "[SF] Failed to set the display frame [%d, %d, %d, %d] %s (%d)",
2069 compositionInfo.hwc.displayFrame.left,
2070 compositionInfo.hwc.displayFrame.right,
2071 compositionInfo.hwc.displayFrame.top,
2072 compositionInfo.hwc.displayFrame.bottom,
2073 to_string(error).c_str(), static_cast<int32_t>(error));
2074
2075 error = (compositionInfo.hwc.hwcLayer)->setSourceCrop(compositionInfo.hwc.sourceCrop);
2076 ALOGE_IF(error != HWC2::Error::None,
2077 "[SF] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: %s (%d)",
2078 compositionInfo.hwc.sourceCrop.left,
2079 compositionInfo.hwc.sourceCrop.right,
2080 compositionInfo.hwc.sourceCrop.top,
2081 compositionInfo.hwc.sourceCrop.bottom,
2082 to_string(error).c_str(), static_cast<int32_t>(error));
2083
2084 error = (compositionInfo.hwc.hwcLayer)->setPlaneAlpha(compositionInfo.hwc.alpha);
2085 ALOGE_IF(error != HWC2::Error::None,
2086 "[SF] Failed to set plane alpha %.3f: "
2087 "%s (%d)",
2088 compositionInfo.hwc.alpha,
2089 to_string(error).c_str(), static_cast<int32_t>(error));
2090
2091
2092 error = (compositionInfo.hwc.hwcLayer)->setZOrder(compositionInfo.hwc.z);
2093 ALOGE_IF(error != HWC2::Error::None,
2094 "[SF] Failed to set Z %u: %s (%d)",
2095 compositionInfo.hwc.z,
2096 to_string(error).c_str(), static_cast<int32_t>(error));
2097
2098 error = (compositionInfo.hwc.hwcLayer)
2099 ->setInfo(compositionInfo.hwc.type, compositionInfo.hwc.appId);
2100 ALOGE_IF(error != HWC2::Error::None,
2101 "[SF] Failed to set info (%d)",
2102 static_cast<int32_t>(error));
2103
2104 error = (compositionInfo.hwc.hwcLayer)->setTransform(compositionInfo.hwc.transform);
2105 ALOGE_IF(error != HWC2::Error::None,
2106 "[SF] Failed to set transform %s: "
2107 "%s (%d)",
2108 to_string(compositionInfo.hwc.transform).c_str(), to_string(error).c_str(),
2109 static_cast<int32_t>(error));
2110 }
2111
2112 error = (compositionInfo.hwc.hwcLayer)->setCompositionType(compositionInfo.compositionType);
2113 ALOGE_IF(error != HWC2::Error::None,
2114 "[SF] Failed to set composition type: %s (%d)",
2115 to_string(error).c_str(), static_cast<int32_t>(error));
2116
2117 error = (compositionInfo.hwc.hwcLayer)->setDataspace(compositionInfo.hwc.dataspace);
2118 ALOGE_IF(error != HWC2::Error::None,
2119 "[SF] Failed to set dataspace: %s (%d)",
2120 to_string(error).c_str(), static_cast<int32_t>(error));
2121
2122 error = (compositionInfo.hwc.hwcLayer)->setPerFrameMetadata(
2123 compositionInfo.hwc.supportedPerFrameMetadata, compositionInfo.hwc.hdrMetadata);
2124 ALOGE_IF(error != HWC2::Error::None && error != HWC2::Error::Unsupported,
2125 "[SF] Failed to set hdrMetadata: %s (%d)",
2126 to_string(error).c_str(), static_cast<int32_t>(error));
2127
2128 if (compositionInfo.compositionType == HWC2::Composition::SolidColor) {
2129 error = (compositionInfo.hwc.hwcLayer)->setColor(compositionInfo.hwc.color);
2130 ALOGE_IF(error != HWC2::Error::None,
2131 "[SF] Failed to set color: %s (%d)",
2132 to_string(error).c_str(), static_cast<int32_t>(error));
2133 }
2134
2135 error = (compositionInfo.hwc.hwcLayer)->setVisibleRegion(compositionInfo.hwc.visibleRegion);
2136 ALOGE_IF(error != HWC2::Error::None,
2137 "[SF] Failed to set visible region: %s (%d)",
2138 to_string(error).c_str(), static_cast<int32_t>(error));
2139
2140 error = (compositionInfo.hwc.hwcLayer)->setSurfaceDamage(compositionInfo.hwc.surfaceDamage);
2141 ALOGE_IF(error != HWC2::Error::None,
2142 "[SF] Failed to set surface damage: %s (%d)",
2143 to_string(error).c_str(), static_cast<int32_t>(error));
2144}
2145
2146void SurfaceFlinger::configureDeviceComposition(const CompositionInfo& compositionInfo) const
2147{
2148 HWC2::Error error;
2149
2150 if (compositionInfo.hwc.fence) {
2151 error = (compositionInfo.hwc.hwcLayer)->setBuffer(compositionInfo.mBufferSlot,
2152 compositionInfo.mBuffer, compositionInfo.hwc.fence);
2153 ALOGE_IF(error != HWC2::Error::None,
2154 "[SF] Failed to set buffer: %s (%d)",
2155 to_string(error).c_str(), static_cast<int32_t>(error));
2156 }
2157}
2158
David Sodmanfa9b2af2017-12-24 13:28:59 -08002159void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002160{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002161 bool dirty = !display->getDirtyRegion(false).isEmpty();
2162 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2163 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002164
David Sodmanfa9b2af2017-12-24 13:28:59 -08002165 // If nothing has changed (!dirty), don't recompose.
2166 // If something changed, but we don't currently have any visible layers,
2167 // and didn't when we last did a composition, then skip it this time.
2168 // The second rule does two things:
2169 // - When all layers are removed from a display, we'll emit one black
2170 // frame, then nothing more until we get new layers.
2171 // - When a display is created with a private layer stack, we won't
2172 // emit any black frames until a layer is added to the layer stack.
2173 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002174
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002175 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2176 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002177 mustRecompose ? "doing" : "skipping",
2178 dirty ? "+" : "-",
2179 empty ? "+" : "-",
2180 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002181
David Sodmanfa9b2af2017-12-24 13:28:59 -08002182 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002183
David Sodmanfa9b2af2017-12-24 13:28:59 -08002184 if (mustRecompose) {
2185 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002186 }
2187}
2188
David Sodmanfa9b2af2017-12-24 13:28:59 -08002189void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002190{
David Sodmanfb95bcc2017-12-22 15:45:30 -08002191 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002192 if (!display->isPoweredOn()) {
2193 return;
David Sodman2b406362017-12-15 13:33:47 -08002194 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002195
David Sodmanfb95bcc2017-12-22 15:45:30 -08002196 status_t result = display->prepareFrame(
2197 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08002198 ALOGE_IF(result != NO_ERROR,
2199 "prepareFrame for display %d failed:"
2200 " %d (%s)",
2201 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002202}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002203
David Sodman10a41ff2018-08-05 12:14:17 -07002204void SurfaceFlinger::setUpHWComposer(const CompositionInfo& compositionInfo) {
2205 ATRACE_CALL();
2206 ALOGV("setUpHWComposer");
2207
2208 switch (compositionInfo.compositionType)
2209 {
2210 case HWC2::Composition::Invalid:
David Sodmana6d42332018-08-29 14:07:04 -07002211 break;
2212
David Sodman10a41ff2018-08-05 12:14:17 -07002213 case HWC2::Composition::Client:
David Sodmana6d42332018-08-29 14:07:04 -07002214 if (compositionInfo.hwc.hwcLayer) {
2215 auto error = (compositionInfo.hwc.hwcLayer)->
2216 setCompositionType(compositionInfo.compositionType);
2217 ALOGE_IF(error != HWC2::Error::None,
2218 "[SF] Failed to set composition type: %s (%d)",
2219 to_string(error).c_str(), static_cast<int32_t>(error));
2220 }
David Sodman10a41ff2018-08-05 12:14:17 -07002221 break;
2222
2223 case HWC2::Composition::Sideband:
2224 configureHwcCommonData(compositionInfo);
2225 configureSidebandComposition(compositionInfo);
2226 break;
2227
2228 case HWC2::Composition::SolidColor:
2229 configureHwcCommonData(compositionInfo);
2230 break;
2231
2232 case HWC2::Composition::Device:
2233 case HWC2::Composition::Cursor:
2234 configureHwcCommonData(compositionInfo);
2235 configureDeviceComposition(compositionInfo);
2236 break;
2237 }
2238}
2239
David Sodmanfa9b2af2017-12-24 13:28:59 -08002240void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002241 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002242 ALOGV("doComposition");
2243
David Sodmanfa9b2af2017-12-24 13:28:59 -08002244 if (display->isPoweredOn()) {
2245 // transform the dirty region into this screen's coordinate space
2246 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002247
David Sodmanfa9b2af2017-12-24 13:28:59 -08002248 // repaint the framebuffer (if needed)
2249 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002250
David Sodmanfa9b2af2017-12-24 13:28:59 -08002251 display->dirtyRegion.clear();
2252 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002253 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002254 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002255}
2256
David Sodmanfa9b2af2017-12-24 13:28:59 -08002257void SurfaceFlinger::postFrame()
2258{
2259 // |mStateLock| not needed as we are on the main thread
2260 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2261 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2262 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2263 logFrameStats();
2264 }
2265 }
2266}
2267
2268void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002269{
Mathias Agopian841cde52012-03-01 15:44:37 -08002270 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002271 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002272
David Sodmanfa9b2af2017-12-24 13:28:59 -08002273 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002274
David Sodmanfa9b2af2017-12-24 13:28:59 -08002275 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002276 const auto displayId = display->getId();
2277 if (displayId >= 0) {
2278 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002279 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002280 display->onSwapBuffersCompleted();
2281 display->makeCurrent();
David Sodman10a41ff2018-08-05 12:14:17 -07002282 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002283 sp<Fence> releaseFence = Fence::NO_FENCE;
Chia-I Wu7b549592017-11-15 09:14:57 -08002284 // The layer buffer from the previous frame (if any) is released
2285 // by HWC only when the release fence from this frame (if any) is
2286 // signaled. Always get the release fence from HWC first.
David Sodman10a41ff2018-08-05 12:14:17 -07002287 auto hwcLayer = compositionInfo.hwc.hwcLayer;
2288 if ((displayId >= 0) && hwcLayer) {
2289 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer.get());
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002290 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002291
2292 // If the layer was client composited in the previous frame, we
2293 // need to merge with the previous client target acquire fence.
2294 // Since we do not track that, always merge with the current
2295 // client target acquire fence when it is available, even though
2296 // this is suboptimal.
David Sodman10a41ff2018-08-05 12:14:17 -07002297 if (compositionInfo.compositionType == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002298 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002299 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002300 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002301
David Sodman10a41ff2018-08-05 12:14:17 -07002302 if (compositionInfo.layer) {
2303 compositionInfo.layer->onLayerDisplayed(releaseFence);
2304 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002305 }
Chia-I Wu83806892017-11-16 10:50:20 -08002306
2307 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002308 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002309 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002310 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002311 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002312 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002313 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002314 }
2315 }
2316
Dominik Laskowski7e045462018-05-30 13:02:02 -07002317 if (displayId >= 0) {
2318 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002319 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002320 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002321}
2322
Mathias Agopian87baae12012-07-31 12:38:26 -07002323void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002324{
Mathias Agopian841cde52012-03-01 15:44:37 -08002325 ATRACE_CALL();
2326
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002327 // here we keep a copy of the drawing state (that is the state that's
2328 // going to be overwritten by handleTransactionLocked()) outside of
2329 // mStateLock so that the side-effects of the State assignment
2330 // don't happen with mStateLock held (which can cause deadlocks).
2331 State drawingState(mDrawingState);
2332
Mathias Agopianca4d3602011-05-19 15:38:14 -07002333 Mutex::Autolock _l(mStateLock);
2334 const nsecs_t now = systemTime();
2335 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002336
Mathias Agopianca4d3602011-05-19 15:38:14 -07002337 // Here we're guaranteed that some transaction flags are set
2338 // so we can call handleTransactionLocked() unconditionally.
2339 // We call getTransactionFlags(), which will also clear the flags,
2340 // with mStateLock held to guarantee that mCurrentState won't change
2341 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002342
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002343 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002344 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002345 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002346
Mathias Agopianca4d3602011-05-19 15:38:14 -07002347 mLastTransactionTime = systemTime() - now;
2348 mDebugInTransaction = 0;
2349 invalidateHwcGeometry();
2350 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002351}
2352
Dominik Laskowski7e045462018-05-30 13:02:02 -07002353DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002354 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002355 // Figure out whether the event is for the primary display or an
2356 // external display by matching the Hwc display id against one for a
2357 // connected display. If we did not find a match, we then check what
2358 // displays are not already connected to determine the type. If we don't
2359 // have a connected primary display, we assume the new display is meant to
2360 // be the primary display, and then if we don't have an external display,
2361 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002362 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2363 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002364 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002365 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002366 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002367 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002368 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002369 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002370 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002371 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002372 return DisplayDevice::DISPLAY_EXTERNAL;
2373 }
2374
2375 return DisplayDevice::DISPLAY_ID_INVALID;
2376}
2377
Lloyd Piqueba04e622017-12-14 17:11:26 -08002378void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2379 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002380 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002381 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002382 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002383 continue;
2384 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002385
2386 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2387 ALOGE("External displays are not supported by the vr hardware composer.");
2388 continue;
2389 }
2390
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002391 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002392 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002393 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002394 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002395 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002396
2397 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002398 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002399 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002400 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002401 DisplayDeviceState info;
2402 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002403 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2404 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002405 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002406 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002407 mInterceptor->saveDisplayCreation(info);
2408 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002409 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002410 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002411
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002412 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002413 if (idx >= 0) {
2414 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002415 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002416 mCurrentState.displays.removeItemsAt(idx);
2417 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002418 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002419 }
2420
2421 processDisplayChangesLocked();
2422 }
2423
2424 mPendingHotplugEvents.clear();
2425}
2426
Lloyd Pique99d3da52018-01-22 17:48:03 -08002427sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002428 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002429 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002430 DisplayDeviceCreationArgs creationArgs(this, displayToken, state.type, displayId);
2431 creationArgs.isSecure = state.isSecure;
2432 creationArgs.displaySurface = dispSurface;
2433 creationArgs.hasWideColorGamut = false;
2434 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002435
Peiyong Lin13effd12018-07-24 17:01:47 -07002436 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002437 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002438 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002439 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002440 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002441 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002442
Dominik Laskowski7e045462018-05-30 13:02:02 -07002443 std::vector<RenderIntent> renderIntents =
2444 getHwComposer().getRenderIntents(displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002445 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002446 }
tangrobin6753a022018-08-10 10:58:54 +08002447 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002448
tangrobin6753a022018-08-10 10:58:54 +08002449 if (displayId >= 0) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002450 getHwComposer().getHdrCapabilities(displayId, &creationArgs.hdrCapabilities);
2451 creationArgs.supportedPerFrameMetadata =
2452 getHwComposer().getSupportedPerFrameMetadata(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002453 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002454
2455 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2456 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002457 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002458
2459 /*
2460 * Create our display's surface
2461 */
Peiyong Lin833074a2018-08-28 11:53:54 -07002462 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002463 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002464 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002465 renderSurface->setNativeWindow(nativeWindow.get());
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002466 creationArgs.displayWidth = renderSurface->getWidth();
2467 creationArgs.displayHeight = renderSurface->getHeight();
2468 creationArgs.renderSurface = std::move(renderSurface);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002469
2470 // Make sure that composition can never be stalled by a virtual display
2471 // consumer that isn't processing buffers fast enough. We have to do this
2472 // in two places:
2473 // * Here, in case the display is composed entirely by HWC.
2474 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2475 // window's swap interval in eglMakeCurrent, so they'll override the
2476 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002477 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002478 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2479 }
2480
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002481 creationArgs.displayInstallOrientation = state.type == DisplayDevice::DISPLAY_PRIMARY
2482 ? primaryDisplayOrientation
2483 : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002484
Lloyd Pique99d3da52018-01-22 17:48:03 -08002485 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002486 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002487
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002488 sp<DisplayDevice> display = new DisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002489
2490 if (maxFrameBufferAcquiredBuffers >= 3) {
2491 nativeWindowSurface->preallocateBuffers();
2492 }
2493
2494 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002495 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002496 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002497 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002498 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002499 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002500 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002501 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002502 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002503 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002504 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002505 display->setLayerStack(state.layerStack);
2506 display->setProjection(state.orientation, state.viewport, state.frame);
2507 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002508
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002509 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002510}
2511
Lloyd Pique347200f2017-12-14 17:00:15 -08002512void SurfaceFlinger::processDisplayChangesLocked() {
2513 // here we take advantage of Vector's copy-on-write semantics to
2514 // improve performance by skipping the transaction entirely when
2515 // know that the lists are identical
2516 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2517 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2518 if (!curr.isIdenticalTo(draw)) {
2519 mVisibleRegionsDirty = true;
2520 const size_t cc = curr.size();
2521 size_t dc = draw.size();
2522
2523 // find the displays that were removed
2524 // (ie: in drawing state but not in current state)
2525 // also handle displays that changed
2526 // (ie: displays that are in both lists)
2527 for (size_t i = 0; i < dc;) {
2528 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2529 if (j < 0) {
2530 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002531 // Call makeCurrent() on the primary display so we can
2532 // be sure that nothing associated with this display
2533 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002534 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2535 defaultDisplay->makeCurrent();
2536 }
2537 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2538 display->disconnect(getHwComposer());
2539 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002540 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002541 if (mUseScheduler) {
2542 mScheduler->hotplugReceived(mAppConnectionHandle,
2543 EventThread::DisplayType::Primary, false);
2544 } else {
2545 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2546 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002547 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002548 if (mUseScheduler) {
2549 mScheduler->hotplugReceived(mAppConnectionHandle,
2550 EventThread::DisplayType::External, false);
2551 } else {
2552 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2553 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002554 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002555 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002556 } else {
2557 // this display is in both lists. see if something changed.
2558 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002559 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002560 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2561 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2562 if (state_binder != draw_binder) {
2563 // changing the surface is like destroying and
2564 // recreating the DisplayDevice, so we just remove it
2565 // from the drawing state, so that it get re-added
2566 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002567 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2568 display->disconnect(getHwComposer());
2569 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002570 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002571 mDrawingState.displays.removeItemsAt(i);
2572 dc--;
2573 // at this point we must loop to the next item
2574 continue;
2575 }
2576
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002577 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002578 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002579 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002580 }
2581 if ((state.orientation != draw[i].orientation) ||
2582 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002583 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002584 }
2585 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002586 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002587 }
2588 }
2589 }
2590 ++i;
2591 }
2592
2593 // find displays that were added
2594 // (ie: in current state but not in drawing state)
2595 for (size_t i = 0; i < cc; i++) {
2596 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2597 const DisplayDeviceState& state(curr[i]);
2598
2599 sp<DisplaySurface> dispSurface;
2600 sp<IGraphicBufferProducer> producer;
2601 sp<IGraphicBufferProducer> bqProducer;
2602 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002603 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002604
Dominik Laskowski7e045462018-05-30 13:02:02 -07002605 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002606 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002607 // Virtual displays without a surface are dormant:
2608 // they have external state (layer stack, projection,
2609 // etc.) but no internal state (i.e. a DisplayDevice).
2610 if (state.surface != nullptr) {
2611 // Allow VR composer to use virtual displays.
2612 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2613 int width = 0;
2614 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2615 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2616 int height = 0;
2617 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2618 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2619 int intFormat = 0;
2620 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2621 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002622 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002623
Dominik Laskowski7e045462018-05-30 13:02:02 -07002624 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2625 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002626 }
2627
2628 // TODO: Plumb requested format back up to consumer
2629
2630 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002631 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002632 bqProducer, bqConsumer,
2633 state.displayName);
2634
2635 dispSurface = vds;
2636 producer = vds;
2637 }
2638 } else {
2639 ALOGE_IF(state.surface != nullptr,
2640 "adding a supported display, but rendering "
2641 "surface is provided (%p), ignoring it",
2642 state.surface.get());
2643
Dominik Laskowski7e045462018-05-30 13:02:02 -07002644 displayId = state.type;
2645 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002646 producer = bqProducer;
2647 }
2648
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002649 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002650 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002651 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002652 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002653 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002654 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002655 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002656 if (mUseScheduler) {
2657 mScheduler->hotplugReceived(mAppConnectionHandle,
2658 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002659 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002660 } else {
2661 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2662 true);
2663 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002664 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002665 if (mUseScheduler) {
2666 mScheduler->hotplugReceived(mAppConnectionHandle,
2667 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002668 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002669 } else {
2670 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2671 true);
2672 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002673 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002674 }
2675 }
2676 }
2677 }
2678 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002679
2680 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002681}
2682
Mathias Agopian87baae12012-07-31 12:38:26 -07002683void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002684{
Dan Stoza7dde5992015-05-22 09:51:44 -07002685 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002686 mCurrentState.traverseInZOrder([](Layer* layer) {
2687 layer->notifyAvailableFrames();
2688 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002689
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002690 /*
2691 * Traversal of the children
2692 * (perform the transaction for each of them if needed)
2693 */
2694
Mathias Agopian3559b072012-08-15 13:46:03 -07002695 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002696 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002697 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002698 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002699
2700 const uint32_t flags = layer->doTransaction(0);
2701 if (flags & Layer::eVisibleRegion)
2702 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002703 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002704 }
2705
2706 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002707 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002708 */
2709
Mathias Agopiane57f2922012-08-09 16:29:12 -07002710 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002711 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002712 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002713 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002714
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002715 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002716 // The transform hint might have changed for some layers
2717 // (either because a display has changed, or because a layer
2718 // as changed).
2719 //
2720 // Walk through all the layers in currentLayers,
2721 // and update their transform hint.
2722 //
2723 // If a layer is visible only on a single display, then that
2724 // display is used to calculate the hint, otherwise we use the
2725 // default display.
2726 //
2727 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2728 // the hint is set before we acquire a buffer from the surface texture.
2729 //
2730 // NOTE: layer transactions have taken place already, so we use their
2731 // drawing state. However, SurfaceFlinger's own transaction has not
2732 // happened yet, so we must use the current state layer list
2733 // (soon to become the drawing state list).
2734 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002735 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002736 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002737 bool first = true;
2738 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002739 // NOTE: we rely on the fact that layers are sorted by
2740 // layerStack first (so we don't have to traverse the list
2741 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002742 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002743 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002744 currentlayerStack = layerStack;
2745 // figure out if this layerstack is mirrored
2746 // (more than one display) if so, pick the default display,
2747 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002748 hintDisplay = nullptr;
2749 for (const auto& [token, display] : mDisplays) {
2750 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2751 if (hintDisplay) {
2752 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002753 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002754 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002755 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002756 }
2757 }
2758 }
2759 }
Chet Haase91d25932013-04-11 15:24:55 -07002760
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002761 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002762 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2763 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002764
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002765 // could be null when this layer is using a layerStack
2766 // that is not visible on any display. Also can occur at
2767 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002768 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002769 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002770
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002771 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002772 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002773 if (hintDisplay) {
2774 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002775 }
Robert Carr2047fae2016-11-28 14:09:09 -08002776
2777 first = false;
2778 });
Mathias Agopian84300952012-11-21 16:02:13 -08002779 }
2780
2781
Mathias Agopian3559b072012-08-15 13:46:03 -07002782 /*
2783 * Perform our own transaction if needed
2784 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002785
2786 if (mLayersAdded) {
2787 mLayersAdded = false;
2788 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002789 mVisibleRegionsDirty = true;
2790 }
2791
2792 // some layers might have been removed, so
2793 // we need to update the regions they're exposing.
2794 if (mLayersRemoved) {
2795 mLayersRemoved = false;
2796 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002797 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002798 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002799 // this layer is not visible anymore
2800 // TODO: we could traverse the tree from front to back and
2801 // compute the actual visible region
2802 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002803 Region visibleReg;
2804 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002805 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002806 }
Robert Carr2047fae2016-11-28 14:09:09 -08002807 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002808 }
2809
2810 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002811
2812 updateCursorAsync();
2813}
2814
2815void SurfaceFlinger::updateCursorAsync()
2816{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002817 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002818 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002819 continue;
2820 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002821
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002822 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2823 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002824 }
2825 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002826}
2827
2828void SurfaceFlinger::commitTransaction()
2829{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002830 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002831 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002832 for (const auto& l : mLayersPendingRemoval) {
2833 recordBufferingStats(l->getName().string(),
2834 l->getOccupancyHistory(true));
2835 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002836 }
2837 mLayersPendingRemoval.clear();
2838 }
2839
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002840 // If this transaction is part of a window animation then the next frame
2841 // we composite should be considered an animation as well.
2842 mAnimCompositionPending = mAnimTransactionPending;
2843
Mathias Agopian4fec8732012-06-29 14:12:52 -07002844 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002845 // clear the "changed" flags in current state
2846 mCurrentState.colorMatrixChanged = false;
2847
Robert Carr1f0a16a2016-10-24 16:27:39 -07002848 mDrawingState.traverseInZOrder([](Layer* layer) {
2849 layer->commitChildList();
2850 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002851 mTransactionPending = false;
2852 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002853 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002854}
2855
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002856void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2857 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002858 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002859 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002860
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002861 Region aboveOpaqueLayers;
2862 Region aboveCoveredLayers;
2863 Region dirty;
2864
Mathias Agopian87baae12012-07-31 12:38:26 -07002865 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002866
Robert Carr2047fae2016-11-28 14:09:09 -08002867 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002868 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002869 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002870
Jesse Hall01e29052013-02-19 16:13:35 -08002871 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002872 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002873 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002874 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002875
Mathias Agopianab028732010-03-16 16:41:46 -07002876 /*
2877 * opaqueRegion: area of a surface that is fully opaque.
2878 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002879 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002880
2881 /*
2882 * visibleRegion: area of a surface that is visible on screen
2883 * and not fully transparent. This is essentially the layer's
2884 * footprint minus the opaque regions above it.
2885 * Areas covered by a translucent surface are considered visible.
2886 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002887 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002888
2889 /*
2890 * coveredRegion: area of a surface that is covered by all
2891 * visible regions above it (which includes the translucent areas).
2892 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002893 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002894
Jesse Halla8026d22012-09-25 13:25:04 -07002895 /*
2896 * transparentRegion: area of a surface that is hinted to be completely
2897 * transparent. This is only used to tell when the layer has no visible
2898 * non-transparent regions and can be removed from the layer list. It
2899 * does not affect the visibleRegion of this layer or any layers
2900 * beneath it. The hint may not be correct if apps don't respect the
2901 * SurfaceView restrictions (which, sadly, some don't).
2902 */
2903 Region transparentRegion;
2904
Mathias Agopianab028732010-03-16 16:41:46 -07002905
2906 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002907 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002908 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002909 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002910 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002911 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002912 if (!visibleRegion.isEmpty()) {
2913 // Remove the transparent area from the visible region
2914 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002915 if (tr.preserveRects()) {
2916 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002917 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002918 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002919 // transformation too complex, can't do the
2920 // transparent region optimization.
2921 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002922 }
Mathias Agopianab028732010-03-16 16:41:46 -07002923 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002924
Mathias Agopianab028732010-03-16 16:41:46 -07002925 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002926 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002927 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002928 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002929 // the opaque region is the layer's footprint
2930 opaqueRegion = visibleRegion;
2931 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002932 }
2933 }
2934
Robert Carre5f4f692018-01-12 13:12:28 -08002935 if (visibleRegion.isEmpty()) {
2936 layer->clearVisibilityRegions();
2937 return;
2938 }
2939
Mathias Agopianab028732010-03-16 16:41:46 -07002940 // Clip the covered region to the visible region
2941 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2942
2943 // Update aboveCoveredLayers for next (lower) layer
2944 aboveCoveredLayers.orSelf(visibleRegion);
2945
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002946 // subtract the opaque region covered by the layers above us
2947 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002948
2949 // compute this layer's dirty region
2950 if (layer->contentDirty) {
2951 // we need to invalidate the whole region
2952 dirty = visibleRegion;
2953 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002954 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002955 layer->contentDirty = false;
2956 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002957 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002958 * the exposed region consists of two components:
2959 * 1) what's VISIBLE now and was COVERED before
2960 * 2) what's EXPOSED now less what was EXPOSED before
2961 *
2962 * note that (1) is conservative, we start with the whole
2963 * visible region but only keep what used to be covered by
2964 * something -- which mean it may have been exposed.
2965 *
2966 * (2) handles areas that were not covered by anything but got
2967 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002968 */
Mathias Agopianab028732010-03-16 16:41:46 -07002969 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002970 const Region oldVisibleRegion = layer->visibleRegion;
2971 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002972 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2973 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002974 }
2975 dirty.subtractSelf(aboveOpaqueLayers);
2976
2977 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002978 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002979
Mathias Agopianab028732010-03-16 16:41:46 -07002980 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002981 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002982
Jesse Halla8026d22012-09-25 13:25:04 -07002983 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002984 layer->setVisibleRegion(visibleRegion);
2985 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002986 layer->setVisibleNonTransparentRegion(
2987 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002988 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002989
Mathias Agopian87baae12012-07-31 12:38:26 -07002990 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002991}
2992
Chia-I Wuab0c3192017-08-01 11:29:00 -07002993void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002994 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002995 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2996 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002997 }
2998 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002999}
3000
Dan Stoza6b9454d2014-11-07 16:00:59 -08003001bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003002{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003003 ALOGV("handlePageFlip");
3004
Brian Andersond6927fb2016-07-23 23:37:30 -07003005 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003006
Mathias Agopian4fec8732012-06-29 14:12:52 -07003007 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003008 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003009 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003010
3011 // Store the set of layers that need updates. This set must not change as
3012 // buffers are being latched, as this could result in a deadlock.
3013 // Example: Two producers share the same command stream and:
3014 // 1.) Layer 0 is latched
3015 // 2.) Layer 0 gets a new frame
3016 // 2.) Layer 1 gets a new frame
3017 // 3.) Layer 1 is latched.
3018 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3019 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003020 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003021 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003022 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07003023 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003024 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003025 } else {
3026 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003027 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003028 } else {
3029 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003030 }
Robert Carr2047fae2016-11-28 14:09:09 -08003031 });
3032
Dan Stoza9e56aa02015-11-02 13:00:03 -08003033 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07003034 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07003035 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003036 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07003037 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06003038 newDataLatched = true;
3039 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003040 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003041
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003042 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003043
3044 // If we will need to wake up at some time in the future to deal with a
3045 // queued frame that shouldn't be displayed during this vsync period, wake
3046 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003047 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003048 signalLayerUpdate();
3049 }
3050
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003051 // enter boot animation on first buffer latch
3052 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3053 ALOGI("Enter boot animation");
3054 mBootStage = BootStage::BOOTANIMATION;
3055 }
3056
Dan Stoza6b9454d2014-11-07 16:00:59 -08003057 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003058 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003059}
3060
Mathias Agopianad456f92011-01-13 17:53:01 -08003061void SurfaceFlinger::invalidateHwcGeometry()
3062{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003063 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003064}
3065
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003066void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
3067 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003068 // We only need to actually compose the display if:
3069 // 1) It is being handled by hardware composer, which may need this to
3070 // keep its virtual display state machine in sync, or
3071 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07003072 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08003073 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003074 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003075 return;
3076 }
3077
Dan Stoza9e56aa02015-11-02 13:00:03 -08003078 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003079 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003080
3081 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003082 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003083}
3084
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003085bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003086 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003087
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003088 const Region bounds(display->bounds());
3089 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003090 const auto displayId = display->getId();
3091 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003092 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003093
Chia-I Wu8e50e692018-05-04 10:12:37 -07003094 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003095 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003096
Dan Stoza9e56aa02015-11-02 13:00:03 -08003097 if (hasClientComposition) {
3098 ALOGV("hasClientComposition");
3099
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003100 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003101 if (display->hasWideColorGamut()) {
3102 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003103 }
3104 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003105 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003106 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003107
Dominik Laskowski7e045462018-05-30 13:02:02 -07003108 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003109 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3110 HWC2::Capability::SkipClientColorTransform);
3111
Chia-I Wud49d6692018-06-27 07:17:41 +08003112 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003113 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3114 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003115 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003116 }
3117
Chia-I Wud49d6692018-06-27 07:17:41 +08003118 // The current enhanced saturation matrix is designed to enhance Display P3,
3119 // thus we only apply this matrix when the render intent is not colorimetric
3120 // and the output color space is Display P3.
3121 needsEnhancedColorMatrix =
3122 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3123 outputDataspace == Dataspace::DISPLAY_P3);
3124 if (needsEnhancedColorMatrix) {
3125 colorMatrix *= mEnhancedSaturationMatrix;
3126 }
3127
3128 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003129
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003130 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003131 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003132 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003133 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003134
3135 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003136 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3137 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3138 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003139 }
3140 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003141 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003142
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003143 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003144 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003145 // when using overlays, we assume a fully transparent framebuffer
3146 // NOTE: we could reduce how much we need to clear, for instance
3147 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003148 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003149 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003150 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003151 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003152 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003153 // we're left with the letterbox region
3154 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003155 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003156
3157 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003158 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003159
Mathias Agopianb9494d52012-04-18 02:28:45 -07003160 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003161 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003162 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003163 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003164 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003165 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003166
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003167 const Rect& bounds = display->getBounds();
3168 const Rect& scissor = display->getScissor();
3169 if (scissor != bounds) {
3170 // scissor doesn't match the screen's dimensions, so we
3171 // need to clear everything outside of it and enable
3172 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003173
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003174 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003175 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003176 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003177 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003178
Mathias Agopian85d751c2012-08-29 16:59:24 -07003179 /*
3180 * and then, render the layers targeted at the framebuffer
3181 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003182
Dan Stoza9e56aa02015-11-02 13:00:03 -08003183 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003184 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003185 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003186 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003187 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003188 displayTransform.transform(layer->visibleRegion)));
3189 ALOGV("Layer: %s", layer->getName().string());
3190 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003191 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003192 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003193 case HWC2::Composition::Cursor:
3194 case HWC2::Composition::Device:
3195 case HWC2::Composition::Sideband:
3196 case HWC2::Composition::SolidColor: {
David Sodmanc1498e62018-09-12 14:36:26 -07003197 const Layer::State& state(layer->getDrawingState());
3198 if (layer->getClearClientTarget(displayId) && !firstLayer &&
3199 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3200 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003201 // never clear the very first layer since we're
3202 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003203 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003204 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003205 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003206 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003207 case HWC2::Composition::Client: {
David Sodmanc1498e62018-09-12 14:36:26 -07003208 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003209 break;
3210 }
3211 default:
3212 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003213 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003214 } else {
3215 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003216 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003217 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003218 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003219
Chia-I Wud49d6692018-06-27 07:17:41 +08003220 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003221 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003222 }
3223
Mathias Agopianf45c5102012-10-24 16:29:17 -07003224 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003225 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003226 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003227}
3228
Chia-I Wu28e3a252018-09-07 12:05:02 -07003229void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003230 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003231 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003232}
3233
Dan Stoza7d89d062015-04-30 13:29:25 -07003234status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003235 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003236 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003237 const sp<Layer>& lbc,
3238 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003239{
Dan Stoza7d89d062015-04-30 13:29:25 -07003240 // add this layer to the current state list
3241 {
3242 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003243 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003244 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3245 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003246 return NO_MEMORY;
3247 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003248 if (parent == nullptr) {
3249 mCurrentState.layersSortedByZ.add(lbc);
3250 } else {
Rob Carr4bba3702018-10-08 21:53:30 +00003251 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003252 ALOGE("addClientLayer called with a removed parent");
3253 return NAME_NOT_FOUND;
3254 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003255 parent->addChild(lbc);
3256 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003257
Yiwei Zhang243b3782018-05-15 17:40:04 -07003258 if (gbc != nullptr) {
3259 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3260 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3261 mMaxGraphicBufferProducerListSize,
3262 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3263 mGraphicBufferProducerList.size(),
3264 mMaxGraphicBufferProducerListSize, mNumLayers);
3265 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003266 mLayersAdded = true;
3267 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003268 }
3269
Mathias Agopian96f08192010-06-02 23:28:45 -07003270 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003271 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003272
Dan Stoza7d89d062015-04-30 13:29:25 -07003273 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003274}
3275
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003276status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003277 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003278 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3279}
Robert Carr7f9b8992017-03-10 11:08:39 -08003280
chaviwca27f252018-02-06 16:46:39 -08003281status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3282 bool topLevelOnly) {
Rob Carr4bba3702018-10-08 21:53:30 +00003283 if (layer->isPendingRemoval()) {
chaviw8b3871a2017-11-01 17:41:01 -07003284 return NO_ERROR;
3285 }
3286
Robert Carr1f0a16a2016-10-24 16:27:39 -07003287 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003288 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003289 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003290 if (topLevelOnly) {
3291 return NO_ERROR;
3292 }
Rob Carr4bba3702018-10-08 21:53:30 +00003293
3294 sp<Layer> ancestor = p;
3295 while (ancestor->getParent() != nullptr) {
3296 ancestor = ancestor->getParent();
3297 }
3298 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3299 ALOGE("removeLayer called with a layer whose parent has been removed");
3300 return NAME_NOT_FOUND;
3301 }
3302
Chia-I Wufae51c42017-06-15 12:53:59 -07003303 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003304 } else {
3305 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003306 }
3307
Rob Carr4bba3702018-10-08 21:53:30 +00003308 // As a matter of normal operation, the LayerCleaner will produce a second
3309 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3310 // so we will succeed in promoting it, but it's already been removed
3311 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3312 // otherwise something has gone wrong and we are leaking the layer.
3313 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
3314 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3315 layer->getName().string(),
3316 (p != nullptr) ? p->getName().string() : "no-parent");
3317 return BAD_VALUE;
3318 } else if (index < 0) {
3319 return NO_ERROR;
3320 }
3321
Chia-I Wuc6657022017-08-15 11:18:17 -07003322 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003323 mLayersPendingRemoval.add(layer);
3324 mLayersRemoved = true;
Rob Carr4bba3702018-10-08 21:53:30 +00003325 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003326 setTransactionFlags(eTransactionNeeded);
3327 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003328}
3329
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003330uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003331 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003332}
3333
Mathias Agopian3f844832013-08-07 21:24:32 -07003334uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003335 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003336}
3337
Mathias Agopian3f844832013-08-07 21:24:32 -07003338uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003339 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3340}
3341
3342uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3343 VSyncModulator::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003344 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003345 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003346 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003347 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003348 }
3349 return old;
3350}
3351
chaviwca27f252018-02-06 16:46:39 -08003352bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3353 for (const ComposerState& state : states) {
3354 // Here we need to check that the interface we're given is indeed
3355 // one of our own. A malicious client could give us a nullptr
3356 // IInterface, or one of its own or even one of our own but a
3357 // different type. All these situations would cause us to crash.
3358 if (state.client == nullptr) {
3359 return true;
3360 }
3361
3362 sp<IBinder> binder = IInterface::asBinder(state.client);
3363 if (binder == nullptr) {
3364 return true;
3365 }
3366
3367 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3368 return true;
3369 }
3370 }
3371 return false;
3372}
3373
Mathias Agopian8b33f032012-07-24 20:43:54 -07003374void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003375 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003376 const Vector<DisplayState>& displays,
3377 uint32_t flags)
3378{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003379 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003380 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003381 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003382
chaviwca27f252018-02-06 16:46:39 -08003383 if (containsAnyInvalidClientState(states)) {
3384 return;
3385 }
3386
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003387 if (flags & eAnimation) {
3388 // For window updates that are part of an animation we must wait for
3389 // previous animation "frames" to be handled.
3390 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003391 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003392 if (CC_UNLIKELY(err != NO_ERROR)) {
3393 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003394 // caller after a few seconds.
3395 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3396 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003397 mAnimTransactionPending = false;
3398 break;
3399 }
3400 }
3401 }
3402
chaviwca27f252018-02-06 16:46:39 -08003403 for (const DisplayState& display : displays) {
3404 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003405 }
3406
chaviwca27f252018-02-06 16:46:39 -08003407 for (const ComposerState& state : states) {
3408 transactionFlags |= setClientStateLocked(state);
3409 }
3410
3411 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3412 // as destroyed should only occur after setting all other states. This is to allow for a
3413 // child re-parent to happen before marking its original parent as destroyed (which would
3414 // then mark the child as destroyed).
3415 for (const ComposerState& state : states) {
3416 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003417 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003418
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003419 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3420 // anyway. This can be used as a flush mechanism for previous async transactions.
3421 // Empty animation transaction can be used to simulate back-pressure, so also force a
3422 // transaction for empty animation transactions.
3423 if (transactionFlags == 0 &&
3424 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003425 transactionFlags = eTransactionNeeded;
3426 }
3427
Mathias Agopian386aa982011-11-07 21:58:03 -08003428 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003429 if (mInterceptor->isEnabled()) {
3430 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003431 }
Irvel468051e2016-06-13 16:44:44 -07003432
Mathias Agopian386aa982011-11-07 21:58:03 -08003433 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003434 const auto start = (flags & eEarlyWakeup)
3435 ? VSyncModulator::TransactionStart::EARLY
3436 : VSyncModulator::TransactionStart::NORMAL;
3437 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003438
3439 // if this is a synchronous transaction, wait for it to take effect
3440 // before returning.
3441 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003442 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003443 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003444 if (flags & eAnimation) {
3445 mAnimTransactionPending = true;
3446 }
3447 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003448 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3449 if (CC_UNLIKELY(err != NO_ERROR)) {
3450 // just in case something goes wrong in SF, return to the
3451 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003452 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3453 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003454 break;
3455 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003456 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003457 }
3458}
3459
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003460uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3461 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3462 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003463
Mathias Agopiane57f2922012-08-09 16:29:12 -07003464 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003465 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3466
3467 const uint32_t what = s.what;
3468 if (what & DisplayState::eSurfaceChanged) {
3469 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3470 state.surface = s.surface;
3471 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003472 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003473 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003474 if (what & DisplayState::eLayerStackChanged) {
3475 if (state.layerStack != s.layerStack) {
3476 state.layerStack = s.layerStack;
3477 flags |= eDisplayTransactionNeeded;
3478 }
3479 }
3480 if (what & DisplayState::eDisplayProjectionChanged) {
3481 if (state.orientation != s.orientation) {
3482 state.orientation = s.orientation;
3483 flags |= eDisplayTransactionNeeded;
3484 }
3485 if (state.frame != s.frame) {
3486 state.frame = s.frame;
3487 flags |= eDisplayTransactionNeeded;
3488 }
3489 if (state.viewport != s.viewport) {
3490 state.viewport = s.viewport;
3491 flags |= eDisplayTransactionNeeded;
3492 }
3493 }
3494 if (what & DisplayState::eDisplaySizeChanged) {
3495 if (state.width != s.width) {
3496 state.width = s.width;
3497 flags |= eDisplayTransactionNeeded;
3498 }
3499 if (state.height != s.height) {
3500 state.height = s.height;
3501 flags |= eDisplayTransactionNeeded;
3502 }
3503 }
3504
Mathias Agopiane57f2922012-08-09 16:29:12 -07003505 return flags;
3506}
3507
Robert Carrd4ae7f32018-06-07 16:10:57 -07003508bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3509 IPCThreadState* ipc = IPCThreadState::self();
3510 const int pid = ipc->getCallingPid();
3511 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003512 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003513 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003514 return false;
3515 }
3516 return true;
3517}
3518
chaviwca27f252018-02-06 16:46:39 -08003519uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3520 const layer_state_t& s = composerState.state;
3521 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3522
Mathias Agopian13127d82013-03-05 17:47:11 -08003523 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003524 if (layer == nullptr) {
3525 return 0;
3526 }
3527
Rob Carr4bba3702018-10-08 21:53:30 +00003528 if (layer->isPendingRemoval()) {
chaviw8b3871a2017-11-01 17:41:01 -07003529 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3530 return 0;
3531 }
3532
3533 uint32_t flags = 0;
3534
3535 const uint32_t what = s.what;
3536 bool geometryAppliesWithResize =
3537 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003538
3539 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3540 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003541 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003542 layer->pushPendingState();
3543 }
3544
chaviw8b3871a2017-11-01 17:41:01 -07003545 if (what & layer_state_t::ePositionChanged) {
3546 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3547 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003548 }
chaviw8b3871a2017-11-01 17:41:01 -07003549 }
3550 if (what & layer_state_t::eLayerChanged) {
3551 // NOTE: index needs to be calculated before we update the state
3552 const auto& p = layer->getParent();
3553 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003554 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003555 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003556 mCurrentState.layersSortedByZ.removeAt(idx);
3557 mCurrentState.layersSortedByZ.add(layer);
3558 // we need traversal (state changed)
3559 // AND transaction (list changed)
3560 flags |= eTransactionNeeded|eTraversalNeeded;
3561 }
chaviw8b3871a2017-11-01 17:41:01 -07003562 } else {
3563 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003564 flags |= eTransactionNeeded|eTraversalNeeded;
3565 }
3566 }
chaviw8b3871a2017-11-01 17:41:01 -07003567 }
3568 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003569 // NOTE: index needs to be calculated before we update the state
3570 const auto& p = layer->getParent();
3571 if (p == nullptr) {
3572 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3573 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3574 mCurrentState.layersSortedByZ.removeAt(idx);
3575 mCurrentState.layersSortedByZ.add(layer);
3576 // we need traversal (state changed)
3577 // AND transaction (list changed)
3578 flags |= eTransactionNeeded|eTraversalNeeded;
3579 }
3580 } else {
3581 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3582 flags |= eTransactionNeeded|eTraversalNeeded;
3583 }
chaviw8b3871a2017-11-01 17:41:01 -07003584 }
3585 }
3586 if (what & layer_state_t::eSizeChanged) {
3587 if (layer->setSize(s.w, s.h)) {
3588 flags |= eTraversalNeeded;
3589 }
3590 }
3591 if (what & layer_state_t::eAlphaChanged) {
3592 if (layer->setAlpha(s.alpha))
3593 flags |= eTraversalNeeded;
3594 }
3595 if (what & layer_state_t::eColorChanged) {
3596 if (layer->setColor(s.color))
3597 flags |= eTraversalNeeded;
3598 }
3599 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003600 // TODO: b/109894387
3601 //
3602 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3603 // rotation. To see the problem observe that if we have a square parent, and a child
3604 // of the same size, then we rotate the child 45 degrees around it's center, the child
3605 // must now be cropped to a non rectangular 8 sided region.
3606 //
3607 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3608 // private API, and the WindowManager only uses rotation in one case, which is on a top
3609 // level layer in which cropping is not an issue.
3610 //
3611 // However given that abuse of rotation matrices could lead to surfaces extending outside
3612 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3613 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3614 // transformations.
3615 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003616 flags |= eTraversalNeeded;
3617 }
3618 if (what & layer_state_t::eTransparentRegionChanged) {
3619 if (layer->setTransparentRegionHint(s.transparentRegion))
3620 flags |= eTraversalNeeded;
3621 }
3622 if (what & layer_state_t::eFlagsChanged) {
3623 if (layer->setFlags(s.flags, s.mask))
3624 flags |= eTraversalNeeded;
3625 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003626 if (what & layer_state_t::eCropChanged_legacy) {
3627 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003628 flags |= eTraversalNeeded;
3629 }
chaviw8b3871a2017-11-01 17:41:01 -07003630 if (what & layer_state_t::eLayerStackChanged) {
3631 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3632 // We only allow setting layer stacks for top level layers,
3633 // everything else inherits layer stack from its parent.
3634 if (layer->hasParent()) {
3635 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3636 layer->getName().string());
3637 } else if (idx < 0) {
3638 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3639 "that also does not appear in the top level layer list. Something"
3640 " has gone wrong.", layer->getName().string());
3641 } else if (layer->setLayerStack(s.layerStack)) {
3642 mCurrentState.layersSortedByZ.removeAt(idx);
3643 mCurrentState.layersSortedByZ.add(layer);
3644 // we need traversal (state changed)
3645 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003646 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003647 }
3648 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003649 if (what & layer_state_t::eDeferTransaction_legacy) {
3650 if (s.barrierHandle_legacy != nullptr) {
3651 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3652 } else if (s.barrierGbp_legacy != nullptr) {
3653 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003654 if (authenticateSurfaceTextureLocked(gbp)) {
3655 const auto& otherLayer =
3656 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003657 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003658 } else {
3659 ALOGE("Attempt to defer transaction to to an"
3660 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003661 }
3662 }
chaviw8b3871a2017-11-01 17:41:01 -07003663 // We don't trigger a traversal here because if no other state is
3664 // changed, we don't want this to cause any more work
3665 }
3666 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003667 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003668 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003669 if (!hadParent) {
3670 mCurrentState.layersSortedByZ.remove(layer);
3671 }
chaviw8b3871a2017-11-01 17:41:01 -07003672 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003673 }
chaviw8b3871a2017-11-01 17:41:01 -07003674 }
3675 if (what & layer_state_t::eReparentChildren) {
3676 if (layer->reparentChildren(s.reparentHandle)) {
3677 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003678 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003679 }
chaviw8b3871a2017-11-01 17:41:01 -07003680 if (what & layer_state_t::eDetachChildren) {
3681 layer->detachChildren();
3682 }
3683 if (what & layer_state_t::eOverrideScalingModeChanged) {
3684 layer->setOverrideScalingMode(s.overrideScalingMode);
3685 // We don't trigger a traversal here because if no other state is
3686 // changed, we don't want this to cause any more work
3687 }
Marissa Wall61c58622018-07-18 10:12:20 -07003688 if (what & layer_state_t::eTransformChanged) {
3689 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3690 }
3691 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3692 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3693 flags |= eTraversalNeeded;
3694 }
3695 if (what & layer_state_t::eCropChanged) {
3696 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3697 }
3698 if (what & layer_state_t::eBufferChanged) {
3699 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3700 }
3701 if (what & layer_state_t::eAcquireFenceChanged) {
3702 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3703 }
3704 if (what & layer_state_t::eDataspaceChanged) {
3705 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3706 }
3707 if (what & layer_state_t::eHdrMetadataChanged) {
3708 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3709 }
3710 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3711 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3712 }
3713 if (what & layer_state_t::eApiChanged) {
3714 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3715 }
3716 if (what & layer_state_t::eSidebandStreamChanged) {
3717 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3718 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003719 return flags;
3720}
3721
chaviwca27f252018-02-06 16:46:39 -08003722void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3723 const layer_state_t& state = composerState.state;
3724 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3725
3726 sp<Layer> layer(client->getLayerUser(state.surface));
3727 if (layer == nullptr) {
3728 return;
3729 }
3730
Rob Carr4bba3702018-10-08 21:53:30 +00003731 if (layer->isPendingRemoval()) {
chaviwca27f252018-02-06 16:46:39 -08003732 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3733 return;
3734 }
3735
3736 if (state.what & layer_state_t::eDestroySurface) {
3737 removeLayerLocked(mStateLock, layer);
3738 }
3739}
3740
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003741status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003742 const String8& name,
3743 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003744 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003745 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003746 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003747{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003748 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003749 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003750 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003751 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003752 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003753
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003754 status_t result = NO_ERROR;
3755
3756 sp<Layer> layer;
3757
Cody Northropbc755282017-03-31 12:00:08 -06003758 String8 uniqueName = getUniqueLayerName(name);
3759
Mathias Agopian3165cc22012-08-08 19:42:09 -07003760 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003761 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003762 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3763 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003764
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003765 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003766 case ISurfaceComposerClient::eFXSurfaceBufferState:
3767 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3768 break;
chaviw13fdc492017-06-27 12:40:18 -07003769 case ISurfaceComposerClient::eFXSurfaceColor:
3770 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003771 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003772 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003773 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003774 case ISurfaceComposerClient::eFXSurfaceContainer:
3775 result = createContainerLayer(client,
3776 uniqueName, w, h, flags,
3777 handle, &layer);
3778 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003779 default:
3780 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003781 break;
3782 }
3783
Dan Stoza7d89d062015-04-30 13:29:25 -07003784 if (result != NO_ERROR) {
3785 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003786 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003787
Chia-I Wuab0c3192017-08-01 11:29:00 -07003788 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3789 // TODO b/64227542
3790 if (windowType == 441731) {
3791 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3792 layer->setPrimaryDisplayOnly();
3793 }
3794
Albert Chaulk479c60c2017-01-27 14:21:34 -05003795 layer->setInfo(windowType, ownerUid);
3796
Robert Carr1f0a16a2016-10-24 16:27:39 -07003797 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003798 if (result != NO_ERROR) {
3799 return result;
3800 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003801 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003802
3803 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003804 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003805}
3806
Cody Northropbc755282017-03-31 12:00:08 -06003807String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3808{
3809 bool matchFound = true;
3810 uint32_t dupeCounter = 0;
3811
3812 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3813 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3814
Dan Stoza436ccf32018-06-21 12:10:12 -07003815 // Grab the state lock since we're accessing mCurrentState
3816 Mutex::Autolock lock(mStateLock);
3817
Cody Northropbc755282017-03-31 12:00:08 -06003818 // Loop over layers until we're sure there is no matching name
3819 while (matchFound) {
3820 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003821 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003822 if (layer->getName() == uniqueName) {
3823 matchFound = true;
3824 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3825 }
3826 });
3827 }
3828
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003829 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3830 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003831
3832 return uniqueName;
3833}
3834
Marissa Wallfd668622018-05-10 10:21:13 -07003835status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3836 uint32_t w, uint32_t h, uint32_t flags,
3837 PixelFormat& format, sp<IBinder>* handle,
3838 sp<IGraphicBufferProducer>* gbp,
3839 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003840 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003841 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003842 case PIXEL_FORMAT_TRANSPARENT:
3843 case PIXEL_FORMAT_TRANSLUCENT:
3844 format = PIXEL_FORMAT_RGBA_8888;
3845 break;
3846 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003847 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003848 break;
3849 }
3850
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003851 sp<BufferQueueLayer> layer =
3852 new BufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003853 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003854 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003855 *handle = layer->getHandle();
3856 *gbp = layer->getProducer();
3857 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003858 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003859
Marissa Wallfd668622018-05-10 10:21:13 -07003860 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003861 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003862}
3863
Marissa Wall61c58622018-07-18 10:12:20 -07003864status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3865 uint32_t w, uint32_t h, uint32_t flags,
3866 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003867 sp<BufferStateLayer> layer =
3868 new BufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003869 *handle = layer->getHandle();
3870 *outLayer = layer;
3871
3872 return NO_ERROR;
3873}
3874
chaviw13fdc492017-06-27 12:40:18 -07003875status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003876 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003877 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003878{
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003879 *outLayer = new ColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003880 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003881 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003882}
3883
Robert Carr6b3f6c52018-08-13 13:05:17 -07003884status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3885 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3886 sp<IBinder>* handle, sp<Layer>* outLayer)
3887{
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003888 *outLayer = new ContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003889 *handle = (*outLayer)->getHandle();
3890 return NO_ERROR;
3891}
3892
3893
Mathias Agopianac9fa422013-02-11 16:40:36 -08003894status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003895{
Robert Carr9524cb32017-02-13 11:32:32 -08003896 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003897 status_t err = NO_ERROR;
3898 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003899 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003900 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003901 err = removeLayer(l);
3902 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3903 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003904 }
3905 return err;
3906}
3907
Rob Carr4bba3702018-10-08 21:53:30 +00003908status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
3909{
3910 // called by ~LayerCleaner() when all references to the IBinder (handle)
3911 // are gone
3912 sp<Layer> l = layer.promote();
3913 if (l == nullptr) {
3914 // The layer has already been removed, carry on
3915 return NO_ERROR;
3916 }
3917 // If we have a parent, then we can continue to live as long as it does.
3918 return removeLayer(l, true);
3919}
3920
Mathias Agopianb60314a2012-04-10 22:09:54 -07003921// ---------------------------------------------------------------------------
3922
Andy McFadden13a082e2012-08-24 10:16:42 -07003923void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003924 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3925 if (!displayToken) return;
3926
Jesse Hall01e29052013-02-19 16:13:35 -08003927 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003928 Vector<ComposerState> state;
3929 Vector<DisplayState> displays;
3930 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003931 d.what = DisplayState::eDisplayProjectionChanged |
3932 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003933 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003934 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003935 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003936 d.frame.makeInvalid();
3937 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003938 d.width = 0;
3939 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003940 displays.add(d);
3941 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003942
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003943 const auto display = getDisplayDevice(displayToken);
3944 if (!display) return;
3945
3946 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3947
3948 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003949 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003950 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003951
Brian Andersond0010582017-03-07 13:20:31 -08003952 // Use phase of 0 since phase is not known.
3953 // Use latency of 0, which will snap to the ideal latency.
3954 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003955}
3956
3957void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003958 // Async since we may be called from the main thread.
3959 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003960}
3961
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003962void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3963 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003964 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003965 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003966
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003967 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003968 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003969 return;
3970 }
3971
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003972 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003973 ALOGW("Trying to set power mode for virtual display");
3974 return;
3975 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003976
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003977 display->setPowerMode(mode);
3978
Lloyd Pique4dccc412018-01-22 17:21:36 -08003979 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003980 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003981 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003982 if (idx < 0) {
3983 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3984 return;
3985 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003986 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003987 }
3988
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003989 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003990 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003991 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003992 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003993 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003994 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003995 if (mUseScheduler) {
3996 mScheduler->onScreenAcquired(mAppConnectionHandle);
3997 } else {
3998 mEventThread->onScreenAcquired();
3999 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004000 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004001 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004002
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004003 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004004 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004005 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004006
4007 struct sched_param param = {0};
4008 param.sched_priority = 1;
4009 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4010 ALOGW("Couldn't set SCHED_FIFO on display on");
4011 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004012 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004013 // Turn off the display
4014 struct sched_param param = {0};
4015 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4016 ALOGW("Couldn't set SCHED_OTHER on display off");
4017 }
4018
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004019 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07004020 disableHardwareVsync(true); // also cancels any in-progress resync
4021
Mathias Agopiancde87a32012-09-13 14:09:01 -07004022 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004023 if (mUseScheduler) {
4024 mScheduler->onScreenReleased(mAppConnectionHandle);
4025 } else {
4026 mEventThread->onScreenReleased();
4027 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004028 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004029
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004030 getHwComposer().setPowerMode(type, mode);
4031 mVisibleRegionsDirty = true;
4032 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004033 } else if (mode == HWC_POWER_MODE_DOZE ||
4034 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004035 // Update display while dozing
4036 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004037 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004038 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004039 if (mUseScheduler) {
4040 mScheduler->onScreenAcquired(mAppConnectionHandle);
4041 } else {
4042 mEventThread->onScreenAcquired();
4043 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004044 resyncToHardwareVsync(true);
4045 }
4046 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4047 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004048 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004049 disableHardwareVsync(true); // also cancels any in-progress resync
4050 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004051 if (mUseScheduler) {
4052 mScheduler->onScreenReleased(mAppConnectionHandle);
4053 } else {
4054 mEventThread->onScreenReleased();
4055 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004056 }
4057 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004058 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004059 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004060 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004061 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004062
4063 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004064}
4065
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004066void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004067 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004068 const auto display = getDisplayDevice(displayToken);
4069 if (!display) {
4070 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4071 displayToken.get());
4072 } else if (display->isVirtual()) {
4073 ALOGW("Attempt to set power mode %d for virtual display", mode);
4074 } else {
4075 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004076 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004077 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004078}
4079
4080// ---------------------------------------------------------------------------
4081
Lloyd Pique755e3192018-01-31 16:46:15 -08004082status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4083 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004084 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004085
Mathias Agopianbd115332013-04-18 16:41:04 -07004086 IPCThreadState* ipc = IPCThreadState::self();
4087 const int pid = ipc->getCallingPid();
4088 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004089
Mathias Agopianbd115332013-04-18 16:41:04 -07004090 if ((uid != AID_SHELL) &&
4091 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004092 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004093 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004094 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004095 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004096 // (this would indicate SF is stuck, but we want to be able to
4097 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004098 status_t err = mStateLock.timedLock(s2ns(1));
4099 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004100 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004101 result.appendFormat(
4102 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4103 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004104 }
4105
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004106 bool dumpAll = true;
4107 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004108 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004109
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004110 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004111 if ((index < numArgs) &&
4112 (args[index] == String16("--list"))) {
4113 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004114 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004115 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004116 }
4117
4118 if ((index < numArgs) &&
4119 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004120 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004121 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004122 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004123 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004124
4125 if ((index < numArgs) &&
4126 (args[index] == String16("--latency-clear"))) {
4127 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004128 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004129 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004130 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004131
4132 if ((index < numArgs) &&
4133 (args[index] == String16("--dispsync"))) {
4134 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004135 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004136 dumpAll = false;
4137 }
Dan Stozab90cf072015-03-05 11:05:59 -08004138
4139 if ((index < numArgs) &&
4140 (args[index] == String16("--static-screen"))) {
4141 index++;
4142 dumpStaticScreenStats(result);
4143 dumpAll = false;
4144 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004145
4146 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004147 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004148 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004149 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004150 dumpAll = false;
4151 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004152
4153 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4154 index++;
4155 dumpWideColorInfo(result);
4156 dumpAll = false;
4157 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004158
4159 if ((index < numArgs) &&
4160 (args[index] == String16("--enable-layer-stats"))) {
4161 index++;
4162 mLayerStats.enable();
4163 dumpAll = false;
4164 }
4165
4166 if ((index < numArgs) &&
4167 (args[index] == String16("--disable-layer-stats"))) {
4168 index++;
4169 mLayerStats.disable();
4170 dumpAll = false;
4171 }
4172
4173 if ((index < numArgs) &&
4174 (args[index] == String16("--clear-layer-stats"))) {
4175 index++;
4176 mLayerStats.clear();
4177 dumpAll = false;
4178 }
4179
4180 if ((index < numArgs) &&
4181 (args[index] == String16("--dump-layer-stats"))) {
4182 index++;
4183 mLayerStats.dump(result);
4184 dumpAll = false;
4185 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004186
4187 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004188 (args[index] == String16("--frame-composition"))) {
4189 index++;
4190 dumpFrameCompositionInfo(result);
4191 dumpAll = false;
4192 }
4193
4194 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004195 (args[index] == String16("--display-identification"))) {
4196 index++;
4197 dumpDisplayIdentificationData(result);
4198 dumpAll = false;
4199 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004200
4201 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4202 index++;
4203 mTimeStats.parseArgs(asProto, args, index, result);
4204 dumpAll = false;
4205 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004206 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004207
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004208 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004209 if (asProto) {
4210 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4211 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4212 } else {
4213 dumpAllLocked(args, index, result);
4214 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004215 }
4216
Mathias Agopian9795c422009-08-26 16:36:26 -07004217 if (locked) {
4218 mStateLock.unlock();
4219 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004220 }
4221 write(fd, result.string(), result.size());
4222 return NO_ERROR;
4223}
4224
Dan Stozac7014012014-02-14 15:03:43 -08004225void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4226 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004227{
Robert Carr2047fae2016-11-28 14:09:09 -08004228 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004229 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004230 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004231}
4232
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004233void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004234 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004235{
4236 String8 name;
4237 if (index < args.size()) {
4238 name = String8(args[index]);
4239 index++;
4240 }
4241
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004242 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4243 getHwComposer().isConnected(displayId)) {
4244 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4245 const nsecs_t period = activeConfig->getVsyncPeriod();
4246 result.appendFormat("%" PRId64 "\n", period);
4247 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004248
4249 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004250 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004251 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004252 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004253 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004254 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004255 }
Robert Carr2047fae2016-11-28 14:09:09 -08004256 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004257 }
4258}
4259
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004260void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004261 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004262{
4263 String8 name;
4264 if (index < args.size()) {
4265 name = String8(args[index]);
4266 index++;
4267 }
4268
Robert Carr2047fae2016-11-28 14:09:09 -08004269 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004270 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004271 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004272 }
Robert Carr2047fae2016-11-28 14:09:09 -08004273 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004274
Svetoslavd85084b2014-03-20 10:28:31 -07004275 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004276}
4277
Jamie Gennis6547ff42013-07-16 20:12:42 -07004278// This should only be called from the main thread. Otherwise it would need
4279// the lock and should use mCurrentState rather than mDrawingState.
4280void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004281 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004282 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004283 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004284
4285 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4286}
4287
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004288void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004289{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004290 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004291
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004292 if (isLayerTripleBufferingDisabled())
4293 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004294
4295 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004296 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004297 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004298 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004299 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4300 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004301 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004302}
4303
Dan Stozab90cf072015-03-05 11:05:59 -08004304void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4305{
4306 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004307 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4308 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004309 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004310 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004311 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4312 b + 1, bucketTimeSec, percent);
4313 }
David Sodman4a36e932017-11-07 14:29:47 -08004314 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004315 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004316 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004317 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004318 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004319}
4320
Dan Stozae77c7662016-05-13 11:37:28 -07004321void SurfaceFlinger::recordBufferingStats(const char* layerName,
4322 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004323 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4324 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004325 for (const auto& segment : history) {
4326 if (!segment.usedThirdBuffer) {
4327 stats.twoBufferTime += segment.totalTime;
4328 }
4329 if (segment.occupancyAverage < 1.0f) {
4330 stats.doubleBufferedTime += segment.totalTime;
4331 } else if (segment.occupancyAverage < 2.0f) {
4332 stats.tripleBufferedTime += segment.totalTime;
4333 }
4334 ++stats.numSegments;
4335 stats.totalTime += segment.totalTime;
4336 }
4337}
4338
Brian Andersond6927fb2016-07-23 23:37:30 -07004339void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4340 result.appendFormat("Layer frame timestamps:\n");
4341
4342 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4343 const size_t count = currentLayers.size();
4344 for (size_t i=0 ; i<count ; i++) {
4345 currentLayers[i]->dumpFrameEvents(result);
4346 }
4347}
4348
Dan Stozae77c7662016-05-13 11:37:28 -07004349void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4350 result.append("Buffering stats:\n");
4351 result.append(" [Layer name] <Active time> <Two buffer> "
4352 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004353 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004354 typedef std::tuple<std::string, float, float, float> BufferTuple;
4355 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004356 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004357 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004358 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004359 if (stats.numSegments == 0) {
4360 continue;
4361 }
4362 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4363 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4364 stats.totalTime;
4365 float doubleBufferRatio = static_cast<float>(
4366 stats.doubleBufferedTime) / stats.totalTime;
4367 float tripleBufferRatio = static_cast<float>(
4368 stats.tripleBufferedTime) / stats.totalTime;
4369 sorted.insert({activeTime, {name, twoBufferRatio,
4370 doubleBufferRatio, tripleBufferRatio}});
4371 }
4372 for (const auto& sortedPair : sorted) {
4373 float activeTime = sortedPair.first;
4374 const BufferTuple& values = sortedPair.second;
4375 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4376 std::get<0>(values).c_str(), activeTime,
4377 std::get<1>(values), std::get<2>(values),
4378 std::get<3>(values));
4379 }
4380 result.append("\n");
4381}
4382
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004383void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004384 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004385 const int32_t displayId = display->getId();
4386 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4387 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004388 continue;
4389 }
4390
Dominik Laskowski7e045462018-05-30 13:02:02 -07004391 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004392 uint8_t port;
4393 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004394 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004395 result.append("no identification data\n");
4396 continue;
4397 }
4398
4399 if (!isEdid(data)) {
4400 result.append("unknown identification data: ");
4401 for (uint8_t byte : data) {
4402 result.appendFormat("%x ", byte);
4403 }
4404 result.append("\n");
4405 continue;
4406 }
4407
4408 const auto edid = parseEdid(data);
4409 if (!edid) {
4410 result.append("invalid EDID: ");
4411 for (uint8_t byte : data) {
4412 result.appendFormat("%x ", byte);
4413 }
4414 result.append("\n");
4415 continue;
4416 }
4417
4418 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4419 result.append(edid->displayName.data(), edid->displayName.length());
4420 result.append("\"\n");
4421 }
4422 result.append("\n");
4423}
4424
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004425void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004426 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4427 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004428 result.appendFormat("DisplayColorSetting: %s\n",
4429 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004430
4431 // TODO: print out if wide-color mode is active or not
4432
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004433 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004434 const int32_t displayId = display->getId();
4435 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004436 continue;
4437 }
4438
Dominik Laskowski7e045462018-05-30 13:02:02 -07004439 result.appendFormat("Display %d color modes:\n", displayId);
4440 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004441 for (auto&& mode : modes) {
4442 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4443 }
4444
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004445 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004446 result.appendFormat(" Current color mode: %s (%d)\n",
4447 decodeColorMode(currentMode).c_str(), currentMode);
4448 }
4449 result.append("\n");
4450}
4451
David Sodman7e4ae112018-02-09 15:02:28 -08004452void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4453 std::string stringResult;
4454
4455 for (const auto& [token, display] : mDisplays) {
4456 const auto displayId = display->getId();
4457 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
4458 continue;
4459 }
4460
4461 const auto& compositionInfoIt = getBE().mEndOfFrameCompositionInfo.find(displayId);
4462 if (compositionInfoIt == getBE().mEndOfFrameCompositionInfo.end()) {
4463 break;
4464 }
4465 const auto& compositionInfoList = compositionInfoIt->second;
4466 stringResult += base::StringPrintf("Display: %d\n", displayId);
4467 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4468 for (const auto& compositionInfo : compositionInfoList) {
4469 compositionInfo.dump(stringResult, nullptr);
4470 stringResult += base::StringPrintf("\n");
4471 }
4472 }
4473
4474 result.append(stringResult.c_str());
4475}
4476
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004477LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004478 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004479 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4480 const State& state = useDrawing ? mDrawingState : mCurrentState;
4481 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004482 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004483 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004484 });
4485
4486 return layersProto;
4487}
4488
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004489LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004490 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004491
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004492 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004493 resolution->set_w(display.getWidth());
4494 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004495
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004496 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4497 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4498 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004499
Dominik Laskowski7e045462018-05-30 13:02:02 -07004500 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004501 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004502 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004503 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004504 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004505 }
4506 });
4507
4508 return layersProto;
4509}
4510
Mathias Agopian74d211a2013-04-22 16:55:35 +02004511void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4512 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004513{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004514 bool colorize = false;
4515 if (index < args.size()
4516 && (args[index] == String16("--color"))) {
4517 colorize = true;
4518 index++;
4519 }
4520
4521 Colorizer colorizer(colorize);
4522
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004523 // figure out if we're stuck somewhere
4524 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004525 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004526 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4527
4528 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004529 * Dump library configuration.
4530 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004531
4532 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004533 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004534 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004535 appendSfConfigString(result);
4536 appendUiConfigString(result);
4537 appendGuiConfigString(result);
4538 result.append("\n");
4539
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004540 result.append("\nDisplay identification data:\n");
4541 dumpDisplayIdentificationData(result);
4542
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004543 result.append("\nWide-Color information:\n");
4544 dumpWideColorInfo(result);
4545
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004546 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004547 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004548 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004549 result.append(SyncFeatures::getInstance().toString());
4550 result.append("\n");
4551
Andy McFadden41d67d72014-04-25 16:58:34 -07004552 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004553 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004554 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004555
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004556 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4557 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004558 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4559 getHwComposer().isConnected(displayId)) {
4560 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004561 result.appendFormat("Display %d: "
4562 "app phase %" PRId64 " ns, "
4563 "sf phase %" PRId64 " ns, "
4564 "early app phase %" PRId64 " ns, "
4565 "early sf phase %" PRId64 " ns, "
4566 "early app gl phase %" PRId64 " ns, "
4567 "early sf gl phase %" PRId64 " ns, "
4568 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4569 displayId,
4570 vsyncPhaseOffsetNs,
4571 sfVsyncPhaseOffsetNs,
4572 appEarlyOffset,
4573 sfEarlyOffset,
4574 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004575 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004576 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004577 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004578 result.append("\n");
4579
Dan Stozab90cf072015-03-05 11:05:59 -08004580 // Dump static screen stats
4581 result.append("\n");
4582 dumpStaticScreenStats(result);
4583 result.append("\n");
4584
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004585 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4586
Dan Stozae77c7662016-05-13 11:37:28 -07004587 dumpBufferingStats(result);
4588
Andy McFadden4803b742012-09-24 19:07:20 -07004589 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004590 * Dump the visible layer list
4591 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004592 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004593 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004594 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4595 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004596 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004597
Chia-I Wu2f884132018-09-13 15:17:58 -07004598 {
4599 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4600 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4601 result.append(LayerProtoParser::layerTreeToString(layerTree).c_str());
4602 result.append("\n");
4603 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004604
David Sodman7e4ae112018-02-09 15:02:28 -08004605 result.append("\nFrame-Composition information:\n");
4606 dumpFrameCompositionInfo(result);
4607 result.append("\n");
4608
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004609 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004610 * Dump Display state
4611 */
4612
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004613 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004614 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004615 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004616 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004617 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004618 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004619 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004620
4621 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004622 * Dump SurfaceFlinger global state
4623 */
4624
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004625 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004626 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004627 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004628
Mathias Agopian888c8222012-08-04 21:10:38 -07004629 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004630 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004631
David Sodmanbc815282017-11-05 18:57:52 -08004632 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004633
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004634 if (display) {
4635 display->undefinedRegion.dump(result, "undefinedRegion");
4636 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4637 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004638 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004639 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004640 " gpu_to_cpu_unsupported : %d\n",
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004641 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004642
4643 if (display) {
4644 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4645 result.appendFormat(" refresh-rate : %f fps\n"
4646 " x-dpi : %f\n"
4647 " y-dpi : %f\n",
4648 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4649 activeConfig->getDpiY());
4650 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004651
Mathias Agopian74d211a2013-04-22 16:55:35 +02004652 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004653 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004654
Ana Krulec98b5b242018-08-10 15:03:23 -07004655 result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004656 /*
4657 * VSYNC state
4658 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004659 if (mUseScheduler) {
4660 mScheduler->dump(mAppConnectionHandle, result);
4661 } else {
4662 mEventThread->dump(result);
4663 }
Dan Stozae22aec72016-08-01 13:20:59 -07004664 result.append("\n");
4665
4666 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004667 * Tracing state
4668 */
4669 mTracing.dump(result);
4670 result.append("\n");
4671
4672 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004673 * HWC layer minidump
4674 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004675 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004676 const int32_t displayId = display->getId();
4677 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004678 continue;
4679 }
4680
Dominik Laskowski7e045462018-05-30 13:02:02 -07004681 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004682 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004683 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004684 result.append("\n");
4685 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004686
4687 /*
4688 * Dump HWComposer state
4689 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004690 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004691 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004692 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004693 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004694 result.appendFormat(" h/w composer %s\n",
4695 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004696 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004697
4698 /*
4699 * Dump gralloc state
4700 */
4701 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4702 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004703
4704 /*
4705 * Dump VrFlinger state if in use.
4706 */
4707 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4708 result.append("VrFlinger state:\n");
4709 result.append(mVrFlinger->Dump().c_str());
4710 result.append("\n");
4711 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004712}
4713
Dominik Laskowski7e045462018-05-30 13:02:02 -07004714const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004715 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004716 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004717 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004718 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004719 }
4720 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004721
4722 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4723 static const Vector<sp<Layer>> empty;
4724 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004725}
4726
Keun young Park63f165f2012-08-31 10:53:36 -07004727bool SurfaceFlinger::startDdmConnection()
4728{
4729 void* libddmconnection_dso =
4730 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4731 if (!libddmconnection_dso) {
4732 return false;
4733 }
4734 void (*DdmConnection_start)(const char* name);
4735 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004736 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004737 if (!DdmConnection_start) {
4738 dlclose(libddmconnection_dso);
4739 return false;
4740 }
4741 (*DdmConnection_start)(getServiceName());
4742 return true;
4743}
4744
Chia-I Wu28f320b2018-05-03 11:02:56 -07004745void SurfaceFlinger::updateColorMatrixLocked() {
4746 mat4 colorMatrix;
4747 if (mGlobalSaturationFactor != 1.0f) {
4748 // Rec.709 luma coefficients
4749 float3 luminance{0.213f, 0.715f, 0.072f};
4750 luminance *= 1.0f - mGlobalSaturationFactor;
4751 mat4 saturationMatrix = mat4(
4752 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4753 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4754 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4755 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4756 );
4757 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4758 } else {
4759 colorMatrix = mClientColorMatrix * mDaltonizer();
4760 }
4761
4762 if (mCurrentState.colorMatrix != colorMatrix) {
4763 mCurrentState.colorMatrix = colorMatrix;
4764 mCurrentState.colorMatrixChanged = true;
4765 setTransactionFlags(eTransactionNeeded);
4766 }
4767}
4768
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004769status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004770#pragma clang diagnostic push
4771#pragma clang diagnostic error "-Wswitch-enum"
4772 switch (static_cast<ISurfaceComposerTag>(code)) {
4773 // These methods should at minimum make sure that the client requested
4774 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004775 case BOOT_FINISHED:
4776 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004777 case CREATE_CONNECTION:
4778 case CREATE_DISPLAY:
4779 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004780 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004781 case GET_ACTIVE_COLOR_MODE:
4782 case GET_ANIMATION_FRAME_STATS:
4783 case GET_HDR_CAPABILITIES:
4784 case SET_ACTIVE_CONFIG:
4785 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004786 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004787 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004788 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4789 IPCThreadState* ipc = IPCThreadState::self();
4790 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4791 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004792 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004793 }
Robert Carr1db73f62016-12-21 12:58:51 -08004794 return OK;
4795 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004796 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004797 IPCThreadState* ipc = IPCThreadState::self();
4798 const int pid = ipc->getCallingPid();
4799 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004800 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4801 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004802 return PERMISSION_DENIED;
4803 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004804 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004805 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004806 // Used by apps to hook Choreographer to SurfaceFlinger.
4807 case CREATE_DISPLAY_EVENT_CONNECTION:
4808 // The following calls are currently used by clients that do not
4809 // request necessary permissions. However, they do not expose any secret
4810 // information, so it is OK to pass them.
4811 case AUTHENTICATE_SURFACE:
4812 case GET_ACTIVE_CONFIG:
4813 case GET_BUILT_IN_DISPLAY:
4814 case GET_DISPLAY_COLOR_MODES:
4815 case GET_DISPLAY_CONFIGS:
4816 case GET_DISPLAY_STATS:
4817 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4818 // Calling setTransactionState is safe, because you need to have been
4819 // granted a reference to Client* and Handle* to do anything with it.
4820 case SET_TRANSACTION_STATE:
4821 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004822 case CREATE_SCOPED_CONNECTION:
4823 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004824 return OK;
4825 }
4826 case CAPTURE_LAYERS:
4827 case CAPTURE_SCREEN: {
4828 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004829 IPCThreadState* ipc = IPCThreadState::self();
4830 const int pid = ipc->getCallingPid();
4831 const int uid = ipc->getCallingUid();
4832 if ((uid != AID_GRAPHICS) &&
4833 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4834 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4835 return PERMISSION_DENIED;
4836 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004837 return OK;
4838 }
4839 // The following codes are deprecated and should never be allowed to access SF.
4840 case CONNECT_DISPLAY_UNUSED:
4841 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4842 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4843 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004844 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004845 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004846
4847 // These codes are used for the IBinder protocol to either interrogate the recipient
4848 // side of the transaction for its canonical interface descriptor or to dump its state.
4849 // We let them pass by default.
4850 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4851 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4852 code == IBinder::SYSPROPS_TRANSACTION) {
4853 return OK;
4854 }
4855 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4856 // in onTransact verifies that the user is root, and has access to use SF.
4857 if (code >= 1000 && code <= 1029) {
4858 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4859 return OK;
4860 }
4861 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4862 return PERMISSION_DENIED;
4863#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004864}
4865
Ana Krulec13be8ad2018-08-21 02:43:56 +00004866status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4867 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004868 status_t credentialCheck = CheckTransactCodeCredentials(code);
4869 if (credentialCheck != OK) {
4870 return credentialCheck;
4871 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004872
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004873 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4874 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004875 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004876 IPCThreadState* ipc = IPCThreadState::self();
4877 const int uid = ipc->getCallingUid();
4878 if (CC_UNLIKELY(uid != AID_SYSTEM
4879 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004880 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004881 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004882 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004883 return PERMISSION_DENIED;
4884 }
4885 int n;
4886 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004887 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004888 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004889 return NO_ERROR;
4890 case 1002: // SHOW_UPDATES
4891 n = data.readInt32();
4892 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004893 invalidateHwcGeometry();
4894 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004895 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004896 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004897 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004898 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004899 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004900 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004901 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004902 setTransactionFlags(
4903 eTransactionNeeded|
4904 eDisplayTransactionNeeded|
4905 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004906 return NO_ERROR;
4907 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004908 case 1006:{ // send empty update
4909 signalRefresh();
4910 return NO_ERROR;
4911 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004912 case 1008: // toggle use of hw composer
4913 n = data.readInt32();
4914 mDebugDisableHWC = n ? 1 : 0;
4915 invalidateHwcGeometry();
4916 repaintEverything();
4917 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004918 case 1009: // toggle use of transform hint
4919 n = data.readInt32();
4920 mDebugDisableTransformHint = n ? 1 : 0;
4921 invalidateHwcGeometry();
4922 repaintEverything();
4923 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004924 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004925 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004926 reply->writeInt32(0);
4927 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004928 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004929 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004930 return NO_ERROR;
4931 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004932 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004933 if (!display) {
4934 return NAME_NOT_FOUND;
4935 }
4936
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004937 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004938 return NO_ERROR;
4939 }
4940 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004941 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004942 // daltonize
4943 n = data.readInt32();
4944 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004945 case 1:
4946 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4947 break;
4948 case 2:
4949 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4950 break;
4951 case 3:
4952 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4953 break;
4954 default:
4955 mDaltonizer.setType(ColorBlindnessType::None);
4956 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004957 }
4958 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004959 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004960 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004961 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004962 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004963
4964 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004965 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004966 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004967 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004968 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004969 // apply a color matrix
4970 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004971 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004972 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004973 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004974 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004975 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004976 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004977 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004978 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004979 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004980 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004981
4982 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4983 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004984 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004985 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4986 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4987 }
4988
Chia-I Wu28f320b2018-05-03 11:02:56 -07004989 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004990 return NO_ERROR;
4991 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004992 // This is an experimental interface
4993 // Needs to be shifted to proper binder interface when we productize
4994 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004995 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07004996 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004997 return NO_ERROR;
4998 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004999 case 1017: {
5000 n = data.readInt32();
5001 mForceFullDamage = static_cast<bool>(n);
5002 return NO_ERROR;
5003 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005004 case 1018: { // Modify Choreographer's phase offset
5005 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005006 if (mUseScheduler) {
5007 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5008 } else {
5009 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5010 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005011 return NO_ERROR;
5012 }
5013 case 1019: { // Modify SurfaceFlinger's phase offset
5014 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005015 if (mUseScheduler) {
5016 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5017 } else {
5018 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5019 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005020 return NO_ERROR;
5021 }
Irvel468051e2016-06-13 16:44:44 -07005022 case 1020: { // Layer updates interceptor
5023 n = data.readInt32();
5024 if (n) {
5025 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005026 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005027 }
5028 else{
5029 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005030 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005031 }
5032 return NO_ERROR;
5033 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005034 case 1021: { // Disable HWC virtual displays
5035 n = data.readInt32();
5036 mUseHwcVirtualDisplays = !n;
5037 return NO_ERROR;
5038 }
Romain Guy0147a172017-06-01 13:53:56 -07005039 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005040 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005041 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005042
Chia-I Wu28f320b2018-05-03 11:02:56 -07005043 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005044 return NO_ERROR;
5045 }
Romain Guy54f154a2017-10-24 21:40:32 +01005046 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005047 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005048 invalidateHwcGeometry();
5049 repaintEverything();
5050 return NO_ERROR;
5051 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005052 // TODO(b/111505327): Find out whether the usage of 1024 can switch to 1030,
5053 // deprecate 1024 if they can.
5054 case 1024: { // Does device have wide color gamut display?
Romain Guy54f154a2017-10-24 21:40:32 +01005055 reply->writeBool(hasWideColorDisplay);
5056 return NO_ERROR;
5057 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005058 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005059 n = data.readInt32();
5060 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005061 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005062 mTracing.enable();
5063 doTracing("tracing.enable");
5064 reply->writeInt32(NO_ERROR);
5065 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005066 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005067 status_t err = mTracing.disable();
5068 reply->writeInt32(err);
5069 }
5070 return NO_ERROR;
5071 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005072 case 1026: { // Get layer tracing status
5073 reply->writeBool(mTracing.isEnabled());
5074 return NO_ERROR;
5075 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005076 // Is a DisplayColorSetting supported?
5077 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005078 const auto display = getDefaultDisplayDevice();
5079 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005080 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005081 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005082
5083 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5084 switch (setting) {
5085 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005086 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005087 break;
5088 case DisplayColorSetting::UNMANAGED:
5089 reply->writeBool(true);
5090 break;
5091 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005092 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005093 break;
5094 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005095 reply->writeBool(
5096 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005097 break;
5098 }
5099 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005100 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005101 // Is VrFlinger active?
5102 case 1028: {
5103 Mutex::Autolock _l(mStateLock);
5104 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5105 return NO_ERROR;
5106 }
David Sodman6d46c1e2018-07-13 12:59:48 -07005107 case 1029: {
5108 // Code 1029 is an experimental feature that allows applications to
5109 // simulate a high frequency panel by setting a multiplier and divisor
5110 // on the VSYNC-sf clock. If either the multiplier or divisor are
David Sodman44b5de02018-08-21 16:28:53 -07005111 // 0, then the code simply return the current multiplier and divisor.
5112 HWC2::Device::FrequencyScaler frequencyScaler;
5113 frequencyScaler.multiplier = data.readInt32();
5114 frequencyScaler.divisor = data.readInt32();
David Sodman6d46c1e2018-07-13 12:59:48 -07005115
David Sodman44b5de02018-08-21 16:28:53 -07005116 if ((frequencyScaler.multiplier == 0) || (frequencyScaler.divisor == 0)) {
5117 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5118 reply->writeInt32(frequencyScaler.multiplier);
5119 reply->writeInt32(frequencyScaler.divisor);
5120 return NO_ERROR;
David Sodman6d46c1e2018-07-13 12:59:48 -07005121 }
5122
David Sodman44b5de02018-08-21 16:28:53 -07005123 if ((frequencyScaler.multiplier == 1) && (frequencyScaler.divisor == 1)) {
David Sodman6d46c1e2018-07-13 12:59:48 -07005124 enableHardwareVsync();
5125 } else {
5126 disableHardwareVsync(true);
5127 }
David Sodman44b5de02018-08-21 16:28:53 -07005128 mPrimaryDispSync->scalePeriod(frequencyScaler);
5129 getBE().mHwc->setDisplayFrequencyScaleParameters(frequencyScaler);
David Sodman6d46c1e2018-07-13 12:59:48 -07005130
David Sodman44b5de02018-08-21 16:28:53 -07005131 ATRACE_INT("PeriodMultiplier", frequencyScaler.multiplier);
5132 ATRACE_INT("PeriodDivisor", frequencyScaler.divisor);
5133
5134 const hwc2_display_t hwcDisplayId = getBE().mHwc->getActiveConfig(
5135 DisplayDevice::DISPLAY_PRIMARY)->getDisplayId();
5136
5137 onHotplugReceived(getBE().mComposerSequenceId,
5138 hwcDisplayId, HWC2::Connection::Disconnected);
5139 onHotplugReceived(getBE().mComposerSequenceId,
5140 hwcDisplayId, HWC2::Connection::Connected);
5141 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5142 reply->writeInt32(frequencyScaler.multiplier);
5143 reply->writeInt32(frequencyScaler.divisor);
5144
David Sodman6d46c1e2018-07-13 12:59:48 -07005145 return NO_ERROR;
5146 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005147 // Is device color managed?
5148 case 1030: {
5149 reply->writeBool(useColorManagement);
5150 return NO_ERROR;
5151 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005152 }
5153 }
5154 return err;
5155}
5156
Steven Thomas6d8110b2017-08-31 18:24:21 -07005157void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005158 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005159 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005160}
5161
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005162// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5163class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005164public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005165 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5166 ~WindowDisconnector() {
5167 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005168 }
5169
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005170private:
5171 ANativeWindow* mWindow;
5172 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005173};
5174
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005175status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
5176 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005177 uint32_t reqWidth, uint32_t reqHeight,
5178 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005179 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005180 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005181
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005182 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005183
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005184 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5185
Chia-I Wu20261cb2018-08-23 12:55:44 -07005186 sp<DisplayDevice> display;
5187 {
5188 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005189
Chia-I Wu20261cb2018-08-23 12:55:44 -07005190 display = getDisplayDeviceLocked(displayToken);
5191 if (!display) return BAD_VALUE;
5192
Chia-I Wu8730ba82018-08-29 09:25:59 -07005193 // ignore sourceCrop (i.e., use the projected logical display
5194 // viewport) until the framework is fixed
5195 sourceCrop.clear();
Chia-I Wucb023152018-08-28 12:57:23 -07005196
5197 // set the requested width/height to the logical display viewport size
5198 // by default
5199 if (reqWidth == 0 || reqHeight == 0) {
5200 reqWidth = uint32_t(display->getViewport().width());
5201 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005202 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005203 }
5204
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005205 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005206
5207 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005208 display, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005209 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005210}
5211
5212status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08005213 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005214 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005215 ATRACE_CALL();
5216
5217 class LayerRenderArea : public RenderArea {
5218 public:
Robert Carr578038f2018-03-09 12:25:24 -08005219 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
5220 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
Chia-I Wu9d1abea2018-08-23 13:44:43 -07005221 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08005222 mLayer(layer),
5223 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005224 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005225 mFlinger(flinger),
5226 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005227 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005228 Rect getBounds() const override {
5229 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005230 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005231 }
Marissa Wall61c58622018-07-18 10:12:20 -07005232 int getHeight() const override {
5233 return mLayer->getActiveHeight(mLayer->getDrawingState());
5234 }
5235 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005236 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005237 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005238 Rect getSourceCrop() const override {
5239 if (mCrop.isEmpty()) {
5240 return getBounds();
5241 } else {
5242 return mCrop;
5243 }
5244 }
Robert Carr578038f2018-03-09 12:25:24 -08005245 class ReparentForDrawing {
5246 public:
5247 const sp<Layer>& oldParent;
5248 const sp<Layer>& newParent;
5249
5250 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5251 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005252 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005253 }
Robert Carr15eae092018-03-23 13:43:53 -07005254 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005255 };
5256
5257 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005258 const Rect sourceCrop = getSourceCrop();
5259 // no need to check rotation because there is none
5260 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5261 sourceCrop.height() != getReqHeight();
5262
Robert Carr578038f2018-03-09 12:25:24 -08005263 if (!mChildrenOnly) {
5264 mTransform = mLayer->getTransform().inverse();
5265 drawLayers();
5266 } else {
5267 Rect bounds = getBounds();
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005268 screenshotParentLayer = new ContainerLayer(
5269 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5270 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005271
5272 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5273 drawLayers();
5274 }
5275 }
chaviwa76b2712017-09-20 12:02:26 -07005276
chaviwa76b2712017-09-20 12:02:26 -07005277 private:
chaviw7206d492017-11-10 16:16:12 -08005278 const sp<Layer> mLayer;
5279 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005280
5281 // In the "childrenOnly" case we reparent the children to a screenshot
5282 // layer which has no properties set and which does not draw.
5283 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005284 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005285 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005286
5287 SurfaceFlinger* mFlinger;
5288 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005289 };
5290
5291 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5292 auto parent = layerHandle->owner.promote();
5293
Rob Carr4bba3702018-10-08 21:53:30 +00005294 if (parent == nullptr || parent->isPendingRemoval()) {
chaviw7206d492017-11-10 16:16:12 -08005295 ALOGE("captureLayers called with a removed parent");
5296 return NAME_NOT_FOUND;
5297 }
5298
Robert Carr578038f2018-03-09 12:25:24 -08005299 const int uid = IPCThreadState::self()->getCallingUid();
5300 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5301 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5302 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5303 return PERMISSION_DENIED;
5304 }
5305
chaviw7206d492017-11-10 16:16:12 -08005306 Rect crop(sourceCrop);
5307 if (sourceCrop.width() <= 0) {
5308 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005309 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005310 }
5311
5312 if (sourceCrop.height() <= 0) {
5313 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005314 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005315 }
5316
5317 int32_t reqWidth = crop.width() * frameScale;
5318 int32_t reqHeight = crop.height() * frameScale;
5319
Chia-I Wu20261cb2018-08-23 12:55:44 -07005320 // really small crop or frameScale
5321 if (reqWidth <= 0) {
5322 reqWidth = 1;
5323 }
5324 if (reqHeight <= 0) {
5325 reqHeight = 1;
5326 }
5327
Robert Carr578038f2018-03-09 12:25:24 -08005328 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005329
Robert Carr578038f2018-03-09 12:25:24 -08005330 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005331 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5332 if (!layer->isVisible()) {
5333 return;
Robert Carr578038f2018-03-09 12:25:24 -08005334 } else if (childrenOnly && layer == parent.get()) {
5335 return;
chaviwa76b2712017-09-20 12:02:26 -07005336 }
5337 visitor(layer);
5338 });
5339 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005340 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005341}
5342
5343status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5344 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005345 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005346 bool useIdentityTransform) {
5347 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005348
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005349 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5350 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5351 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5352 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005353
5354 // This mutex protects syncFd and captureResult for communication of the return values from the
5355 // main thread back to this Binder thread
5356 std::mutex captureMutex;
5357 std::condition_variable captureCondition;
5358 std::unique_lock<std::mutex> captureLock(captureMutex);
5359 int syncFd = -1;
5360 std::optional<status_t> captureResult;
5361
Robert Carr03480e22018-01-04 16:02:06 -08005362 const int uid = IPCThreadState::self()->getCallingUid();
5363 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5364
Dominik Laskowski8c001672018-05-30 16:52:06 -07005365 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005366 // If there is a refresh pending, bug out early and tell the binder thread to try again
5367 // after the refresh.
5368 if (mRefreshPending) {
5369 ATRACE_NAME("Skipping screenshot for now");
5370 std::unique_lock<std::mutex> captureLock(captureMutex);
5371 captureResult = std::make_optional<status_t>(EAGAIN);
5372 captureCondition.notify_one();
5373 return;
5374 }
5375
5376 status_t result = NO_ERROR;
5377 int fd = -1;
5378 {
5379 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005380 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005381 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5382 useIdentityTransform, forSystem, &fd);
5383 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005384 }
5385
5386 {
5387 std::unique_lock<std::mutex> captureLock(captureMutex);
5388 syncFd = fd;
5389 captureResult = std::make_optional<status_t>(result);
5390 captureCondition.notify_one();
5391 }
5392 });
5393
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005394 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005395 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005396 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005397 while (*captureResult == EAGAIN) {
5398 captureResult.reset();
5399 result = postMessageAsync(message);
5400 if (result != NO_ERROR) {
5401 return result;
5402 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005403 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005404 }
5405 result = *captureResult;
5406 }
5407
5408 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005409 sync_wait(syncFd, -1);
5410 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005411 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005412
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005413 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005414}
5415
chaviwa76b2712017-09-20 12:02:26 -07005416void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005417 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005418 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005419 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005420
Lloyd Pique144e1162017-12-20 16:44:52 -08005421 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005422
chaviwa76b2712017-09-20 12:02:26 -07005423 const auto reqWidth = renderArea.getReqWidth();
5424 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005425 const auto sourceCrop = renderArea.getSourceCrop();
5426 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005427
Chia-I Wu36574d92018-05-16 10:54:36 -07005428 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5429 engine.setOutputDataSpace(Dataspace::SRGB);
5430 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005431
Mathias Agopian180f10d2013-04-10 22:55:41 -07005432 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005433 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005434
5435 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005436 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005437 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005438
chaviw50da5042018-04-09 13:49:37 -07005439 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005440 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005441 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005442
chaviwa76b2712017-09-20 12:02:26 -07005443 traverseLayers([&](Layer* layer) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08005444 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005445 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005446}
5447
chaviwa76b2712017-09-20 12:02:26 -07005448status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5449 TraverseLayersFunction traverseLayers,
5450 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005451 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005452 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005453 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005454 ATRACE_CALL();
5455
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005456 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005457
5458 traverseLayers([&](Layer* layer) {
5459 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5460 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005461
Robert Carr03480e22018-01-04 16:02:06 -08005462 // We allow the system server to take screenshots of secure layers for
5463 // use in situations like the Screen-rotation animation and place
5464 // the impetus on WindowManager to not persist them.
5465 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005466 ALOGW("FB is protected: PERMISSION_DENIED");
5467 return PERMISSION_DENIED;
5468 }
5469
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005470 // this binds the given EGLImage as a framebuffer for the
5471 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005472 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005473 if (bufferBond.getStatus() != NO_ERROR) {
5474 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005475 return INVALID_OPERATION;
5476 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005477
Dan Stozaabcda352017-06-01 14:37:39 -07005478 // this will in fact render into our dequeued buffer
5479 // via an FBO, which means we didn't have to create
5480 // an EGLSurface and therefore we're not
5481 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005482 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005483
Alec Mouri492bc572018-09-11 21:40:04 +00005484 base::unique_fd syncFd = getRenderEngine().flush();
5485 if (syncFd < 0) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005486 getRenderEngine().finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005487 }
Alec Mouri492bc572018-09-11 21:40:04 +00005488 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005489
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005490 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005491}
5492
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005493// ---------------------------------------------------------------------------
5494
Dan Stoza412903f2017-04-27 13:42:17 -07005495void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5496 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005497}
5498
Dan Stoza412903f2017-04-27 13:42:17 -07005499void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5500 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005501}
5502
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005503void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005504 const LayerVector::Visitor& visitor) {
5505 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005506 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005507 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005508 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005509 continue;
5510 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005511 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005512 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005513 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005514 return;
5515 }
chaviwa76b2712017-09-20 12:02:26 -07005516 if (!layer->isVisible()) {
5517 return;
5518 }
5519 visitor(layer);
5520 });
5521 }
5522}
5523
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005524}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005525
Lloyd Pique074e8122018-07-26 12:57:23 -07005526
Mathias Agopian3f844832013-08-07 21:24:32 -07005527#if defined(__gl_h_)
5528#error "don't include gl/gl.h in this file"
5529#endif
5530
5531#if defined(__gl2_h_)
5532#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005533#endif