blob: 23281c27575f6af5bf5a5b4a9d7422833c911d1d [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
Alec Mouri86770e52018-09-24 22:40:58 +00001531 // Setup RenderEngine sync fences if native sync is supported.
1532 if (getBE().mRenderEngine->useNativeFenceSync()) {
1533 if (mHadClientComposition) {
1534 base::unique_fd flushFence(getRenderEngine().flush());
1535 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1536 getBE().flushFence = new Fence(std::move(flushFence));
1537 } else {
1538 // Cleanup for hygiene.
1539 getBE().flushFence = Fence::NO_FENCE;
1540 }
1541 }
1542
Jorim Jaggi90535212018-05-23 23:44:06 +02001543 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001544
David Sodman7e4ae112018-02-09 15:02:28 -08001545 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001546 for (const auto& [token, display] : mDisplays) {
1547 const auto displayId = display->getId();
David Sodman7e4ae112018-02-09 15:02:28 -08001548 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[displayId]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001549 compositionInfo.hwc.hwcLayer = nullptr;
1550 }
David Sodmanba340492018-08-05 21:51:33 -07001551 }
David Sodman7e4ae112018-02-09 15:02:28 -08001552
1553 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001554}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001555
David Sodmanfa9b2af2017-12-24 13:28:59 -08001556
1557bool SurfaceFlinger::handleMessageInvalidate() {
1558 ATRACE_CALL();
1559 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001560}
1561
David Sodman79bba0e2018-08-05 18:07:49 -07001562void SurfaceFlinger::calculateWorkingSet() {
1563 ATRACE_CALL();
1564 ALOGV(__FUNCTION__);
1565
David Sodman79bba0e2018-08-05 18:07:49 -07001566 // build the h/w work list
1567 if (CC_UNLIKELY(mGeometryInvalid)) {
1568 mGeometryInvalid = false;
1569 for (const auto& [token, display] : mDisplays) {
1570 const auto displayId = display->getId();
1571 if (displayId >= 0) {
1572 const Vector<sp<Layer>>& currentLayers(
1573 display->getVisibleLayersSortedByZ());
1574 for (size_t i = 0; i < currentLayers.size(); i++) {
1575 const auto& layer = currentLayers[i];
1576
1577 if (!layer->hasHwcLayer(displayId)) {
1578 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1579 layer->forceClientComposition(displayId);
1580 continue;
1581 }
1582 }
1583
1584 layer->setGeometry(display, i);
1585 if (mDebugDisableHWC || mDebugRegion) {
1586 layer->forceClientComposition(displayId);
1587 }
1588 }
1589 }
1590 }
1591 }
1592
1593 // Set the per-frame data
1594 for (const auto& [token, display] : mDisplays) {
1595 const auto displayId = display->getId();
1596 if (displayId < 0) {
1597 continue;
1598 }
1599
1600 if (mDrawingState.colorMatrixChanged) {
1601 display->setColorTransform(mDrawingState.colorMatrix);
1602 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1603 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1604 "display %d: %d", displayId, result);
1605 }
1606 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1607 if (layer->isHdrY410()) {
1608 layer->forceClientComposition(displayId);
1609 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1610 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1611 !display->hasHDR10Support()) {
1612 layer->forceClientComposition(displayId);
1613 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1614 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1615 !display->hasHLGSupport()) {
1616 layer->forceClientComposition(displayId);
1617 }
1618
Peiyong Lind3788632018-09-18 16:01:31 -07001619 // TODO(b/111562338) remove when composer 2.3 is shipped.
1620 if (layer->hasColorTransform()) {
1621 layer->forceClientComposition(displayId);
1622 }
1623
David Sodman79bba0e2018-08-05 18:07:49 -07001624 if (layer->getForceClientComposition(displayId)) {
1625 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1626 layer->setCompositionType(displayId, HWC2::Composition::Client);
1627 continue;
1628 }
1629
1630 layer->setPerFrameData(display);
1631 }
1632
Peiyong Lin13effd12018-07-24 17:01:47 -07001633 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001634 ColorMode colorMode;
1635 Dataspace dataSpace;
1636 RenderIntent renderIntent;
1637 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1638 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1639 }
1640 }
1641
1642 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001643
1644 for (const auto& [token, display] : mDisplays) {
David Sodman15fb96e2018-01-07 10:23:24 -08001645 const auto displayId = display->getId();
1646 getBE().mCompositionInfo[displayId].clear();
David Sodmanba340492018-08-05 21:51:33 -07001647 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1648 auto displayId = display->getId();
1649 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1650 if (!layer->setHwcLayer(displayId)) {
1651 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1652 }
David Sodman15fb96e2018-01-07 10:23:24 -08001653 layer->getBE().compositionInfo.hwc.displayId = displayId;
1654 getBE().mCompositionInfo[displayId].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001655 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1656 }
1657 }
David Sodman79bba0e2018-08-05 18:07:49 -07001658}
1659
David Sodmanfa9b2af2017-12-24 13:28:59 -08001660void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001661{
David Sodmanfb95bcc2017-12-22 15:45:30 -08001662 const auto displayId = display->getId();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001663 // is debugging enabled
1664 if (CC_LIKELY(!mDebugRegion))
1665 return;
1666
David Sodmanfa9b2af2017-12-24 13:28:59 -08001667 if (display->isPoweredOn()) {
1668 // transform the dirty region into this screen's coordinate space
1669 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1670 if (!dirtyRegion.isEmpty()) {
1671 // redraw the whole screen
1672 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001673
David Sodmanfa9b2af2017-12-24 13:28:59 -08001674 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001675 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001676 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001677
David Sodmanfa9b2af2017-12-24 13:28:59 -08001678 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001679 }
1680 }
1681
David Sodmanfa9b2af2017-12-24 13:28:59 -08001682 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001683
1684 if (mDebugRegion > 1) {
1685 usleep(mDebugRegion * 1000);
1686 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001687
David Sodmanfa9b2af2017-12-24 13:28:59 -08001688 if (display->isPoweredOn()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08001689 status_t result = display->prepareFrame(
1690 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001691 ALOGE_IF(result != NO_ERROR,
1692 "prepareFrame for display %d failed:"
1693 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001694 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001695 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001696}
1697
Adrian Roos1e1a1282017-11-01 19:05:31 +01001698void SurfaceFlinger::doTracing(const char* where) {
1699 ATRACE_CALL();
1700 ATRACE_NAME(where);
1701 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001702 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001703 }
1704}
1705
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001706void SurfaceFlinger::logLayerStats() {
1707 ATRACE_CALL();
1708 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001709 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001710 if (display->isPrimary()) {
1711 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001712 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001713 }
1714 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001715
1716 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001717 }
1718}
1719
David Sodman2b406362017-12-15 13:33:47 -08001720void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001721{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001722 ATRACE_CALL();
1723 ALOGV("preComposition");
1724
David Sodman2b406362017-12-15 13:33:47 -08001725 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1726
Mathias Agopiancd60f992012-08-16 16:28:27 -07001727 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001728 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001729 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001730 needExtraInvalidate = true;
1731 }
Robert Carr2047fae2016-11-28 14:09:09 -08001732 });
1733
Mathias Agopiancd60f992012-08-16 16:28:27 -07001734 if (needExtraInvalidate) {
1735 signalLayerUpdate();
1736 }
1737}
1738
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001739void SurfaceFlinger::updateCompositorTiming(
1740 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1741 std::shared_ptr<FenceTime>& presentFenceTime) {
1742 // Update queue of past composite+present times and determine the
1743 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001744 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001745 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001746 while (!getBE().mCompositePresentTimes.empty()) {
1747 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001748 // Cached values should have been updated before calling this method,
1749 // which helps avoid duplicate syscalls.
1750 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1751 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1752 break;
1753 }
1754 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001755 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001756 }
1757
1758 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001759 while (getBE().mCompositePresentTimes.size() > 16) {
1760 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001761 }
1762
Brian Andersond0010582017-03-07 13:20:31 -08001763 setCompositorTimingSnapped(
1764 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1765}
1766
1767void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1768 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001769 // Integer division and modulo round toward 0 not -inf, so we need to
1770 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001771 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001772 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1773 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1774
Brian Andersond0010582017-03-07 13:20:31 -08001775 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1776 if (idealLatency <= 0) {
1777 idealLatency = vsyncInterval;
1778 }
1779
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001780 // Snap the latency to a value that removes scheduling jitter from the
1781 // composition and present times, which often have >1ms of jitter.
1782 // Reducing jitter is important if an app attempts to extrapolate
1783 // something (such as user input) to an accurate diasplay time.
1784 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1785 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001786 nsecs_t bias = vsyncInterval / 2;
1787 int64_t extraVsyncs =
1788 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1789 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1790 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001791
David Sodman99974d22017-11-28 12:04:33 -08001792 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1793 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1794 getBE().mCompositorTiming.interval = vsyncInterval;
1795 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001796}
1797
David Sodman2b406362017-12-15 13:33:47 -08001798void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001799{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001800 ATRACE_CALL();
1801 ALOGV("postComposition");
1802
Brian Anderson3546a3f2016-07-14 11:51:14 -07001803 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001804 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001805 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001806 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001807 }
1808
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001809 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001810 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001811
David Sodman73beded2017-11-15 11:56:06 -08001812 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001813 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001814 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001815 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001816 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001817 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001818 } else {
1819 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1820 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001821
David Sodman73beded2017-11-15 11:56:06 -08001822 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001823 mPreviousPresentFence =
1824 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1825 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001826 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001827
Lloyd Pique41be5d22018-06-21 13:11:48 -07001828 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1829 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001830
David Sodman2b406362017-12-15 13:33:47 -08001831 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001832 // when we started doing work for this frame, but that should be okay
1833 // since updateCompositorTiming has snapping logic.
1834 updateCompositorTiming(
David Sodman2b406362017-12-15 13:33:47 -08001835 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001836 CompositorTiming compositorTiming;
1837 {
David Sodman99974d22017-11-28 12:04:33 -08001838 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1839 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001840 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001841
Robert Carr2047fae2016-11-28 14:09:09 -08001842 mDrawingState.traverseInZOrder([&](Layer* layer) {
1843 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001844 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001845 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001846 recordBufferingStats(layer->getName().string(),
1847 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001848 }
Robert Carr2047fae2016-11-28 14:09:09 -08001849 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001850
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001851 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001852 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001853 enableHardwareVsync();
1854 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001855 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001856 }
1857 }
1858
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001859 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001860 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001861 enableHardwareVsync();
1862 }
1863 }
1864
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001865 if (mAnimCompositionPending) {
1866 mAnimCompositionPending = false;
1867
Brian Anderson4e606e32017-03-16 15:34:57 -07001868 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001869 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001870 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001871 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001872 // The HWC doesn't support present fences, so use the refresh
1873 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001874 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001875 mAnimFrameTracker.setActualPresentTime(presentTime);
1876 }
1877 mAnimFrameTracker.advanceFrame();
1878 }
Dan Stozab90cf072015-03-05 11:05:59 -08001879
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001880 mTimeStats.incrementTotalFrames();
1881 if (mHadClientComposition) {
1882 mTimeStats.incrementClientCompositionFrames();
1883 }
1884
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001885 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001886 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001887 return;
1888 }
1889
1890 nsecs_t currentTime = systemTime();
1891 if (mHasPoweredOff) {
1892 mHasPoweredOff = false;
1893 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001894 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001895 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001896 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1897 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001898 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001899 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001900 }
David Sodman4a36e932017-11-07 14:29:47 -08001901 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001902 }
David Sodman4a36e932017-11-07 14:29:47 -08001903 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001904
1905 {
1906 std::lock_guard lock(mTexturePoolMutex);
1907 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1908 if (refillCount > 0) {
1909 const size_t offset = mTexturePool.size();
1910 mTexturePool.resize(mTexturePoolSize);
1911 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1912 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1913 }
1914 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001915}
1916
1917void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001918 ATRACE_CALL();
1919 ALOGV("rebuildLayerStacks");
1920
Mathias Agopiancd60f992012-08-16 16:28:27 -07001921 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001922 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001923 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001924 mVisibleRegionsDirty = false;
1925 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001926
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001927 for (const auto& pair : mDisplays) {
1928 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001929 Region opaqueRegion;
1930 Region dirtyRegion;
1931 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001932 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001933 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001934 const Rect bounds = display->getBounds();
1935 if (display->isPoweredOn()) {
1936 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001937
Jeff Sharkey76488112017-02-27 14:15:18 -07001938 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001939 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001940 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001941 Region drawRegion(tr.transform(
1942 layer->visibleNonTransparentRegion));
1943 drawRegion.andSelf(bounds);
1944 if (!drawRegion.isEmpty()) {
1945 layersSortedByZ.add(layer);
1946 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001947 // Clear out the HWC layer if this layer was
1948 // previously visible, but no longer is
1949 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001950 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001951 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001952 // WM changes display->layerStack upon sleep/awake.
1953 // Here we make sure we delete the HWC layers even if
1954 // WM changed their layer stack.
1955 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001956 }
1957
1958 // If a layer is not going to get a release fence because
1959 // it is invisible, but it is also going to release its
1960 // old buffer, add it to the list of layers needing
1961 // fences.
1962 if (hwcLayerDestroyed) {
1963 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1964 mLayersWithQueuedFrames.cend(), layer);
1965 if (found != mLayersWithQueuedFrames.cend()) {
1966 layersNeedingFences.add(layer);
1967 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001968 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001969 });
1970 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001971 display->setVisibleLayersSortedByZ(layersSortedByZ);
1972 display->setLayersNeedingFences(layersNeedingFences);
1973 display->undefinedRegion.set(bounds);
1974 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1975 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001976 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001977 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001978}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001979
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001980// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001981// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001982// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001983// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001984// The returned HDR data space is one of
1985// - Dataspace::UNKNOWN
1986// - Dataspace::BT2020_HLG
1987// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001988Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1989 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001990 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001991 *outHdrDataSpace = Dataspace::UNKNOWN;
1992
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001993 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001994 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001995 case Dataspace::V0_SCRGB:
1996 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001997 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001998 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001999 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002000 case Dataspace::BT2020_PQ:
2001 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002002 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002003 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002004 case Dataspace::BT2020_HLG:
2005 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002006 // When there's mixed PQ content and HLG content, we set the HDR
2007 // data space to be BT2020_PQ and convert HLG to PQ.
2008 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2009 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002010 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002011 break;
2012 default:
2013 break;
2014 }
Romain Guy54f154a2017-10-24 21:40:32 +01002015 }
2016
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002017 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002018}
2019
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002020// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002021void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2022 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002023 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2024 *outMode = ColorMode::NATIVE;
2025 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002026 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002027 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002028 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002029
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002030 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002031 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002032
Peiyong Lindfde5112018-06-05 10:58:41 -07002033 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002034 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002035 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002036 if (isHdr) {
2037 bestDataSpace = hdrDataSpace;
2038 }
2039
Chia-I Wu0d711262018-05-21 15:19:35 -07002040 RenderIntent intent;
2041 switch (mDisplayColorSetting) {
2042 case DisplayColorSetting::MANAGED:
2043 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002044 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002045 break;
2046 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002047 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002048 break;
2049 default: // vendor display color setting
2050 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2051 break;
2052 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002053
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002054 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002055}
2056
David Sodman10a41ff2018-08-05 12:14:17 -07002057void SurfaceFlinger::configureSidebandComposition(const CompositionInfo& compositionInfo) const
2058{
2059 HWC2::Error error;
2060 LOG_ALWAYS_FATAL_IF(compositionInfo.hwc.sidebandStream == nullptr,
2061 "CompositionType is sideband, but sideband stream is nullptr");
2062 error = (compositionInfo.hwc.hwcLayer)
2063 ->setSidebandStream(compositionInfo.hwc.sidebandStream->handle());
2064 if (error != HWC2::Error::None) {
2065 ALOGE("[SF] Failed to set sideband stream %p: %s (%d)",
2066 compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
2067 static_cast<int32_t>(error));
2068 }
2069}
2070
2071void SurfaceFlinger::configureHwcCommonData(const CompositionInfo& compositionInfo) const
2072{
2073 HWC2::Error error;
2074
2075 if (!compositionInfo.hwc.skipGeometry) {
2076 error = (compositionInfo.hwc.hwcLayer)->setBlendMode(compositionInfo.hwc.blendMode);
2077 ALOGE_IF(error != HWC2::Error::None,
2078 "[SF] Failed to set blend mode %s:"
2079 " %s (%d)",
2080 to_string(compositionInfo.hwc.blendMode).c_str(), to_string(error).c_str(),
2081 static_cast<int32_t>(error));
2082
2083 error = (compositionInfo.hwc.hwcLayer)->setDisplayFrame(compositionInfo.hwc.displayFrame);
2084 ALOGE_IF(error != HWC2::Error::None,
2085 "[SF] Failed to set the display frame [%d, %d, %d, %d] %s (%d)",
2086 compositionInfo.hwc.displayFrame.left,
2087 compositionInfo.hwc.displayFrame.right,
2088 compositionInfo.hwc.displayFrame.top,
2089 compositionInfo.hwc.displayFrame.bottom,
2090 to_string(error).c_str(), static_cast<int32_t>(error));
2091
2092 error = (compositionInfo.hwc.hwcLayer)->setSourceCrop(compositionInfo.hwc.sourceCrop);
2093 ALOGE_IF(error != HWC2::Error::None,
2094 "[SF] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: %s (%d)",
2095 compositionInfo.hwc.sourceCrop.left,
2096 compositionInfo.hwc.sourceCrop.right,
2097 compositionInfo.hwc.sourceCrop.top,
2098 compositionInfo.hwc.sourceCrop.bottom,
2099 to_string(error).c_str(), static_cast<int32_t>(error));
2100
2101 error = (compositionInfo.hwc.hwcLayer)->setPlaneAlpha(compositionInfo.hwc.alpha);
2102 ALOGE_IF(error != HWC2::Error::None,
2103 "[SF] Failed to set plane alpha %.3f: "
2104 "%s (%d)",
2105 compositionInfo.hwc.alpha,
2106 to_string(error).c_str(), static_cast<int32_t>(error));
2107
2108
2109 error = (compositionInfo.hwc.hwcLayer)->setZOrder(compositionInfo.hwc.z);
2110 ALOGE_IF(error != HWC2::Error::None,
2111 "[SF] Failed to set Z %u: %s (%d)",
2112 compositionInfo.hwc.z,
2113 to_string(error).c_str(), static_cast<int32_t>(error));
2114
2115 error = (compositionInfo.hwc.hwcLayer)
2116 ->setInfo(compositionInfo.hwc.type, compositionInfo.hwc.appId);
2117 ALOGE_IF(error != HWC2::Error::None,
2118 "[SF] Failed to set info (%d)",
2119 static_cast<int32_t>(error));
2120
2121 error = (compositionInfo.hwc.hwcLayer)->setTransform(compositionInfo.hwc.transform);
2122 ALOGE_IF(error != HWC2::Error::None,
2123 "[SF] Failed to set transform %s: "
2124 "%s (%d)",
2125 to_string(compositionInfo.hwc.transform).c_str(), to_string(error).c_str(),
2126 static_cast<int32_t>(error));
2127 }
2128
2129 error = (compositionInfo.hwc.hwcLayer)->setCompositionType(compositionInfo.compositionType);
2130 ALOGE_IF(error != HWC2::Error::None,
2131 "[SF] Failed to set composition type: %s (%d)",
2132 to_string(error).c_str(), static_cast<int32_t>(error));
2133
2134 error = (compositionInfo.hwc.hwcLayer)->setDataspace(compositionInfo.hwc.dataspace);
2135 ALOGE_IF(error != HWC2::Error::None,
2136 "[SF] Failed to set dataspace: %s (%d)",
2137 to_string(error).c_str(), static_cast<int32_t>(error));
2138
2139 error = (compositionInfo.hwc.hwcLayer)->setPerFrameMetadata(
2140 compositionInfo.hwc.supportedPerFrameMetadata, compositionInfo.hwc.hdrMetadata);
2141 ALOGE_IF(error != HWC2::Error::None && error != HWC2::Error::Unsupported,
2142 "[SF] Failed to set hdrMetadata: %s (%d)",
2143 to_string(error).c_str(), static_cast<int32_t>(error));
2144
2145 if (compositionInfo.compositionType == HWC2::Composition::SolidColor) {
2146 error = (compositionInfo.hwc.hwcLayer)->setColor(compositionInfo.hwc.color);
2147 ALOGE_IF(error != HWC2::Error::None,
2148 "[SF] Failed to set color: %s (%d)",
2149 to_string(error).c_str(), static_cast<int32_t>(error));
2150 }
2151
2152 error = (compositionInfo.hwc.hwcLayer)->setVisibleRegion(compositionInfo.hwc.visibleRegion);
2153 ALOGE_IF(error != HWC2::Error::None,
2154 "[SF] Failed to set visible region: %s (%d)",
2155 to_string(error).c_str(), static_cast<int32_t>(error));
2156
2157 error = (compositionInfo.hwc.hwcLayer)->setSurfaceDamage(compositionInfo.hwc.surfaceDamage);
2158 ALOGE_IF(error != HWC2::Error::None,
2159 "[SF] Failed to set surface damage: %s (%d)",
2160 to_string(error).c_str(), static_cast<int32_t>(error));
Peiyong Lind3788632018-09-18 16:01:31 -07002161
2162 error = (compositionInfo.hwc.hwcLayer)->setColorTransform(compositionInfo.hwc.colorTransform);
David Sodman10a41ff2018-08-05 12:14:17 -07002163}
2164
2165void SurfaceFlinger::configureDeviceComposition(const CompositionInfo& compositionInfo) const
2166{
2167 HWC2::Error error;
2168
2169 if (compositionInfo.hwc.fence) {
2170 error = (compositionInfo.hwc.hwcLayer)->setBuffer(compositionInfo.mBufferSlot,
2171 compositionInfo.mBuffer, compositionInfo.hwc.fence);
2172 ALOGE_IF(error != HWC2::Error::None,
2173 "[SF] Failed to set buffer: %s (%d)",
2174 to_string(error).c_str(), static_cast<int32_t>(error));
2175 }
2176}
2177
David Sodmanfa9b2af2017-12-24 13:28:59 -08002178void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002179{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002180 bool dirty = !display->getDirtyRegion(false).isEmpty();
2181 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2182 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002183
David Sodmanfa9b2af2017-12-24 13:28:59 -08002184 // If nothing has changed (!dirty), don't recompose.
2185 // If something changed, but we don't currently have any visible layers,
2186 // and didn't when we last did a composition, then skip it this time.
2187 // The second rule does two things:
2188 // - When all layers are removed from a display, we'll emit one black
2189 // frame, then nothing more until we get new layers.
2190 // - When a display is created with a private layer stack, we won't
2191 // emit any black frames until a layer is added to the layer stack.
2192 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002193
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002194 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2195 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002196 mustRecompose ? "doing" : "skipping",
2197 dirty ? "+" : "-",
2198 empty ? "+" : "-",
2199 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002200
David Sodmanfa9b2af2017-12-24 13:28:59 -08002201 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002202
David Sodmanfa9b2af2017-12-24 13:28:59 -08002203 if (mustRecompose) {
2204 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002205 }
2206}
2207
David Sodmanfa9b2af2017-12-24 13:28:59 -08002208void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002209{
David Sodmanfb95bcc2017-12-22 15:45:30 -08002210 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002211 if (!display->isPoweredOn()) {
2212 return;
David Sodman2b406362017-12-15 13:33:47 -08002213 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002214
David Sodmanfb95bcc2017-12-22 15:45:30 -08002215 status_t result = display->prepareFrame(
2216 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08002217 ALOGE_IF(result != NO_ERROR,
2218 "prepareFrame for display %d failed:"
2219 " %d (%s)",
2220 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002221}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002222
David Sodman10a41ff2018-08-05 12:14:17 -07002223void SurfaceFlinger::setUpHWComposer(const CompositionInfo& compositionInfo) {
2224 ATRACE_CALL();
2225 ALOGV("setUpHWComposer");
2226
2227 switch (compositionInfo.compositionType)
2228 {
2229 case HWC2::Composition::Invalid:
David Sodmana6d42332018-08-29 14:07:04 -07002230 break;
2231
David Sodman10a41ff2018-08-05 12:14:17 -07002232 case HWC2::Composition::Client:
David Sodmana6d42332018-08-29 14:07:04 -07002233 if (compositionInfo.hwc.hwcLayer) {
2234 auto error = (compositionInfo.hwc.hwcLayer)->
2235 setCompositionType(compositionInfo.compositionType);
2236 ALOGE_IF(error != HWC2::Error::None,
2237 "[SF] Failed to set composition type: %s (%d)",
2238 to_string(error).c_str(), static_cast<int32_t>(error));
2239 }
David Sodman10a41ff2018-08-05 12:14:17 -07002240 break;
2241
2242 case HWC2::Composition::Sideband:
2243 configureHwcCommonData(compositionInfo);
2244 configureSidebandComposition(compositionInfo);
2245 break;
2246
2247 case HWC2::Composition::SolidColor:
2248 configureHwcCommonData(compositionInfo);
2249 break;
2250
2251 case HWC2::Composition::Device:
2252 case HWC2::Composition::Cursor:
2253 configureHwcCommonData(compositionInfo);
2254 configureDeviceComposition(compositionInfo);
2255 break;
2256 }
2257}
2258
David Sodmanfa9b2af2017-12-24 13:28:59 -08002259void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002260 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002261 ALOGV("doComposition");
2262
David Sodmanfa9b2af2017-12-24 13:28:59 -08002263 if (display->isPoweredOn()) {
2264 // transform the dirty region into this screen's coordinate space
2265 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002266
David Sodmanfa9b2af2017-12-24 13:28:59 -08002267 // repaint the framebuffer (if needed)
2268 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002269
David Sodmanfa9b2af2017-12-24 13:28:59 -08002270 display->dirtyRegion.clear();
2271 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002272 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002273 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002274}
2275
David Sodmanfa9b2af2017-12-24 13:28:59 -08002276void SurfaceFlinger::postFrame()
2277{
2278 // |mStateLock| not needed as we are on the main thread
2279 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2280 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2281 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2282 logFrameStats();
2283 }
2284 }
2285}
2286
2287void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002288{
Mathias Agopian841cde52012-03-01 15:44:37 -08002289 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002290 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002291
David Sodmanfa9b2af2017-12-24 13:28:59 -08002292 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002293
David Sodmanfa9b2af2017-12-24 13:28:59 -08002294 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002295 const auto displayId = display->getId();
2296 if (displayId >= 0) {
2297 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002298 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002299 display->onSwapBuffersCompleted();
2300 display->makeCurrent();
David Sodman10a41ff2018-08-05 12:14:17 -07002301 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002302 sp<Fence> releaseFence = Fence::NO_FENCE;
Chia-I Wu7b549592017-11-15 09:14:57 -08002303 // The layer buffer from the previous frame (if any) is released
2304 // by HWC only when the release fence from this frame (if any) is
2305 // signaled. Always get the release fence from HWC first.
David Sodman10a41ff2018-08-05 12:14:17 -07002306 auto hwcLayer = compositionInfo.hwc.hwcLayer;
2307 if ((displayId >= 0) && hwcLayer) {
2308 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer.get());
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002309 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002310
2311 // If the layer was client composited in the previous frame, we
2312 // need to merge with the previous client target acquire fence.
2313 // Since we do not track that, always merge with the current
2314 // client target acquire fence when it is available, even though
2315 // this is suboptimal.
David Sodman10a41ff2018-08-05 12:14:17 -07002316 if (compositionInfo.compositionType == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002317 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002318 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002319 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002320
David Sodman10a41ff2018-08-05 12:14:17 -07002321 if (compositionInfo.layer) {
2322 compositionInfo.layer->onLayerDisplayed(releaseFence);
2323 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002324 }
Chia-I Wu83806892017-11-16 10:50:20 -08002325
2326 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002327 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002328 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002329 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002330 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002331 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002332 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002333 }
2334 }
2335
Dominik Laskowski7e045462018-05-30 13:02:02 -07002336 if (displayId >= 0) {
2337 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002338 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002339 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002340}
2341
Mathias Agopian87baae12012-07-31 12:38:26 -07002342void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002343{
Mathias Agopian841cde52012-03-01 15:44:37 -08002344 ATRACE_CALL();
2345
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002346 // here we keep a copy of the drawing state (that is the state that's
2347 // going to be overwritten by handleTransactionLocked()) outside of
2348 // mStateLock so that the side-effects of the State assignment
2349 // don't happen with mStateLock held (which can cause deadlocks).
2350 State drawingState(mDrawingState);
2351
Mathias Agopianca4d3602011-05-19 15:38:14 -07002352 Mutex::Autolock _l(mStateLock);
2353 const nsecs_t now = systemTime();
2354 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002355
Mathias Agopianca4d3602011-05-19 15:38:14 -07002356 // Here we're guaranteed that some transaction flags are set
2357 // so we can call handleTransactionLocked() unconditionally.
2358 // We call getTransactionFlags(), which will also clear the flags,
2359 // with mStateLock held to guarantee that mCurrentState won't change
2360 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002361
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002362 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002363 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002364 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002365
Mathias Agopianca4d3602011-05-19 15:38:14 -07002366 mLastTransactionTime = systemTime() - now;
2367 mDebugInTransaction = 0;
2368 invalidateHwcGeometry();
2369 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002370}
2371
Dominik Laskowski7e045462018-05-30 13:02:02 -07002372DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002373 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002374 // Figure out whether the event is for the primary display or an
2375 // external display by matching the Hwc display id against one for a
2376 // connected display. If we did not find a match, we then check what
2377 // displays are not already connected to determine the type. If we don't
2378 // have a connected primary display, we assume the new display is meant to
2379 // be the primary display, and then if we don't have an external display,
2380 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002381 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2382 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002383 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002384 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002385 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002386 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002387 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002388 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002389 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002390 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002391 return DisplayDevice::DISPLAY_EXTERNAL;
2392 }
2393
2394 return DisplayDevice::DISPLAY_ID_INVALID;
2395}
2396
Lloyd Piqueba04e622017-12-14 17:11:26 -08002397void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2398 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002399 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002400 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002401 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002402 continue;
2403 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002404
2405 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2406 ALOGE("External displays are not supported by the vr hardware composer.");
2407 continue;
2408 }
2409
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002410 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002411 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002412 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002413 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002414 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002415
2416 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002417 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002418 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002419 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002420 DisplayDeviceState info;
2421 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002422 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2423 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002424 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002425 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002426 mInterceptor->saveDisplayCreation(info);
2427 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002428 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002429 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002430
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002431 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002432 if (idx >= 0) {
2433 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002434 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002435 mCurrentState.displays.removeItemsAt(idx);
2436 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002437 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002438 }
2439
2440 processDisplayChangesLocked();
2441 }
2442
2443 mPendingHotplugEvents.clear();
2444}
2445
Lloyd Pique99d3da52018-01-22 17:48:03 -08002446sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002447 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002448 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002449 DisplayDeviceCreationArgs creationArgs(this, displayToken, state.type, displayId);
2450 creationArgs.isSecure = state.isSecure;
2451 creationArgs.displaySurface = dispSurface;
2452 creationArgs.hasWideColorGamut = false;
2453 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002454
Peiyong Lin13effd12018-07-24 17:01:47 -07002455 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002456 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002457 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002458 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002459 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002460 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002461
Dominik Laskowski7e045462018-05-30 13:02:02 -07002462 std::vector<RenderIntent> renderIntents =
2463 getHwComposer().getRenderIntents(displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002464 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002465 }
tangrobin6753a022018-08-10 10:58:54 +08002466 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002467
tangrobin6753a022018-08-10 10:58:54 +08002468 if (displayId >= 0) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002469 getHwComposer().getHdrCapabilities(displayId, &creationArgs.hdrCapabilities);
2470 creationArgs.supportedPerFrameMetadata =
2471 getHwComposer().getSupportedPerFrameMetadata(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002472 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002473
2474 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2475 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002476 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002477
2478 /*
2479 * Create our display's surface
2480 */
Peiyong Lin833074a2018-08-28 11:53:54 -07002481 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002482 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002483 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002484 renderSurface->setNativeWindow(nativeWindow.get());
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002485 creationArgs.displayWidth = renderSurface->getWidth();
2486 creationArgs.displayHeight = renderSurface->getHeight();
2487 creationArgs.renderSurface = std::move(renderSurface);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002488
2489 // Make sure that composition can never be stalled by a virtual display
2490 // consumer that isn't processing buffers fast enough. We have to do this
2491 // in two places:
2492 // * Here, in case the display is composed entirely by HWC.
2493 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2494 // window's swap interval in eglMakeCurrent, so they'll override the
2495 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002496 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002497 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2498 }
2499
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002500 creationArgs.displayInstallOrientation = state.type == DisplayDevice::DISPLAY_PRIMARY
2501 ? primaryDisplayOrientation
2502 : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002503
Lloyd Pique99d3da52018-01-22 17:48:03 -08002504 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002505 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002506
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002507 sp<DisplayDevice> display = new DisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002508
2509 if (maxFrameBufferAcquiredBuffers >= 3) {
2510 nativeWindowSurface->preallocateBuffers();
2511 }
2512
2513 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002514 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002515 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002516 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002517 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002518 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002519 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002520 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002521 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002522 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002523 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002524 display->setLayerStack(state.layerStack);
2525 display->setProjection(state.orientation, state.viewport, state.frame);
2526 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002527
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002528 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002529}
2530
Lloyd Pique347200f2017-12-14 17:00:15 -08002531void SurfaceFlinger::processDisplayChangesLocked() {
2532 // here we take advantage of Vector's copy-on-write semantics to
2533 // improve performance by skipping the transaction entirely when
2534 // know that the lists are identical
2535 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2536 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2537 if (!curr.isIdenticalTo(draw)) {
2538 mVisibleRegionsDirty = true;
2539 const size_t cc = curr.size();
2540 size_t dc = draw.size();
2541
2542 // find the displays that were removed
2543 // (ie: in drawing state but not in current state)
2544 // also handle displays that changed
2545 // (ie: displays that are in both lists)
2546 for (size_t i = 0; i < dc;) {
2547 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2548 if (j < 0) {
2549 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002550 // Call makeCurrent() on the primary display so we can
2551 // be sure that nothing associated with this display
2552 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002553 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2554 defaultDisplay->makeCurrent();
2555 }
2556 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2557 display->disconnect(getHwComposer());
2558 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002559 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002560 if (mUseScheduler) {
2561 mScheduler->hotplugReceived(mAppConnectionHandle,
2562 EventThread::DisplayType::Primary, false);
2563 } else {
2564 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2565 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002566 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002567 if (mUseScheduler) {
2568 mScheduler->hotplugReceived(mAppConnectionHandle,
2569 EventThread::DisplayType::External, false);
2570 } else {
2571 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2572 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002573 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002574 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002575 } else {
2576 // this display is in both lists. see if something changed.
2577 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002578 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002579 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2580 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2581 if (state_binder != draw_binder) {
2582 // changing the surface is like destroying and
2583 // recreating the DisplayDevice, so we just remove it
2584 // from the drawing state, so that it get re-added
2585 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002586 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2587 display->disconnect(getHwComposer());
2588 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002589 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002590 mDrawingState.displays.removeItemsAt(i);
2591 dc--;
2592 // at this point we must loop to the next item
2593 continue;
2594 }
2595
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002596 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002597 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002598 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002599 }
2600 if ((state.orientation != draw[i].orientation) ||
2601 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002602 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002603 }
2604 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002605 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002606 }
2607 }
2608 }
2609 ++i;
2610 }
2611
2612 // find displays that were added
2613 // (ie: in current state but not in drawing state)
2614 for (size_t i = 0; i < cc; i++) {
2615 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2616 const DisplayDeviceState& state(curr[i]);
2617
2618 sp<DisplaySurface> dispSurface;
2619 sp<IGraphicBufferProducer> producer;
2620 sp<IGraphicBufferProducer> bqProducer;
2621 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002622 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002623
Dominik Laskowski7e045462018-05-30 13:02:02 -07002624 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002625 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002626 // Virtual displays without a surface are dormant:
2627 // they have external state (layer stack, projection,
2628 // etc.) but no internal state (i.e. a DisplayDevice).
2629 if (state.surface != nullptr) {
2630 // Allow VR composer to use virtual displays.
2631 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2632 int width = 0;
2633 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2634 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2635 int height = 0;
2636 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2637 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2638 int intFormat = 0;
2639 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2640 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002641 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002642
Dominik Laskowski7e045462018-05-30 13:02:02 -07002643 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2644 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002645 }
2646
2647 // TODO: Plumb requested format back up to consumer
2648
2649 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002650 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002651 bqProducer, bqConsumer,
2652 state.displayName);
2653
2654 dispSurface = vds;
2655 producer = vds;
2656 }
2657 } else {
2658 ALOGE_IF(state.surface != nullptr,
2659 "adding a supported display, but rendering "
2660 "surface is provided (%p), ignoring it",
2661 state.surface.get());
2662
Dominik Laskowski7e045462018-05-30 13:02:02 -07002663 displayId = state.type;
2664 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002665 producer = bqProducer;
2666 }
2667
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002668 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002669 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002670 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002671 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002672 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002673 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002674 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002675 if (mUseScheduler) {
2676 mScheduler->hotplugReceived(mAppConnectionHandle,
2677 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002678 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002679 } else {
2680 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2681 true);
2682 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002683 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002684 if (mUseScheduler) {
2685 mScheduler->hotplugReceived(mAppConnectionHandle,
2686 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002687 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002688 } else {
2689 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2690 true);
2691 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002692 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002693 }
2694 }
2695 }
2696 }
2697 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002698
2699 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002700}
2701
Mathias Agopian87baae12012-07-31 12:38:26 -07002702void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002703{
Dan Stoza7dde5992015-05-22 09:51:44 -07002704 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002705 mCurrentState.traverseInZOrder([](Layer* layer) {
2706 layer->notifyAvailableFrames();
2707 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002708
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002709 /*
2710 * Traversal of the children
2711 * (perform the transaction for each of them if needed)
2712 */
2713
Mathias Agopian3559b072012-08-15 13:46:03 -07002714 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002715 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002716 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002717 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002718
2719 const uint32_t flags = layer->doTransaction(0);
2720 if (flags & Layer::eVisibleRegion)
2721 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002722 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002723 }
2724
2725 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002726 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002727 */
2728
Mathias Agopiane57f2922012-08-09 16:29:12 -07002729 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002730 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002731 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002732 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002733
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002734 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002735 // The transform hint might have changed for some layers
2736 // (either because a display has changed, or because a layer
2737 // as changed).
2738 //
2739 // Walk through all the layers in currentLayers,
2740 // and update their transform hint.
2741 //
2742 // If a layer is visible only on a single display, then that
2743 // display is used to calculate the hint, otherwise we use the
2744 // default display.
2745 //
2746 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2747 // the hint is set before we acquire a buffer from the surface texture.
2748 //
2749 // NOTE: layer transactions have taken place already, so we use their
2750 // drawing state. However, SurfaceFlinger's own transaction has not
2751 // happened yet, so we must use the current state layer list
2752 // (soon to become the drawing state list).
2753 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002754 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002755 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002756 bool first = true;
2757 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002758 // NOTE: we rely on the fact that layers are sorted by
2759 // layerStack first (so we don't have to traverse the list
2760 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002761 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002762 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002763 currentlayerStack = layerStack;
2764 // figure out if this layerstack is mirrored
2765 // (more than one display) if so, pick the default display,
2766 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002767 hintDisplay = nullptr;
2768 for (const auto& [token, display] : mDisplays) {
2769 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2770 if (hintDisplay) {
2771 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002772 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002773 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002774 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002775 }
2776 }
2777 }
2778 }
Chet Haase91d25932013-04-11 15:24:55 -07002779
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002780 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002781 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2782 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002783
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002784 // could be null when this layer is using a layerStack
2785 // that is not visible on any display. Also can occur at
2786 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002787 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002788 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002789
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002790 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002791 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002792 if (hintDisplay) {
2793 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002794 }
Robert Carr2047fae2016-11-28 14:09:09 -08002795
2796 first = false;
2797 });
Mathias Agopian84300952012-11-21 16:02:13 -08002798 }
2799
2800
Mathias Agopian3559b072012-08-15 13:46:03 -07002801 /*
2802 * Perform our own transaction if needed
2803 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002804
2805 if (mLayersAdded) {
2806 mLayersAdded = false;
2807 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002808 mVisibleRegionsDirty = true;
2809 }
2810
2811 // some layers might have been removed, so
2812 // we need to update the regions they're exposing.
2813 if (mLayersRemoved) {
2814 mLayersRemoved = false;
2815 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002816 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002817 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002818 // this layer is not visible anymore
2819 // TODO: we could traverse the tree from front to back and
2820 // compute the actual visible region
2821 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002822 Region visibleReg;
2823 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002824 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002825 }
Robert Carr2047fae2016-11-28 14:09:09 -08002826 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002827 }
2828
2829 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002830
2831 updateCursorAsync();
2832}
2833
2834void SurfaceFlinger::updateCursorAsync()
2835{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002836 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002837 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002838 continue;
2839 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002840
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002841 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2842 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002843 }
2844 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002845}
2846
2847void SurfaceFlinger::commitTransaction()
2848{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002849 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002850 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002851 for (const auto& l : mLayersPendingRemoval) {
2852 recordBufferingStats(l->getName().string(),
2853 l->getOccupancyHistory(true));
2854 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002855 }
2856 mLayersPendingRemoval.clear();
2857 }
2858
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002859 // If this transaction is part of a window animation then the next frame
2860 // we composite should be considered an animation as well.
2861 mAnimCompositionPending = mAnimTransactionPending;
2862
Mathias Agopian4fec8732012-06-29 14:12:52 -07002863 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002864 // clear the "changed" flags in current state
2865 mCurrentState.colorMatrixChanged = false;
2866
Robert Carr1f0a16a2016-10-24 16:27:39 -07002867 mDrawingState.traverseInZOrder([](Layer* layer) {
2868 layer->commitChildList();
2869 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002870 mTransactionPending = false;
2871 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002872 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002873}
2874
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002875void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2876 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002877 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002878 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002879
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002880 Region aboveOpaqueLayers;
2881 Region aboveCoveredLayers;
2882 Region dirty;
2883
Mathias Agopian87baae12012-07-31 12:38:26 -07002884 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002885
Robert Carr2047fae2016-11-28 14:09:09 -08002886 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002887 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002888 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002889
Jesse Hall01e29052013-02-19 16:13:35 -08002890 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002891 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002892 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002893 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002894
Mathias Agopianab028732010-03-16 16:41:46 -07002895 /*
2896 * opaqueRegion: area of a surface that is fully opaque.
2897 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002898 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002899
2900 /*
2901 * visibleRegion: area of a surface that is visible on screen
2902 * and not fully transparent. This is essentially the layer's
2903 * footprint minus the opaque regions above it.
2904 * Areas covered by a translucent surface are considered visible.
2905 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002906 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002907
2908 /*
2909 * coveredRegion: area of a surface that is covered by all
2910 * visible regions above it (which includes the translucent areas).
2911 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002912 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002913
Jesse Halla8026d22012-09-25 13:25:04 -07002914 /*
2915 * transparentRegion: area of a surface that is hinted to be completely
2916 * transparent. This is only used to tell when the layer has no visible
2917 * non-transparent regions and can be removed from the layer list. It
2918 * does not affect the visibleRegion of this layer or any layers
2919 * beneath it. The hint may not be correct if apps don't respect the
2920 * SurfaceView restrictions (which, sadly, some don't).
2921 */
2922 Region transparentRegion;
2923
Mathias Agopianab028732010-03-16 16:41:46 -07002924
2925 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002926 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002927 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002928 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002929 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002930 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002931 if (!visibleRegion.isEmpty()) {
2932 // Remove the transparent area from the visible region
2933 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002934 if (tr.preserveRects()) {
2935 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002936 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002937 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002938 // transformation too complex, can't do the
2939 // transparent region optimization.
2940 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002941 }
Mathias Agopianab028732010-03-16 16:41:46 -07002942 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002943
Mathias Agopianab028732010-03-16 16:41:46 -07002944 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002945 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002946 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002947 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002948 // the opaque region is the layer's footprint
2949 opaqueRegion = visibleRegion;
2950 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002951 }
2952 }
2953
Robert Carre5f4f692018-01-12 13:12:28 -08002954 if (visibleRegion.isEmpty()) {
2955 layer->clearVisibilityRegions();
2956 return;
2957 }
2958
Mathias Agopianab028732010-03-16 16:41:46 -07002959 // Clip the covered region to the visible region
2960 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2961
2962 // Update aboveCoveredLayers for next (lower) layer
2963 aboveCoveredLayers.orSelf(visibleRegion);
2964
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002965 // subtract the opaque region covered by the layers above us
2966 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002967
2968 // compute this layer's dirty region
2969 if (layer->contentDirty) {
2970 // we need to invalidate the whole region
2971 dirty = visibleRegion;
2972 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002973 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002974 layer->contentDirty = false;
2975 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002976 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002977 * the exposed region consists of two components:
2978 * 1) what's VISIBLE now and was COVERED before
2979 * 2) what's EXPOSED now less what was EXPOSED before
2980 *
2981 * note that (1) is conservative, we start with the whole
2982 * visible region but only keep what used to be covered by
2983 * something -- which mean it may have been exposed.
2984 *
2985 * (2) handles areas that were not covered by anything but got
2986 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002987 */
Mathias Agopianab028732010-03-16 16:41:46 -07002988 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002989 const Region oldVisibleRegion = layer->visibleRegion;
2990 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002991 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2992 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002993 }
2994 dirty.subtractSelf(aboveOpaqueLayers);
2995
2996 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002997 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002998
Mathias Agopianab028732010-03-16 16:41:46 -07002999 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003000 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003001
Jesse Halla8026d22012-09-25 13:25:04 -07003002 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003003 layer->setVisibleRegion(visibleRegion);
3004 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003005 layer->setVisibleNonTransparentRegion(
3006 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003007 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003008
Mathias Agopian87baae12012-07-31 12:38:26 -07003009 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003010}
3011
Chia-I Wuab0c3192017-08-01 11:29:00 -07003012void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003013 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003014 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
3015 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003016 }
3017 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003018}
3019
Dan Stoza6b9454d2014-11-07 16:00:59 -08003020bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003021{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003022 ALOGV("handlePageFlip");
3023
Brian Andersond6927fb2016-07-23 23:37:30 -07003024 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003025
Mathias Agopian4fec8732012-06-29 14:12:52 -07003026 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003027 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003028 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003029
3030 // Store the set of layers that need updates. This set must not change as
3031 // buffers are being latched, as this could result in a deadlock.
3032 // Example: Two producers share the same command stream and:
3033 // 1.) Layer 0 is latched
3034 // 2.) Layer 0 gets a new frame
3035 // 2.) Layer 1 gets a new frame
3036 // 3.) Layer 1 is latched.
3037 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3038 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003039 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003040 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003041 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003042 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3043 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003044 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003045 } else {
3046 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003047 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003048 } else {
3049 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003050 }
Robert Carr2047fae2016-11-28 14:09:09 -08003051 });
3052
Dan Stoza9e56aa02015-11-02 13:00:03 -08003053 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri86770e52018-09-24 22:40:58 +00003054 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
Dan Stozaee44edd2015-03-23 15:50:23 -07003055 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003056 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07003057 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06003058 newDataLatched = true;
3059 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003060 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003061
Alec Mouri86770e52018-09-24 22:40:58 +00003062 // Clear the renderengine fence here...
3063 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3064 // clear instead of sp::clear.
3065 getBE().flushFence = Fence::NO_FENCE;
3066
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003067 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003068
3069 // If we will need to wake up at some time in the future to deal with a
3070 // queued frame that shouldn't be displayed during this vsync period, wake
3071 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003072 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003073 signalLayerUpdate();
3074 }
3075
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003076 // enter boot animation on first buffer latch
3077 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3078 ALOGI("Enter boot animation");
3079 mBootStage = BootStage::BOOTANIMATION;
3080 }
3081
Dan Stoza6b9454d2014-11-07 16:00:59 -08003082 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003083 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003084}
3085
Mathias Agopianad456f92011-01-13 17:53:01 -08003086void SurfaceFlinger::invalidateHwcGeometry()
3087{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003088 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003089}
3090
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003091void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
3092 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003093 // We only need to actually compose the display if:
3094 // 1) It is being handled by hardware composer, which may need this to
3095 // keep its virtual display state machine in sync, or
3096 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07003097 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08003098 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003099 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003100 return;
3101 }
3102
Dan Stoza9e56aa02015-11-02 13:00:03 -08003103 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003104 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003105
3106 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003107 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003108}
3109
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003110bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003111 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003112
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003113 const Region bounds(display->bounds());
3114 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003115 const auto displayId = display->getId();
3116 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003117 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003118
Peiyong Lind3788632018-09-18 16:01:31 -07003119 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003120 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003121 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003122
Dan Stoza9e56aa02015-11-02 13:00:03 -08003123 if (hasClientComposition) {
3124 ALOGV("hasClientComposition");
3125
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003126 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003127 if (display->hasWideColorGamut()) {
3128 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003129 }
3130 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003131 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003132 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003133
Dominik Laskowski7e045462018-05-30 13:02:02 -07003134 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003135 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3136 HWC2::Capability::SkipClientColorTransform);
3137
Peiyong Lind3788632018-09-18 16:01:31 -07003138 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003139 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3140 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003141 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003142 }
3143
Chia-I Wud49d6692018-06-27 07:17:41 +08003144 // The current enhanced saturation matrix is designed to enhance Display P3,
3145 // thus we only apply this matrix when the render intent is not colorimetric
3146 // and the output color space is Display P3.
3147 needsEnhancedColorMatrix =
3148 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3149 outputDataspace == Dataspace::DISPLAY_P3);
3150 if (needsEnhancedColorMatrix) {
3151 colorMatrix *= mEnhancedSaturationMatrix;
3152 }
3153
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003154 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003155 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003156 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003157 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003158
3159 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003160 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3161 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3162 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003163 }
3164 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003165 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003166
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003167 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003168 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003169 // when using overlays, we assume a fully transparent framebuffer
3170 // NOTE: we could reduce how much we need to clear, for instance
3171 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003172 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003173 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003174 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003175 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003176 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003177 // we're left with the letterbox region
3178 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003179 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003180
3181 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003182 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003183
Mathias Agopianb9494d52012-04-18 02:28:45 -07003184 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003185 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003186 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003187 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003188 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003189 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003190
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003191 const Rect& bounds = display->getBounds();
3192 const Rect& scissor = display->getScissor();
3193 if (scissor != bounds) {
3194 // scissor doesn't match the screen's dimensions, so we
3195 // need to clear everything outside of it and enable
3196 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003197
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003198 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003199 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003200 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003201 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003202
Mathias Agopian85d751c2012-08-29 16:59:24 -07003203 /*
3204 * and then, render the layers targeted at the framebuffer
3205 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003206
Dan Stoza9e56aa02015-11-02 13:00:03 -08003207 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003208 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003209 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003210 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003211 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003212 displayTransform.transform(layer->visibleRegion)));
3213 ALOGV("Layer: %s", layer->getName().string());
3214 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003215 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003216 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003217 case HWC2::Composition::Cursor:
3218 case HWC2::Composition::Device:
3219 case HWC2::Composition::Sideband:
3220 case HWC2::Composition::SolidColor: {
David Sodmanc1498e62018-09-12 14:36:26 -07003221 const Layer::State& state(layer->getDrawingState());
3222 if (layer->getClearClientTarget(displayId) && !firstLayer &&
3223 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3224 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003225 // never clear the very first layer since we're
3226 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003227 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003228 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003229 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003230 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003231 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003232 if (layer->hasColorTransform()) {
3233 mat4 tmpMatrix;
3234 if (applyColorMatrix) {
3235 tmpMatrix = mDrawingState.colorMatrix;
3236 }
3237 tmpMatrix *= layer->getColorTransform();
3238 if (needsEnhancedColorMatrix) {
3239 tmpMatrix *= mEnhancedSaturationMatrix;
3240 }
3241 getRenderEngine().setColorTransform(tmpMatrix);
3242 } else {
3243 getRenderEngine().setColorTransform(colorMatrix);
3244 }
David Sodmanc1498e62018-09-12 14:36:26 -07003245 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003246 break;
3247 }
3248 default:
3249 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003250 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003251 } else {
3252 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003253 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003254 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003255 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003256
Peiyong Lind3788632018-09-18 16:01:31 -07003257 // Clear color transform matrix at the end of the frame.
3258 getRenderEngine().setColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003259
Mathias Agopianf45c5102012-10-24 16:29:17 -07003260 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003261 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003262 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003263}
3264
Chia-I Wu28e3a252018-09-07 12:05:02 -07003265void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003266 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003267 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003268}
3269
Dan Stoza7d89d062015-04-30 13:29:25 -07003270status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003271 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003272 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003273 const sp<Layer>& lbc,
3274 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003275{
Dan Stoza7d89d062015-04-30 13:29:25 -07003276 // add this layer to the current state list
3277 {
3278 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003279 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003280 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3281 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003282 return NO_MEMORY;
3283 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003284 if (parent == nullptr) {
3285 mCurrentState.layersSortedByZ.add(lbc);
3286 } else {
Rob Carr4bba3702018-10-08 21:53:30 +00003287 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003288 ALOGE("addClientLayer called with a removed parent");
3289 return NAME_NOT_FOUND;
3290 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003291 parent->addChild(lbc);
3292 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003293
Yiwei Zhang243b3782018-05-15 17:40:04 -07003294 if (gbc != nullptr) {
3295 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3296 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3297 mMaxGraphicBufferProducerListSize,
3298 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3299 mGraphicBufferProducerList.size(),
3300 mMaxGraphicBufferProducerListSize, mNumLayers);
3301 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003302 mLayersAdded = true;
3303 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003304 }
3305
Mathias Agopian96f08192010-06-02 23:28:45 -07003306 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003307 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003308
Dan Stoza7d89d062015-04-30 13:29:25 -07003309 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003310}
3311
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003312status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003313 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003314 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3315}
Robert Carr7f9b8992017-03-10 11:08:39 -08003316
chaviwca27f252018-02-06 16:46:39 -08003317status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3318 bool topLevelOnly) {
Rob Carr4bba3702018-10-08 21:53:30 +00003319 if (layer->isPendingRemoval()) {
chaviw8b3871a2017-11-01 17:41:01 -07003320 return NO_ERROR;
3321 }
3322
Robert Carr1f0a16a2016-10-24 16:27:39 -07003323 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003324 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003325 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003326 if (topLevelOnly) {
3327 return NO_ERROR;
3328 }
Rob Carr4bba3702018-10-08 21:53:30 +00003329
3330 sp<Layer> ancestor = p;
3331 while (ancestor->getParent() != nullptr) {
3332 ancestor = ancestor->getParent();
3333 }
3334 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3335 ALOGE("removeLayer called with a layer whose parent has been removed");
3336 return NAME_NOT_FOUND;
3337 }
3338
Chia-I Wufae51c42017-06-15 12:53:59 -07003339 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003340 } else {
3341 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003342 }
3343
Rob Carr4bba3702018-10-08 21:53:30 +00003344 // As a matter of normal operation, the LayerCleaner will produce a second
3345 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3346 // so we will succeed in promoting it, but it's already been removed
3347 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3348 // otherwise something has gone wrong and we are leaking the layer.
3349 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
3350 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3351 layer->getName().string(),
3352 (p != nullptr) ? p->getName().string() : "no-parent");
3353 return BAD_VALUE;
3354 } else if (index < 0) {
3355 return NO_ERROR;
3356 }
3357
Chia-I Wuc6657022017-08-15 11:18:17 -07003358 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003359 mLayersPendingRemoval.add(layer);
3360 mLayersRemoved = true;
Rob Carr4bba3702018-10-08 21:53:30 +00003361 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003362 setTransactionFlags(eTransactionNeeded);
3363 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003364}
3365
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003366uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003367 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003368}
3369
Mathias Agopian3f844832013-08-07 21:24:32 -07003370uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003371 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003372}
3373
Mathias Agopian3f844832013-08-07 21:24:32 -07003374uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003375 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003376}
3377
3378uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003379 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003380 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003381 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003382 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003383 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003384 }
3385 return old;
3386}
3387
chaviwca27f252018-02-06 16:46:39 -08003388bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3389 for (const ComposerState& state : states) {
3390 // Here we need to check that the interface we're given is indeed
3391 // one of our own. A malicious client could give us a nullptr
3392 // IInterface, or one of its own or even one of our own but a
3393 // different type. All these situations would cause us to crash.
3394 if (state.client == nullptr) {
3395 return true;
3396 }
3397
3398 sp<IBinder> binder = IInterface::asBinder(state.client);
3399 if (binder == nullptr) {
3400 return true;
3401 }
3402
3403 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3404 return true;
3405 }
3406 }
3407 return false;
3408}
3409
Mathias Agopian8b33f032012-07-24 20:43:54 -07003410void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003411 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003412 const Vector<DisplayState>& displays,
3413 uint32_t flags)
3414{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003415 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003416 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003417 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003418
chaviwca27f252018-02-06 16:46:39 -08003419 if (containsAnyInvalidClientState(states)) {
3420 return;
3421 }
3422
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003423 if (flags & eAnimation) {
3424 // For window updates that are part of an animation we must wait for
3425 // previous animation "frames" to be handled.
3426 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003427 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003428 if (CC_UNLIKELY(err != NO_ERROR)) {
3429 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003430 // caller after a few seconds.
3431 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3432 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003433 mAnimTransactionPending = false;
3434 break;
3435 }
3436 }
3437 }
3438
chaviwca27f252018-02-06 16:46:39 -08003439 for (const DisplayState& display : displays) {
3440 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003441 }
3442
chaviwca27f252018-02-06 16:46:39 -08003443 for (const ComposerState& state : states) {
3444 transactionFlags |= setClientStateLocked(state);
3445 }
3446
3447 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3448 // as destroyed should only occur after setting all other states. This is to allow for a
3449 // child re-parent to happen before marking its original parent as destroyed (which would
3450 // then mark the child as destroyed).
3451 for (const ComposerState& state : states) {
3452 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003453 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003454
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003455 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3456 // anyway. This can be used as a flush mechanism for previous async transactions.
3457 // Empty animation transaction can be used to simulate back-pressure, so also force a
3458 // transaction for empty animation transactions.
3459 if (transactionFlags == 0 &&
3460 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003461 transactionFlags = eTransactionNeeded;
3462 }
3463
Mathias Agopian386aa982011-11-07 21:58:03 -08003464 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003465 if (mInterceptor->isEnabled()) {
3466 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003467 }
Irvel468051e2016-06-13 16:44:44 -07003468
Mathias Agopian386aa982011-11-07 21:58:03 -08003469 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003470 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3471 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003472 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003473
3474 // if this is a synchronous transaction, wait for it to take effect
3475 // before returning.
3476 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003477 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003478 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003479 if (flags & eAnimation) {
3480 mAnimTransactionPending = true;
3481 }
3482 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003483 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3484 if (CC_UNLIKELY(err != NO_ERROR)) {
3485 // just in case something goes wrong in SF, return to the
3486 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003487 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3488 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003489 break;
3490 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003491 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003492 }
3493}
3494
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003495uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3496 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3497 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003498
Mathias Agopiane57f2922012-08-09 16:29:12 -07003499 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003500 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3501
3502 const uint32_t what = s.what;
3503 if (what & DisplayState::eSurfaceChanged) {
3504 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3505 state.surface = s.surface;
3506 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003507 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003508 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003509 if (what & DisplayState::eLayerStackChanged) {
3510 if (state.layerStack != s.layerStack) {
3511 state.layerStack = s.layerStack;
3512 flags |= eDisplayTransactionNeeded;
3513 }
3514 }
3515 if (what & DisplayState::eDisplayProjectionChanged) {
3516 if (state.orientation != s.orientation) {
3517 state.orientation = s.orientation;
3518 flags |= eDisplayTransactionNeeded;
3519 }
3520 if (state.frame != s.frame) {
3521 state.frame = s.frame;
3522 flags |= eDisplayTransactionNeeded;
3523 }
3524 if (state.viewport != s.viewport) {
3525 state.viewport = s.viewport;
3526 flags |= eDisplayTransactionNeeded;
3527 }
3528 }
3529 if (what & DisplayState::eDisplaySizeChanged) {
3530 if (state.width != s.width) {
3531 state.width = s.width;
3532 flags |= eDisplayTransactionNeeded;
3533 }
3534 if (state.height != s.height) {
3535 state.height = s.height;
3536 flags |= eDisplayTransactionNeeded;
3537 }
3538 }
3539
Mathias Agopiane57f2922012-08-09 16:29:12 -07003540 return flags;
3541}
3542
Robert Carrd4ae7f32018-06-07 16:10:57 -07003543bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3544 IPCThreadState* ipc = IPCThreadState::self();
3545 const int pid = ipc->getCallingPid();
3546 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003547 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003548 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003549 return false;
3550 }
3551 return true;
3552}
3553
chaviwca27f252018-02-06 16:46:39 -08003554uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3555 const layer_state_t& s = composerState.state;
3556 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3557
Mathias Agopian13127d82013-03-05 17:47:11 -08003558 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003559 if (layer == nullptr) {
3560 return 0;
3561 }
3562
Rob Carr4bba3702018-10-08 21:53:30 +00003563 if (layer->isPendingRemoval()) {
chaviw8b3871a2017-11-01 17:41:01 -07003564 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3565 return 0;
3566 }
3567
3568 uint32_t flags = 0;
3569
3570 const uint32_t what = s.what;
3571 bool geometryAppliesWithResize =
3572 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003573
3574 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3575 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003576 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003577 layer->pushPendingState();
3578 }
3579
chaviw8b3871a2017-11-01 17:41:01 -07003580 if (what & layer_state_t::ePositionChanged) {
3581 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3582 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003583 }
chaviw8b3871a2017-11-01 17:41:01 -07003584 }
3585 if (what & layer_state_t::eLayerChanged) {
3586 // NOTE: index needs to be calculated before we update the state
3587 const auto& p = layer->getParent();
3588 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003589 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003590 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003591 mCurrentState.layersSortedByZ.removeAt(idx);
3592 mCurrentState.layersSortedByZ.add(layer);
3593 // we need traversal (state changed)
3594 // AND transaction (list changed)
3595 flags |= eTransactionNeeded|eTraversalNeeded;
3596 }
chaviw8b3871a2017-11-01 17:41:01 -07003597 } else {
3598 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003599 flags |= eTransactionNeeded|eTraversalNeeded;
3600 }
3601 }
chaviw8b3871a2017-11-01 17:41:01 -07003602 }
3603 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003604 // NOTE: index needs to be calculated before we update the state
3605 const auto& p = layer->getParent();
3606 if (p == nullptr) {
3607 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3608 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3609 mCurrentState.layersSortedByZ.removeAt(idx);
3610 mCurrentState.layersSortedByZ.add(layer);
3611 // we need traversal (state changed)
3612 // AND transaction (list changed)
3613 flags |= eTransactionNeeded|eTraversalNeeded;
3614 }
3615 } else {
3616 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3617 flags |= eTransactionNeeded|eTraversalNeeded;
3618 }
chaviw8b3871a2017-11-01 17:41:01 -07003619 }
3620 }
3621 if (what & layer_state_t::eSizeChanged) {
3622 if (layer->setSize(s.w, s.h)) {
3623 flags |= eTraversalNeeded;
3624 }
3625 }
3626 if (what & layer_state_t::eAlphaChanged) {
3627 if (layer->setAlpha(s.alpha))
3628 flags |= eTraversalNeeded;
3629 }
3630 if (what & layer_state_t::eColorChanged) {
3631 if (layer->setColor(s.color))
3632 flags |= eTraversalNeeded;
3633 }
Peiyong Lind3788632018-09-18 16:01:31 -07003634 if (what & layer_state_t::eColorTransformChanged) {
3635 if (layer->setColorTransform(s.colorTransform)) {
3636 flags |= eTraversalNeeded;
3637 }
3638 }
chaviw8b3871a2017-11-01 17:41:01 -07003639 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003640 // TODO: b/109894387
3641 //
3642 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3643 // rotation. To see the problem observe that if we have a square parent, and a child
3644 // of the same size, then we rotate the child 45 degrees around it's center, the child
3645 // must now be cropped to a non rectangular 8 sided region.
3646 //
3647 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3648 // private API, and the WindowManager only uses rotation in one case, which is on a top
3649 // level layer in which cropping is not an issue.
3650 //
3651 // However given that abuse of rotation matrices could lead to surfaces extending outside
3652 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3653 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3654 // transformations.
3655 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003656 flags |= eTraversalNeeded;
3657 }
3658 if (what & layer_state_t::eTransparentRegionChanged) {
3659 if (layer->setTransparentRegionHint(s.transparentRegion))
3660 flags |= eTraversalNeeded;
3661 }
3662 if (what & layer_state_t::eFlagsChanged) {
3663 if (layer->setFlags(s.flags, s.mask))
3664 flags |= eTraversalNeeded;
3665 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003666 if (what & layer_state_t::eCropChanged_legacy) {
3667 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003668 flags |= eTraversalNeeded;
3669 }
chaviw8b3871a2017-11-01 17:41:01 -07003670 if (what & layer_state_t::eLayerStackChanged) {
3671 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3672 // We only allow setting layer stacks for top level layers,
3673 // everything else inherits layer stack from its parent.
3674 if (layer->hasParent()) {
3675 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3676 layer->getName().string());
3677 } else if (idx < 0) {
3678 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3679 "that also does not appear in the top level layer list. Something"
3680 " has gone wrong.", layer->getName().string());
3681 } else if (layer->setLayerStack(s.layerStack)) {
3682 mCurrentState.layersSortedByZ.removeAt(idx);
3683 mCurrentState.layersSortedByZ.add(layer);
3684 // we need traversal (state changed)
3685 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003686 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003687 }
3688 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003689 if (what & layer_state_t::eDeferTransaction_legacy) {
3690 if (s.barrierHandle_legacy != nullptr) {
3691 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3692 } else if (s.barrierGbp_legacy != nullptr) {
3693 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003694 if (authenticateSurfaceTextureLocked(gbp)) {
3695 const auto& otherLayer =
3696 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003697 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003698 } else {
3699 ALOGE("Attempt to defer transaction to to an"
3700 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003701 }
3702 }
chaviw8b3871a2017-11-01 17:41:01 -07003703 // We don't trigger a traversal here because if no other state is
3704 // changed, we don't want this to cause any more work
3705 }
3706 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003707 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003708 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003709 if (!hadParent) {
3710 mCurrentState.layersSortedByZ.remove(layer);
3711 }
chaviw8b3871a2017-11-01 17:41:01 -07003712 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003713 }
chaviw8b3871a2017-11-01 17:41:01 -07003714 }
3715 if (what & layer_state_t::eReparentChildren) {
3716 if (layer->reparentChildren(s.reparentHandle)) {
3717 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003718 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003719 }
chaviw8b3871a2017-11-01 17:41:01 -07003720 if (what & layer_state_t::eDetachChildren) {
3721 layer->detachChildren();
3722 }
3723 if (what & layer_state_t::eOverrideScalingModeChanged) {
3724 layer->setOverrideScalingMode(s.overrideScalingMode);
3725 // We don't trigger a traversal here because if no other state is
3726 // changed, we don't want this to cause any more work
3727 }
Marissa Wall61c58622018-07-18 10:12:20 -07003728 if (what & layer_state_t::eTransformChanged) {
3729 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3730 }
3731 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3732 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3733 flags |= eTraversalNeeded;
3734 }
3735 if (what & layer_state_t::eCropChanged) {
3736 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3737 }
3738 if (what & layer_state_t::eBufferChanged) {
3739 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3740 }
3741 if (what & layer_state_t::eAcquireFenceChanged) {
3742 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3743 }
3744 if (what & layer_state_t::eDataspaceChanged) {
3745 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3746 }
3747 if (what & layer_state_t::eHdrMetadataChanged) {
3748 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3749 }
3750 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3751 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3752 }
3753 if (what & layer_state_t::eApiChanged) {
3754 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3755 }
3756 if (what & layer_state_t::eSidebandStreamChanged) {
3757 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3758 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003759 return flags;
3760}
3761
chaviwca27f252018-02-06 16:46:39 -08003762void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3763 const layer_state_t& state = composerState.state;
3764 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3765
3766 sp<Layer> layer(client->getLayerUser(state.surface));
3767 if (layer == nullptr) {
3768 return;
3769 }
3770
Rob Carr4bba3702018-10-08 21:53:30 +00003771 if (layer->isPendingRemoval()) {
chaviwca27f252018-02-06 16:46:39 -08003772 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3773 return;
3774 }
3775
3776 if (state.what & layer_state_t::eDestroySurface) {
3777 removeLayerLocked(mStateLock, layer);
3778 }
3779}
3780
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003781status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003782 const String8& name,
3783 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003784 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003785 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003786 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003787{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003788 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003789 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003790 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003791 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003792 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003793
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003794 status_t result = NO_ERROR;
3795
3796 sp<Layer> layer;
3797
Cody Northropbc755282017-03-31 12:00:08 -06003798 String8 uniqueName = getUniqueLayerName(name);
3799
Mathias Agopian3165cc22012-08-08 19:42:09 -07003800 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003801 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003802 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3803 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003804
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003805 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003806 case ISurfaceComposerClient::eFXSurfaceBufferState:
3807 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3808 break;
chaviw13fdc492017-06-27 12:40:18 -07003809 case ISurfaceComposerClient::eFXSurfaceColor:
3810 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003811 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003812 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003813 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003814 case ISurfaceComposerClient::eFXSurfaceContainer:
3815 result = createContainerLayer(client,
3816 uniqueName, w, h, flags,
3817 handle, &layer);
3818 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003819 default:
3820 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003821 break;
3822 }
3823
Dan Stoza7d89d062015-04-30 13:29:25 -07003824 if (result != NO_ERROR) {
3825 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003826 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003827
Chia-I Wuab0c3192017-08-01 11:29:00 -07003828 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3829 // TODO b/64227542
3830 if (windowType == 441731) {
3831 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3832 layer->setPrimaryDisplayOnly();
3833 }
3834
Albert Chaulk479c60c2017-01-27 14:21:34 -05003835 layer->setInfo(windowType, ownerUid);
3836
Robert Carr1f0a16a2016-10-24 16:27:39 -07003837 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003838 if (result != NO_ERROR) {
3839 return result;
3840 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003841 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003842
3843 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003844 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003845}
3846
Cody Northropbc755282017-03-31 12:00:08 -06003847String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3848{
3849 bool matchFound = true;
3850 uint32_t dupeCounter = 0;
3851
3852 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3853 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3854
Dan Stoza436ccf32018-06-21 12:10:12 -07003855 // Grab the state lock since we're accessing mCurrentState
3856 Mutex::Autolock lock(mStateLock);
3857
Cody Northropbc755282017-03-31 12:00:08 -06003858 // Loop over layers until we're sure there is no matching name
3859 while (matchFound) {
3860 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003861 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003862 if (layer->getName() == uniqueName) {
3863 matchFound = true;
3864 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3865 }
3866 });
3867 }
3868
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003869 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3870 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003871
3872 return uniqueName;
3873}
3874
Marissa Wallfd668622018-05-10 10:21:13 -07003875status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3876 uint32_t w, uint32_t h, uint32_t flags,
3877 PixelFormat& format, sp<IBinder>* handle,
3878 sp<IGraphicBufferProducer>* gbp,
3879 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003880 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003881 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003882 case PIXEL_FORMAT_TRANSPARENT:
3883 case PIXEL_FORMAT_TRANSLUCENT:
3884 format = PIXEL_FORMAT_RGBA_8888;
3885 break;
3886 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003887 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003888 break;
3889 }
3890
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003891 sp<BufferQueueLayer> layer =
3892 new BufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003893 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003894 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003895 *handle = layer->getHandle();
3896 *gbp = layer->getProducer();
3897 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003898 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003899
Marissa Wallfd668622018-05-10 10:21:13 -07003900 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003901 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003902}
3903
Marissa Wall61c58622018-07-18 10:12:20 -07003904status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3905 uint32_t w, uint32_t h, uint32_t flags,
3906 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003907 sp<BufferStateLayer> layer =
3908 new BufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003909 *handle = layer->getHandle();
3910 *outLayer = layer;
3911
3912 return NO_ERROR;
3913}
3914
chaviw13fdc492017-06-27 12:40:18 -07003915status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003916 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003917 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003918{
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003919 *outLayer = new ColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003920 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003921 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003922}
3923
Robert Carr6b3f6c52018-08-13 13:05:17 -07003924status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3925 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3926 sp<IBinder>* handle, sp<Layer>* outLayer)
3927{
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003928 *outLayer = new ContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003929 *handle = (*outLayer)->getHandle();
3930 return NO_ERROR;
3931}
3932
3933
Mathias Agopianac9fa422013-02-11 16:40:36 -08003934status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003935{
Robert Carr9524cb32017-02-13 11:32:32 -08003936 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003937 status_t err = NO_ERROR;
3938 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003939 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003940 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003941 err = removeLayer(l);
3942 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3943 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003944 }
3945 return err;
3946}
3947
Rob Carr4bba3702018-10-08 21:53:30 +00003948status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
3949{
3950 // called by ~LayerCleaner() when all references to the IBinder (handle)
3951 // are gone
3952 sp<Layer> l = layer.promote();
3953 if (l == nullptr) {
3954 // The layer has already been removed, carry on
3955 return NO_ERROR;
3956 }
3957 // If we have a parent, then we can continue to live as long as it does.
3958 return removeLayer(l, true);
3959}
3960
Mathias Agopianb60314a2012-04-10 22:09:54 -07003961// ---------------------------------------------------------------------------
3962
Andy McFadden13a082e2012-08-24 10:16:42 -07003963void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003964 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3965 if (!displayToken) return;
3966
Jesse Hall01e29052013-02-19 16:13:35 -08003967 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003968 Vector<ComposerState> state;
3969 Vector<DisplayState> displays;
3970 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003971 d.what = DisplayState::eDisplayProjectionChanged |
3972 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003973 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003974 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003975 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003976 d.frame.makeInvalid();
3977 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003978 d.width = 0;
3979 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003980 displays.add(d);
3981 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003982
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003983 const auto display = getDisplayDevice(displayToken);
3984 if (!display) return;
3985
3986 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3987
3988 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003989 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003990 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003991
Brian Andersond0010582017-03-07 13:20:31 -08003992 // Use phase of 0 since phase is not known.
3993 // Use latency of 0, which will snap to the ideal latency.
3994 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003995}
3996
3997void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003998 // Async since we may be called from the main thread.
3999 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004000}
4001
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004002void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
4003 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004004 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004005 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07004006
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004007 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004008 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004009 return;
4010 }
4011
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004012 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004013 ALOGW("Trying to set power mode for virtual display");
4014 return;
4015 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004016
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004017 display->setPowerMode(mode);
4018
Lloyd Pique4dccc412018-01-22 17:21:36 -08004019 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07004020 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004021 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07004022 if (idx < 0) {
4023 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
4024 return;
4025 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07004026 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07004027 }
4028
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004029 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004030 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004031 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004032 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004033 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004034 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004035 if (mUseScheduler) {
4036 mScheduler->onScreenAcquired(mAppConnectionHandle);
4037 } else {
4038 mEventThread->onScreenAcquired();
4039 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004040 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004041 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004042
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004043 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004044 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004045 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004046
4047 struct sched_param param = {0};
4048 param.sched_priority = 1;
4049 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4050 ALOGW("Couldn't set SCHED_FIFO on display on");
4051 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004052 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004053 // Turn off the display
4054 struct sched_param param = {0};
4055 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4056 ALOGW("Couldn't set SCHED_OTHER on display off");
4057 }
4058
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004059 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07004060 disableHardwareVsync(true); // also cancels any in-progress resync
4061
Mathias Agopiancde87a32012-09-13 14:09:01 -07004062 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004063 if (mUseScheduler) {
4064 mScheduler->onScreenReleased(mAppConnectionHandle);
4065 } else {
4066 mEventThread->onScreenReleased();
4067 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004068 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004069
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004070 getHwComposer().setPowerMode(type, mode);
4071 mVisibleRegionsDirty = true;
4072 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004073 } else if (mode == HWC_POWER_MODE_DOZE ||
4074 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004075 // Update display while dozing
4076 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004077 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004078 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004079 if (mUseScheduler) {
4080 mScheduler->onScreenAcquired(mAppConnectionHandle);
4081 } else {
4082 mEventThread->onScreenAcquired();
4083 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004084 resyncToHardwareVsync(true);
4085 }
4086 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4087 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004088 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004089 disableHardwareVsync(true); // also cancels any in-progress resync
4090 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004091 if (mUseScheduler) {
4092 mScheduler->onScreenReleased(mAppConnectionHandle);
4093 } else {
4094 mEventThread->onScreenReleased();
4095 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004096 }
4097 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004098 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004099 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004100 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004101 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004102
4103 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004104}
4105
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004106void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004107 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004108 const auto display = getDisplayDevice(displayToken);
4109 if (!display) {
4110 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4111 displayToken.get());
4112 } else if (display->isVirtual()) {
4113 ALOGW("Attempt to set power mode %d for virtual display", mode);
4114 } else {
4115 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004116 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004117 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004118}
4119
4120// ---------------------------------------------------------------------------
4121
Lloyd Pique755e3192018-01-31 16:46:15 -08004122status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4123 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004124 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004125
Mathias Agopianbd115332013-04-18 16:41:04 -07004126 IPCThreadState* ipc = IPCThreadState::self();
4127 const int pid = ipc->getCallingPid();
4128 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004129
Mathias Agopianbd115332013-04-18 16:41:04 -07004130 if ((uid != AID_SHELL) &&
4131 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004132 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004133 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004134 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004135 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004136 // (this would indicate SF is stuck, but we want to be able to
4137 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004138 status_t err = mStateLock.timedLock(s2ns(1));
4139 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004140 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004141 result.appendFormat(
4142 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4143 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004144 }
4145
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004146 bool dumpAll = true;
4147 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004148 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004149
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004150 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004151 if ((index < numArgs) &&
4152 (args[index] == String16("--list"))) {
4153 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004154 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004155 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004156 }
4157
4158 if ((index < numArgs) &&
4159 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004160 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004161 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004162 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004163 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004164
4165 if ((index < numArgs) &&
4166 (args[index] == String16("--latency-clear"))) {
4167 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004168 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004169 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004170 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004171
4172 if ((index < numArgs) &&
4173 (args[index] == String16("--dispsync"))) {
4174 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004175 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004176 dumpAll = false;
4177 }
Dan Stozab90cf072015-03-05 11:05:59 -08004178
4179 if ((index < numArgs) &&
4180 (args[index] == String16("--static-screen"))) {
4181 index++;
4182 dumpStaticScreenStats(result);
4183 dumpAll = false;
4184 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004185
4186 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004187 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004188 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004189 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004190 dumpAll = false;
4191 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004192
4193 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4194 index++;
4195 dumpWideColorInfo(result);
4196 dumpAll = false;
4197 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004198
4199 if ((index < numArgs) &&
4200 (args[index] == String16("--enable-layer-stats"))) {
4201 index++;
4202 mLayerStats.enable();
4203 dumpAll = false;
4204 }
4205
4206 if ((index < numArgs) &&
4207 (args[index] == String16("--disable-layer-stats"))) {
4208 index++;
4209 mLayerStats.disable();
4210 dumpAll = false;
4211 }
4212
4213 if ((index < numArgs) &&
4214 (args[index] == String16("--clear-layer-stats"))) {
4215 index++;
4216 mLayerStats.clear();
4217 dumpAll = false;
4218 }
4219
4220 if ((index < numArgs) &&
4221 (args[index] == String16("--dump-layer-stats"))) {
4222 index++;
4223 mLayerStats.dump(result);
4224 dumpAll = false;
4225 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004226
4227 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004228 (args[index] == String16("--frame-composition"))) {
4229 index++;
4230 dumpFrameCompositionInfo(result);
4231 dumpAll = false;
4232 }
4233
4234 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004235 (args[index] == String16("--display-identification"))) {
4236 index++;
4237 dumpDisplayIdentificationData(result);
4238 dumpAll = false;
4239 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004240
4241 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4242 index++;
4243 mTimeStats.parseArgs(asProto, args, index, result);
4244 dumpAll = false;
4245 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004246 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004247
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004248 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004249 if (asProto) {
4250 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4251 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4252 } else {
4253 dumpAllLocked(args, index, result);
4254 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004255 }
4256
Mathias Agopian9795c422009-08-26 16:36:26 -07004257 if (locked) {
4258 mStateLock.unlock();
4259 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004260 }
4261 write(fd, result.string(), result.size());
4262 return NO_ERROR;
4263}
4264
Dan Stozac7014012014-02-14 15:03:43 -08004265void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4266 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004267{
Robert Carr2047fae2016-11-28 14:09:09 -08004268 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004269 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004270 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004271}
4272
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004273void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004274 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004275{
4276 String8 name;
4277 if (index < args.size()) {
4278 name = String8(args[index]);
4279 index++;
4280 }
4281
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004282 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4283 getHwComposer().isConnected(displayId)) {
4284 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4285 const nsecs_t period = activeConfig->getVsyncPeriod();
4286 result.appendFormat("%" PRId64 "\n", period);
4287 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004288
4289 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004290 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004291 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004292 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004293 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004294 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004295 }
Robert Carr2047fae2016-11-28 14:09:09 -08004296 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004297 }
4298}
4299
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004300void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004301 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004302{
4303 String8 name;
4304 if (index < args.size()) {
4305 name = String8(args[index]);
4306 index++;
4307 }
4308
Robert Carr2047fae2016-11-28 14:09:09 -08004309 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004310 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004311 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004312 }
Robert Carr2047fae2016-11-28 14:09:09 -08004313 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004314
Svetoslavd85084b2014-03-20 10:28:31 -07004315 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004316}
4317
Jamie Gennis6547ff42013-07-16 20:12:42 -07004318// This should only be called from the main thread. Otherwise it would need
4319// the lock and should use mCurrentState rather than mDrawingState.
4320void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004321 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004322 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004323 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004324
4325 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4326}
4327
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004328void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004329{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004330 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004331
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004332 if (isLayerTripleBufferingDisabled())
4333 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004334
4335 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004336 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004337 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004338 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004339 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4340 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004341 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004342}
4343
Dan Stozab90cf072015-03-05 11:05:59 -08004344void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4345{
4346 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004347 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4348 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004349 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004350 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004351 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4352 b + 1, bucketTimeSec, percent);
4353 }
David Sodman4a36e932017-11-07 14:29:47 -08004354 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004355 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004356 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004357 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004358 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004359}
4360
Dan Stozae77c7662016-05-13 11:37:28 -07004361void SurfaceFlinger::recordBufferingStats(const char* layerName,
4362 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004363 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4364 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004365 for (const auto& segment : history) {
4366 if (!segment.usedThirdBuffer) {
4367 stats.twoBufferTime += segment.totalTime;
4368 }
4369 if (segment.occupancyAverage < 1.0f) {
4370 stats.doubleBufferedTime += segment.totalTime;
4371 } else if (segment.occupancyAverage < 2.0f) {
4372 stats.tripleBufferedTime += segment.totalTime;
4373 }
4374 ++stats.numSegments;
4375 stats.totalTime += segment.totalTime;
4376 }
4377}
4378
Brian Andersond6927fb2016-07-23 23:37:30 -07004379void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4380 result.appendFormat("Layer frame timestamps:\n");
4381
4382 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4383 const size_t count = currentLayers.size();
4384 for (size_t i=0 ; i<count ; i++) {
4385 currentLayers[i]->dumpFrameEvents(result);
4386 }
4387}
4388
Dan Stozae77c7662016-05-13 11:37:28 -07004389void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4390 result.append("Buffering stats:\n");
4391 result.append(" [Layer name] <Active time> <Two buffer> "
4392 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004393 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004394 typedef std::tuple<std::string, float, float, float> BufferTuple;
4395 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004396 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004397 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004398 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004399 if (stats.numSegments == 0) {
4400 continue;
4401 }
4402 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4403 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4404 stats.totalTime;
4405 float doubleBufferRatio = static_cast<float>(
4406 stats.doubleBufferedTime) / stats.totalTime;
4407 float tripleBufferRatio = static_cast<float>(
4408 stats.tripleBufferedTime) / stats.totalTime;
4409 sorted.insert({activeTime, {name, twoBufferRatio,
4410 doubleBufferRatio, tripleBufferRatio}});
4411 }
4412 for (const auto& sortedPair : sorted) {
4413 float activeTime = sortedPair.first;
4414 const BufferTuple& values = sortedPair.second;
4415 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4416 std::get<0>(values).c_str(), activeTime,
4417 std::get<1>(values), std::get<2>(values),
4418 std::get<3>(values));
4419 }
4420 result.append("\n");
4421}
4422
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004423void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004424 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004425 const int32_t displayId = display->getId();
4426 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4427 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004428 continue;
4429 }
4430
Dominik Laskowski7e045462018-05-30 13:02:02 -07004431 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004432 uint8_t port;
4433 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004434 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004435 result.append("no identification data\n");
4436 continue;
4437 }
4438
4439 if (!isEdid(data)) {
4440 result.append("unknown identification data: ");
4441 for (uint8_t byte : data) {
4442 result.appendFormat("%x ", byte);
4443 }
4444 result.append("\n");
4445 continue;
4446 }
4447
4448 const auto edid = parseEdid(data);
4449 if (!edid) {
4450 result.append("invalid EDID: ");
4451 for (uint8_t byte : data) {
4452 result.appendFormat("%x ", byte);
4453 }
4454 result.append("\n");
4455 continue;
4456 }
4457
4458 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4459 result.append(edid->displayName.data(), edid->displayName.length());
4460 result.append("\"\n");
4461 }
4462 result.append("\n");
4463}
4464
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004465void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004466 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4467 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004468 result.appendFormat("DisplayColorSetting: %s\n",
4469 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004470
4471 // TODO: print out if wide-color mode is active or not
4472
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004473 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004474 const int32_t displayId = display->getId();
4475 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004476 continue;
4477 }
4478
Dominik Laskowski7e045462018-05-30 13:02:02 -07004479 result.appendFormat("Display %d color modes:\n", displayId);
4480 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004481 for (auto&& mode : modes) {
4482 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4483 }
4484
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004485 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004486 result.appendFormat(" Current color mode: %s (%d)\n",
4487 decodeColorMode(currentMode).c_str(), currentMode);
4488 }
4489 result.append("\n");
4490}
4491
David Sodman7e4ae112018-02-09 15:02:28 -08004492void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4493 std::string stringResult;
4494
4495 for (const auto& [token, display] : mDisplays) {
4496 const auto displayId = display->getId();
4497 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
4498 continue;
4499 }
4500
4501 const auto& compositionInfoIt = getBE().mEndOfFrameCompositionInfo.find(displayId);
4502 if (compositionInfoIt == getBE().mEndOfFrameCompositionInfo.end()) {
4503 break;
4504 }
4505 const auto& compositionInfoList = compositionInfoIt->second;
4506 stringResult += base::StringPrintf("Display: %d\n", displayId);
4507 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4508 for (const auto& compositionInfo : compositionInfoList) {
4509 compositionInfo.dump(stringResult, nullptr);
4510 stringResult += base::StringPrintf("\n");
4511 }
4512 }
4513
4514 result.append(stringResult.c_str());
4515}
4516
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004517LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004518 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004519 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4520 const State& state = useDrawing ? mDrawingState : mCurrentState;
4521 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004522 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004523 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004524 });
4525
4526 return layersProto;
4527}
4528
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004529LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004530 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004531
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004532 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004533 resolution->set_w(display.getWidth());
4534 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004535
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004536 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4537 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4538 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004539
Dominik Laskowski7e045462018-05-30 13:02:02 -07004540 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004541 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004542 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004543 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004544 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004545 }
4546 });
4547
4548 return layersProto;
4549}
4550
Mathias Agopian74d211a2013-04-22 16:55:35 +02004551void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4552 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004553{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004554 bool colorize = false;
4555 if (index < args.size()
4556 && (args[index] == String16("--color"))) {
4557 colorize = true;
4558 index++;
4559 }
4560
4561 Colorizer colorizer(colorize);
4562
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004563 // figure out if we're stuck somewhere
4564 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004565 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004566 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4567
4568 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004569 * Dump library configuration.
4570 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004571
4572 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004573 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004574 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004575 appendSfConfigString(result);
4576 appendUiConfigString(result);
4577 appendGuiConfigString(result);
4578 result.append("\n");
4579
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004580 result.append("\nDisplay identification data:\n");
4581 dumpDisplayIdentificationData(result);
4582
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004583 result.append("\nWide-Color information:\n");
4584 dumpWideColorInfo(result);
4585
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004586 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004587 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004588 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004589 result.append(SyncFeatures::getInstance().toString());
4590 result.append("\n");
4591
Andy McFadden41d67d72014-04-25 16:58:34 -07004592 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004593 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004594 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004595
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004596 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4597 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004598 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4599 getHwComposer().isConnected(displayId)) {
4600 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004601 result.appendFormat("Display %d: "
4602 "app phase %" PRId64 " ns, "
4603 "sf phase %" PRId64 " ns, "
4604 "early app phase %" PRId64 " ns, "
4605 "early sf phase %" PRId64 " ns, "
4606 "early app gl phase %" PRId64 " ns, "
4607 "early sf gl phase %" PRId64 " ns, "
4608 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4609 displayId,
4610 vsyncPhaseOffsetNs,
4611 sfVsyncPhaseOffsetNs,
4612 appEarlyOffset,
4613 sfEarlyOffset,
4614 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004615 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004616 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004617 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004618 result.append("\n");
4619
Dan Stozab90cf072015-03-05 11:05:59 -08004620 // Dump static screen stats
4621 result.append("\n");
4622 dumpStaticScreenStats(result);
4623 result.append("\n");
4624
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004625 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4626
Dan Stozae77c7662016-05-13 11:37:28 -07004627 dumpBufferingStats(result);
4628
Andy McFadden4803b742012-09-24 19:07:20 -07004629 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004630 * Dump the visible layer list
4631 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004632 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004633 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004634 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4635 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004636 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004637
Chia-I Wu2f884132018-09-13 15:17:58 -07004638 {
4639 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4640 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4641 result.append(LayerProtoParser::layerTreeToString(layerTree).c_str());
4642 result.append("\n");
4643 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004644
David Sodman7e4ae112018-02-09 15:02:28 -08004645 result.append("\nFrame-Composition information:\n");
4646 dumpFrameCompositionInfo(result);
4647 result.append("\n");
4648
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004649 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004650 * Dump Display state
4651 */
4652
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004653 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004654 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004655 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004656 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004657 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004658 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004659 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004660
4661 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004662 * Dump SurfaceFlinger global state
4663 */
4664
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004665 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004666 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004667 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004668
Mathias Agopian888c8222012-08-04 21:10:38 -07004669 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004670 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004671
David Sodmanbc815282017-11-05 18:57:52 -08004672 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004673
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004674 if (display) {
4675 display->undefinedRegion.dump(result, "undefinedRegion");
4676 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4677 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004678 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004679 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004680 " gpu_to_cpu_unsupported : %d\n",
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004681 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004682
4683 if (display) {
4684 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4685 result.appendFormat(" refresh-rate : %f fps\n"
4686 " x-dpi : %f\n"
4687 " y-dpi : %f\n",
4688 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4689 activeConfig->getDpiY());
4690 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004691
Mathias Agopian74d211a2013-04-22 16:55:35 +02004692 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004693 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004694
Ana Krulec98b5b242018-08-10 15:03:23 -07004695 result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004696 /*
4697 * VSYNC state
4698 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004699 if (mUseScheduler) {
4700 mScheduler->dump(mAppConnectionHandle, result);
4701 } else {
4702 mEventThread->dump(result);
4703 }
Dan Stozae22aec72016-08-01 13:20:59 -07004704 result.append("\n");
4705
4706 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004707 * Tracing state
4708 */
4709 mTracing.dump(result);
4710 result.append("\n");
4711
4712 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004713 * HWC layer minidump
4714 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004715 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004716 const int32_t displayId = display->getId();
4717 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004718 continue;
4719 }
4720
Dominik Laskowski7e045462018-05-30 13:02:02 -07004721 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004722 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004723 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004724 result.append("\n");
4725 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004726
4727 /*
4728 * Dump HWComposer state
4729 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004730 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004731 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004732 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004733 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004734 result.appendFormat(" h/w composer %s\n",
4735 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004736 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004737
4738 /*
4739 * Dump gralloc state
4740 */
4741 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4742 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004743
4744 /*
4745 * Dump VrFlinger state if in use.
4746 */
4747 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4748 result.append("VrFlinger state:\n");
4749 result.append(mVrFlinger->Dump().c_str());
4750 result.append("\n");
4751 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004752}
4753
Dominik Laskowski7e045462018-05-30 13:02:02 -07004754const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004755 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004756 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004757 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004758 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004759 }
4760 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004761
4762 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4763 static const Vector<sp<Layer>> empty;
4764 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004765}
4766
Keun young Park63f165f2012-08-31 10:53:36 -07004767bool SurfaceFlinger::startDdmConnection()
4768{
4769 void* libddmconnection_dso =
4770 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4771 if (!libddmconnection_dso) {
4772 return false;
4773 }
4774 void (*DdmConnection_start)(const char* name);
4775 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004776 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004777 if (!DdmConnection_start) {
4778 dlclose(libddmconnection_dso);
4779 return false;
4780 }
4781 (*DdmConnection_start)(getServiceName());
4782 return true;
4783}
4784
Chia-I Wu28f320b2018-05-03 11:02:56 -07004785void SurfaceFlinger::updateColorMatrixLocked() {
4786 mat4 colorMatrix;
4787 if (mGlobalSaturationFactor != 1.0f) {
4788 // Rec.709 luma coefficients
4789 float3 luminance{0.213f, 0.715f, 0.072f};
4790 luminance *= 1.0f - mGlobalSaturationFactor;
4791 mat4 saturationMatrix = mat4(
4792 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4793 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4794 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4795 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4796 );
4797 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4798 } else {
4799 colorMatrix = mClientColorMatrix * mDaltonizer();
4800 }
4801
4802 if (mCurrentState.colorMatrix != colorMatrix) {
4803 mCurrentState.colorMatrix = colorMatrix;
4804 mCurrentState.colorMatrixChanged = true;
4805 setTransactionFlags(eTransactionNeeded);
4806 }
4807}
4808
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004809status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004810#pragma clang diagnostic push
4811#pragma clang diagnostic error "-Wswitch-enum"
4812 switch (static_cast<ISurfaceComposerTag>(code)) {
4813 // These methods should at minimum make sure that the client requested
4814 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004815 case BOOT_FINISHED:
4816 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004817 case CREATE_CONNECTION:
4818 case CREATE_DISPLAY:
4819 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004820 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004821 case GET_ACTIVE_COLOR_MODE:
4822 case GET_ANIMATION_FRAME_STATS:
4823 case GET_HDR_CAPABILITIES:
4824 case SET_ACTIVE_CONFIG:
4825 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004826 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004827 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004828 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4829 IPCThreadState* ipc = IPCThreadState::self();
4830 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4831 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004832 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004833 }
Robert Carr1db73f62016-12-21 12:58:51 -08004834 return OK;
4835 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004836 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004837 IPCThreadState* ipc = IPCThreadState::self();
4838 const int pid = ipc->getCallingPid();
4839 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004840 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4841 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004842 return PERMISSION_DENIED;
4843 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004844 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004845 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004846 // Used by apps to hook Choreographer to SurfaceFlinger.
4847 case CREATE_DISPLAY_EVENT_CONNECTION:
4848 // The following calls are currently used by clients that do not
4849 // request necessary permissions. However, they do not expose any secret
4850 // information, so it is OK to pass them.
4851 case AUTHENTICATE_SURFACE:
4852 case GET_ACTIVE_CONFIG:
4853 case GET_BUILT_IN_DISPLAY:
4854 case GET_DISPLAY_COLOR_MODES:
4855 case GET_DISPLAY_CONFIGS:
4856 case GET_DISPLAY_STATS:
4857 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4858 // Calling setTransactionState is safe, because you need to have been
4859 // granted a reference to Client* and Handle* to do anything with it.
4860 case SET_TRANSACTION_STATE:
4861 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004862 case CREATE_SCOPED_CONNECTION:
4863 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004864 return OK;
4865 }
4866 case CAPTURE_LAYERS:
4867 case CAPTURE_SCREEN: {
4868 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004869 IPCThreadState* ipc = IPCThreadState::self();
4870 const int pid = ipc->getCallingPid();
4871 const int uid = ipc->getCallingUid();
4872 if ((uid != AID_GRAPHICS) &&
4873 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4874 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4875 return PERMISSION_DENIED;
4876 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004877 return OK;
4878 }
4879 // The following codes are deprecated and should never be allowed to access SF.
4880 case CONNECT_DISPLAY_UNUSED:
4881 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4882 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4883 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004884 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004885 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004886
4887 // These codes are used for the IBinder protocol to either interrogate the recipient
4888 // side of the transaction for its canonical interface descriptor or to dump its state.
4889 // We let them pass by default.
4890 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4891 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4892 code == IBinder::SYSPROPS_TRANSACTION) {
4893 return OK;
4894 }
4895 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4896 // in onTransact verifies that the user is root, and has access to use SF.
4897 if (code >= 1000 && code <= 1029) {
4898 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4899 return OK;
4900 }
4901 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4902 return PERMISSION_DENIED;
4903#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004904}
4905
Ana Krulec13be8ad2018-08-21 02:43:56 +00004906status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4907 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004908 status_t credentialCheck = CheckTransactCodeCredentials(code);
4909 if (credentialCheck != OK) {
4910 return credentialCheck;
4911 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004912
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004913 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4914 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004915 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004916 IPCThreadState* ipc = IPCThreadState::self();
4917 const int uid = ipc->getCallingUid();
4918 if (CC_UNLIKELY(uid != AID_SYSTEM
4919 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004920 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004921 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004922 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004923 return PERMISSION_DENIED;
4924 }
4925 int n;
4926 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004927 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004928 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004929 return NO_ERROR;
4930 case 1002: // SHOW_UPDATES
4931 n = data.readInt32();
4932 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004933 invalidateHwcGeometry();
4934 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004935 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004936 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004937 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004938 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004939 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004940 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004941 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004942 setTransactionFlags(
4943 eTransactionNeeded|
4944 eDisplayTransactionNeeded|
4945 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004946 return NO_ERROR;
4947 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004948 case 1006:{ // send empty update
4949 signalRefresh();
4950 return NO_ERROR;
4951 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004952 case 1008: // toggle use of hw composer
4953 n = data.readInt32();
4954 mDebugDisableHWC = n ? 1 : 0;
4955 invalidateHwcGeometry();
4956 repaintEverything();
4957 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004958 case 1009: // toggle use of transform hint
4959 n = data.readInt32();
4960 mDebugDisableTransformHint = n ? 1 : 0;
4961 invalidateHwcGeometry();
4962 repaintEverything();
4963 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004964 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004965 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004966 reply->writeInt32(0);
4967 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004968 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004969 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004970 return NO_ERROR;
4971 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004972 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004973 if (!display) {
4974 return NAME_NOT_FOUND;
4975 }
4976
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004977 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004978 return NO_ERROR;
4979 }
4980 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004981 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004982 // daltonize
4983 n = data.readInt32();
4984 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004985 case 1:
4986 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4987 break;
4988 case 2:
4989 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4990 break;
4991 case 3:
4992 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4993 break;
4994 default:
4995 mDaltonizer.setType(ColorBlindnessType::None);
4996 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004997 }
4998 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004999 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005000 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005001 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005002 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005003
5004 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005005 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005006 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005007 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005008 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005009 // apply a color matrix
5010 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005011 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005012 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005013 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005014 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005015 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005016 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005017 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005018 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005019 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005020 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005021
5022 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5023 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005024 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005025 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5026 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5027 }
5028
Chia-I Wu28f320b2018-05-03 11:02:56 -07005029 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005030 return NO_ERROR;
5031 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005032 // This is an experimental interface
5033 // Needs to be shifted to proper binder interface when we productize
5034 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005035 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07005036 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005037 return NO_ERROR;
5038 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005039 case 1017: {
5040 n = data.readInt32();
5041 mForceFullDamage = static_cast<bool>(n);
5042 return NO_ERROR;
5043 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005044 case 1018: { // Modify Choreographer's phase offset
5045 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005046 if (mUseScheduler) {
5047 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5048 } else {
5049 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5050 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005051 return NO_ERROR;
5052 }
5053 case 1019: { // Modify SurfaceFlinger's phase offset
5054 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005055 if (mUseScheduler) {
5056 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5057 } else {
5058 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5059 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005060 return NO_ERROR;
5061 }
Irvel468051e2016-06-13 16:44:44 -07005062 case 1020: { // Layer updates interceptor
5063 n = data.readInt32();
5064 if (n) {
5065 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005066 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005067 }
5068 else{
5069 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005070 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005071 }
5072 return NO_ERROR;
5073 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005074 case 1021: { // Disable HWC virtual displays
5075 n = data.readInt32();
5076 mUseHwcVirtualDisplays = !n;
5077 return NO_ERROR;
5078 }
Romain Guy0147a172017-06-01 13:53:56 -07005079 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005080 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005081 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005082
Chia-I Wu28f320b2018-05-03 11:02:56 -07005083 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005084 return NO_ERROR;
5085 }
Romain Guy54f154a2017-10-24 21:40:32 +01005086 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005087 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005088 invalidateHwcGeometry();
5089 repaintEverything();
5090 return NO_ERROR;
5091 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005092 // TODO(b/111505327): Find out whether the usage of 1024 can switch to 1030,
5093 // deprecate 1024 if they can.
5094 case 1024: { // Does device have wide color gamut display?
Romain Guy54f154a2017-10-24 21:40:32 +01005095 reply->writeBool(hasWideColorDisplay);
5096 return NO_ERROR;
5097 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005098 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005099 n = data.readInt32();
5100 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005101 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005102 mTracing.enable();
5103 doTracing("tracing.enable");
5104 reply->writeInt32(NO_ERROR);
5105 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005106 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005107 status_t err = mTracing.disable();
5108 reply->writeInt32(err);
5109 }
5110 return NO_ERROR;
5111 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005112 case 1026: { // Get layer tracing status
5113 reply->writeBool(mTracing.isEnabled());
5114 return NO_ERROR;
5115 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005116 // Is a DisplayColorSetting supported?
5117 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005118 const auto display = getDefaultDisplayDevice();
5119 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005120 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005121 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005122
5123 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5124 switch (setting) {
5125 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005126 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005127 break;
5128 case DisplayColorSetting::UNMANAGED:
5129 reply->writeBool(true);
5130 break;
5131 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005132 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005133 break;
5134 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005135 reply->writeBool(
5136 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005137 break;
5138 }
5139 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005140 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005141 // Is VrFlinger active?
5142 case 1028: {
5143 Mutex::Autolock _l(mStateLock);
5144 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5145 return NO_ERROR;
5146 }
David Sodman6d46c1e2018-07-13 12:59:48 -07005147 case 1029: {
5148 // Code 1029 is an experimental feature that allows applications to
5149 // simulate a high frequency panel by setting a multiplier and divisor
5150 // on the VSYNC-sf clock. If either the multiplier or divisor are
David Sodman44b5de02018-08-21 16:28:53 -07005151 // 0, then the code simply return the current multiplier and divisor.
5152 HWC2::Device::FrequencyScaler frequencyScaler;
5153 frequencyScaler.multiplier = data.readInt32();
5154 frequencyScaler.divisor = data.readInt32();
David Sodman6d46c1e2018-07-13 12:59:48 -07005155
David Sodman44b5de02018-08-21 16:28:53 -07005156 if ((frequencyScaler.multiplier == 0) || (frequencyScaler.divisor == 0)) {
5157 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5158 reply->writeInt32(frequencyScaler.multiplier);
5159 reply->writeInt32(frequencyScaler.divisor);
5160 return NO_ERROR;
David Sodman6d46c1e2018-07-13 12:59:48 -07005161 }
5162
David Sodman44b5de02018-08-21 16:28:53 -07005163 if ((frequencyScaler.multiplier == 1) && (frequencyScaler.divisor == 1)) {
David Sodman6d46c1e2018-07-13 12:59:48 -07005164 enableHardwareVsync();
5165 } else {
5166 disableHardwareVsync(true);
5167 }
David Sodman44b5de02018-08-21 16:28:53 -07005168 mPrimaryDispSync->scalePeriod(frequencyScaler);
5169 getBE().mHwc->setDisplayFrequencyScaleParameters(frequencyScaler);
David Sodman6d46c1e2018-07-13 12:59:48 -07005170
David Sodman44b5de02018-08-21 16:28:53 -07005171 ATRACE_INT("PeriodMultiplier", frequencyScaler.multiplier);
5172 ATRACE_INT("PeriodDivisor", frequencyScaler.divisor);
5173
5174 const hwc2_display_t hwcDisplayId = getBE().mHwc->getActiveConfig(
5175 DisplayDevice::DISPLAY_PRIMARY)->getDisplayId();
5176
5177 onHotplugReceived(getBE().mComposerSequenceId,
5178 hwcDisplayId, HWC2::Connection::Disconnected);
5179 onHotplugReceived(getBE().mComposerSequenceId,
5180 hwcDisplayId, HWC2::Connection::Connected);
5181 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5182 reply->writeInt32(frequencyScaler.multiplier);
5183 reply->writeInt32(frequencyScaler.divisor);
5184
David Sodman6d46c1e2018-07-13 12:59:48 -07005185 return NO_ERROR;
5186 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005187 // Is device color managed?
5188 case 1030: {
5189 reply->writeBool(useColorManagement);
5190 return NO_ERROR;
5191 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005192 }
5193 }
5194 return err;
5195}
5196
Steven Thomas6d8110b2017-08-31 18:24:21 -07005197void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005198 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005199 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005200}
5201
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005202// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5203class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005204public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005205 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5206 ~WindowDisconnector() {
5207 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005208 }
5209
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005210private:
5211 ANativeWindow* mWindow;
5212 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005213};
5214
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005215status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
5216 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005217 uint32_t reqWidth, uint32_t reqHeight,
5218 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005219 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005220 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005221
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005222 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005223
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005224 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5225
Chia-I Wu20261cb2018-08-23 12:55:44 -07005226 sp<DisplayDevice> display;
5227 {
5228 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005229
Chia-I Wu20261cb2018-08-23 12:55:44 -07005230 display = getDisplayDeviceLocked(displayToken);
5231 if (!display) return BAD_VALUE;
5232
Chia-I Wu8730ba82018-08-29 09:25:59 -07005233 // ignore sourceCrop (i.e., use the projected logical display
5234 // viewport) until the framework is fixed
5235 sourceCrop.clear();
Chia-I Wucb023152018-08-28 12:57:23 -07005236
5237 // set the requested width/height to the logical display viewport size
5238 // by default
5239 if (reqWidth == 0 || reqHeight == 0) {
5240 reqWidth = uint32_t(display->getViewport().width());
5241 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005242 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005243 }
5244
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005245 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005246
5247 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005248 display, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005249 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005250}
5251
5252status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08005253 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005254 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005255 ATRACE_CALL();
5256
5257 class LayerRenderArea : public RenderArea {
5258 public:
Robert Carr578038f2018-03-09 12:25:24 -08005259 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
5260 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
Chia-I Wu9d1abea2018-08-23 13:44:43 -07005261 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08005262 mLayer(layer),
5263 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005264 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005265 mFlinger(flinger),
5266 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005267 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005268 Rect getBounds() const override {
5269 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005270 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005271 }
Marissa Wall61c58622018-07-18 10:12:20 -07005272 int getHeight() const override {
5273 return mLayer->getActiveHeight(mLayer->getDrawingState());
5274 }
5275 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005276 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005277 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005278 Rect getSourceCrop() const override {
5279 if (mCrop.isEmpty()) {
5280 return getBounds();
5281 } else {
5282 return mCrop;
5283 }
5284 }
Robert Carr578038f2018-03-09 12:25:24 -08005285 class ReparentForDrawing {
5286 public:
5287 const sp<Layer>& oldParent;
5288 const sp<Layer>& newParent;
5289
5290 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5291 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005292 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005293 }
Robert Carr15eae092018-03-23 13:43:53 -07005294 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005295 };
5296
5297 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005298 const Rect sourceCrop = getSourceCrop();
5299 // no need to check rotation because there is none
5300 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5301 sourceCrop.height() != getReqHeight();
5302
Robert Carr578038f2018-03-09 12:25:24 -08005303 if (!mChildrenOnly) {
5304 mTransform = mLayer->getTransform().inverse();
5305 drawLayers();
5306 } else {
5307 Rect bounds = getBounds();
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005308 screenshotParentLayer = new ContainerLayer(
5309 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5310 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005311
5312 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5313 drawLayers();
5314 }
5315 }
chaviwa76b2712017-09-20 12:02:26 -07005316
chaviwa76b2712017-09-20 12:02:26 -07005317 private:
chaviw7206d492017-11-10 16:16:12 -08005318 const sp<Layer> mLayer;
5319 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005320
5321 // In the "childrenOnly" case we reparent the children to a screenshot
5322 // layer which has no properties set and which does not draw.
5323 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005324 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005325 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005326
5327 SurfaceFlinger* mFlinger;
5328 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005329 };
5330
5331 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5332 auto parent = layerHandle->owner.promote();
5333
Rob Carr4bba3702018-10-08 21:53:30 +00005334 if (parent == nullptr || parent->isPendingRemoval()) {
chaviw7206d492017-11-10 16:16:12 -08005335 ALOGE("captureLayers called with a removed parent");
5336 return NAME_NOT_FOUND;
5337 }
5338
Robert Carr578038f2018-03-09 12:25:24 -08005339 const int uid = IPCThreadState::self()->getCallingUid();
5340 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5341 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5342 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5343 return PERMISSION_DENIED;
5344 }
5345
chaviw7206d492017-11-10 16:16:12 -08005346 Rect crop(sourceCrop);
5347 if (sourceCrop.width() <= 0) {
5348 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005349 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005350 }
5351
5352 if (sourceCrop.height() <= 0) {
5353 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005354 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005355 }
5356
5357 int32_t reqWidth = crop.width() * frameScale;
5358 int32_t reqHeight = crop.height() * frameScale;
5359
Chia-I Wu20261cb2018-08-23 12:55:44 -07005360 // really small crop or frameScale
5361 if (reqWidth <= 0) {
5362 reqWidth = 1;
5363 }
5364 if (reqHeight <= 0) {
5365 reqHeight = 1;
5366 }
5367
Robert Carr578038f2018-03-09 12:25:24 -08005368 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005369
Robert Carr578038f2018-03-09 12:25:24 -08005370 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005371 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5372 if (!layer->isVisible()) {
5373 return;
Robert Carr578038f2018-03-09 12:25:24 -08005374 } else if (childrenOnly && layer == parent.get()) {
5375 return;
chaviwa76b2712017-09-20 12:02:26 -07005376 }
5377 visitor(layer);
5378 });
5379 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005380 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005381}
5382
5383status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5384 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005385 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005386 bool useIdentityTransform) {
5387 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005388
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005389 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5390 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5391 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5392 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005393
5394 // This mutex protects syncFd and captureResult for communication of the return values from the
5395 // main thread back to this Binder thread
5396 std::mutex captureMutex;
5397 std::condition_variable captureCondition;
5398 std::unique_lock<std::mutex> captureLock(captureMutex);
5399 int syncFd = -1;
5400 std::optional<status_t> captureResult;
5401
Robert Carr03480e22018-01-04 16:02:06 -08005402 const int uid = IPCThreadState::self()->getCallingUid();
5403 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5404
Dominik Laskowski8c001672018-05-30 16:52:06 -07005405 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005406 // If there is a refresh pending, bug out early and tell the binder thread to try again
5407 // after the refresh.
5408 if (mRefreshPending) {
5409 ATRACE_NAME("Skipping screenshot for now");
5410 std::unique_lock<std::mutex> captureLock(captureMutex);
5411 captureResult = std::make_optional<status_t>(EAGAIN);
5412 captureCondition.notify_one();
5413 return;
5414 }
5415
5416 status_t result = NO_ERROR;
5417 int fd = -1;
5418 {
5419 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005420 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005421 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5422 useIdentityTransform, forSystem, &fd);
5423 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005424 }
5425
5426 {
5427 std::unique_lock<std::mutex> captureLock(captureMutex);
5428 syncFd = fd;
5429 captureResult = std::make_optional<status_t>(result);
5430 captureCondition.notify_one();
5431 }
5432 });
5433
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005434 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005435 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005436 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005437 while (*captureResult == EAGAIN) {
5438 captureResult.reset();
5439 result = postMessageAsync(message);
5440 if (result != NO_ERROR) {
5441 return result;
5442 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005443 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005444 }
5445 result = *captureResult;
5446 }
5447
5448 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005449 sync_wait(syncFd, -1);
5450 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005451 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005452
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005453 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005454}
5455
chaviwa76b2712017-09-20 12:02:26 -07005456void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005457 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005458 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005459 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005460
Lloyd Pique144e1162017-12-20 16:44:52 -08005461 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005462
chaviwa76b2712017-09-20 12:02:26 -07005463 const auto reqWidth = renderArea.getReqWidth();
5464 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005465 const auto sourceCrop = renderArea.getSourceCrop();
5466 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005467
Chia-I Wu36574d92018-05-16 10:54:36 -07005468 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5469 engine.setOutputDataSpace(Dataspace::SRGB);
5470 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005471
Mathias Agopian180f10d2013-04-10 22:55:41 -07005472 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005473 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005474
5475 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005476 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005477 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005478
chaviw50da5042018-04-09 13:49:37 -07005479 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005480 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005481 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005482
chaviwa76b2712017-09-20 12:02:26 -07005483 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005484 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005485 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005486 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005487 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005488}
5489
chaviwa76b2712017-09-20 12:02:26 -07005490status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5491 TraverseLayersFunction traverseLayers,
5492 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005493 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005494 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005495 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005496 ATRACE_CALL();
5497
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005498 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005499
5500 traverseLayers([&](Layer* layer) {
5501 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5502 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005503
Robert Carr03480e22018-01-04 16:02:06 -08005504 // We allow the system server to take screenshots of secure layers for
5505 // use in situations like the Screen-rotation animation and place
5506 // the impetus on WindowManager to not persist them.
5507 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005508 ALOGW("FB is protected: PERMISSION_DENIED");
5509 return PERMISSION_DENIED;
5510 }
5511
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005512 // this binds the given EGLImage as a framebuffer for the
5513 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005514 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005515 if (bufferBond.getStatus() != NO_ERROR) {
5516 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005517 return INVALID_OPERATION;
5518 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005519
Dan Stozaabcda352017-06-01 14:37:39 -07005520 // this will in fact render into our dequeued buffer
5521 // via an FBO, which means we didn't have to create
5522 // an EGLSurface and therefore we're not
5523 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005524 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005525
Alec Mouri492bc572018-09-11 21:40:04 +00005526 base::unique_fd syncFd = getRenderEngine().flush();
5527 if (syncFd < 0) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005528 getRenderEngine().finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005529 }
Alec Mouri492bc572018-09-11 21:40:04 +00005530 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005531
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005532 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005533}
5534
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005535// ---------------------------------------------------------------------------
5536
Dan Stoza412903f2017-04-27 13:42:17 -07005537void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5538 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005539}
5540
Dan Stoza412903f2017-04-27 13:42:17 -07005541void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5542 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005543}
5544
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005545void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005546 const LayerVector::Visitor& visitor) {
5547 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005548 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005549 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005550 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005551 continue;
5552 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005553 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005554 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005555 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005556 return;
5557 }
chaviwa76b2712017-09-20 12:02:26 -07005558 if (!layer->isVisible()) {
5559 return;
5560 }
5561 visitor(layer);
5562 });
5563 }
5564}
5565
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005566}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005567
Lloyd Pique074e8122018-07-26 12:57:23 -07005568
Mathias Agopian3f844832013-08-07 21:24:32 -07005569#if defined(__gl_h_)
5570#error "don't include gl/gl.h in this file"
5571#endif
5572
5573#if defined(__gl2_h_)
5574#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005575#endif