blob: 87d8db739740259a3c7167761c88886f5d7647b1 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Chia-I Wud49d6692018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070050#include <renderengine/RenderEngine.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070051#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070066#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070067#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020070#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080072#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080073#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070077#include "NativeWindowSurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070081#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070082#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070083#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070084#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070086#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070087#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070088#include "Scheduler/EventControlThread.h"
89#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070090#include "Scheduler/InjectVSyncSource.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070091#include "Scheduler/Scheduler.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070092
Mathias Agopianff2ed702013-09-01 21:36:12 -070093#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070094
David Sodman7e4ae112018-02-09 15:02:28 -080095#include "android-base/stringprintf.h"
96
Jiyong Park4b20c2e2017-01-14 19:45:11 +090097#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080098#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -070099#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800100#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900101#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900102
chaviw1d044282017-09-27 12:19:28 -0700103#include <layerproto/LayerProtoParser.h>
104
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800105#define DISPLAY_COUNT 1
106
107namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700108
Jaesoo Lee43518572017-01-23 19:03:16 +0900109using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900110using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700111using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700112using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700113using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700114using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900115
Steven Thomasb02664d2017-07-26 18:48:28 -0700116namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700117
118#pragma clang diagnostic push
119#pragma clang diagnostic error "-Wswitch-enum"
120
121bool isWideColorMode(const ColorMode colorMode) {
122 switch (colorMode) {
123 case ColorMode::DISPLAY_P3:
124 case ColorMode::ADOBE_RGB:
125 case ColorMode::DCI_P3:
126 case ColorMode::BT2020:
127 case ColorMode::BT2100_PQ:
128 case ColorMode::BT2100_HLG:
129 return true;
130 case ColorMode::NATIVE:
131 case ColorMode::STANDARD_BT601_625:
132 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
133 case ColorMode::STANDARD_BT601_525:
134 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
135 case ColorMode::STANDARD_BT709:
136 case ColorMode::SRGB:
137 return false;
138 }
139 return false;
140}
141
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700142ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
143 switch (rotation) {
144 case ISurfaceComposer::eRotateNone:
145 return ui::Transform::ROT_0;
146 case ISurfaceComposer::eRotate90:
147 return ui::Transform::ROT_90;
148 case ISurfaceComposer::eRotate180:
149 return ui::Transform::ROT_180;
150 case ISurfaceComposer::eRotate270:
151 return ui::Transform::ROT_270;
152 }
153 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
154 return ui::Transform::ROT_0;
155}
156
Peiyong Linfca547f2018-07-09 13:03:33 -0700157#pragma clang diagnostic pop
158
Steven Thomasb02664d2017-07-26 18:48:28 -0700159class ConditionalLock {
160public:
161 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
162 if (lock) {
163 mMutex.lock();
164 }
165 }
166 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
167private:
168 Mutex& mMutex;
169 bool mLocked;
170};
Peiyong Linfca547f2018-07-09 13:03:33 -0700171
Steven Thomasb02664d2017-07-26 18:48:28 -0700172} // namespace anonymous
173
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800174// ---------------------------------------------------------------------------
175
Mathias Agopian99b49842011-06-27 16:05:52 -0700176const String16 sHardwareTest("android.permission.HARDWARE_TEST");
177const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
178const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
179const String16 sDump("android.permission.DUMP");
180
181// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800182int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
183int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700184int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700185bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800186uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800187bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800188bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800189int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800190// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600191bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700192int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700193bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700194bool SurfaceFlinger::useContextPriority;
Peiyong Lin0256f722018-08-31 15:45:10 -0700195Dataspace SurfaceFlinger::compositionDataSpace = Dataspace::V0_SRGB;
196ui::PixelFormat SurfaceFlinger::compositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700197
Kalle Raitaa099a242017-01-11 11:17:29 -0800198std::string getHwcServiceName() {
199 char value[PROPERTY_VALUE_MAX] = {};
200 property_get("debug.sf.hwc_service_name", value, "default");
201 ALOGI("Using HWComposer service: '%s'", value);
202 return std::string(value);
203}
204
205bool useTrebleTestingOverride() {
206 char value[PROPERTY_VALUE_MAX] = {};
207 property_get("debug.sf.treble_testing_override", value, "false");
208 ALOGI("Treble testing override: '%s'", value);
209 return std::string(value) == "true";
210}
211
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800212std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
213 switch(displayColorSetting) {
214 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700215 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800216 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700217 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800218 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700219 return std::string("Enhanced");
220 default:
221 return std::string("Unknown ") +
222 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800223 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800224}
225
David Sodmanbc815282017-11-05 18:57:52 -0800226SurfaceFlingerBE::SurfaceFlingerBE()
227 : mHwcServiceName(getHwcServiceName()),
228 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800229 mFrameBuckets(),
230 mTotalTime(0),
231 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800232 mComposerSequenceId(0) {
233}
234
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800235SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800236 : BnSurfaceComposer(),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700237 mTransactionPending(false),
238 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700239 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700240 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800241 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700242 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800243 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800244 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800245 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800246 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800247 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700248 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700249 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700250 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700251 mDebugInTransaction(0),
252 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700253 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700254 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700255 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800256 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800257 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800258 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700259 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800260 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800261 mCreateBufferQueue(&BufferQueue::createBufferQueue),
Lloyd Pique22098362018-09-13 11:46:49 -0700262 mCreateNativeWindowSurface(&surfaceflinger::impl::createNativeWindowSurface) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800263
264SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800265 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800266
267 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
268 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
269
270 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
271 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
272
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800273 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
274 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800275
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700276 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
277 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
278
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700279 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
280 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
281
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800282 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
283 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
284
Steven Thomas050b2c82017-03-06 11:45:16 -0800285 // Vr flinger is only enabled on Daydream ready devices.
286 useVrFlinger = getBool< ISurfaceFlingerConfigs,
287 &ISurfaceFlingerConfigs::useVrFlinger>(false);
288
Fabien Sanglard1971b632017-03-10 14:50:03 -0800289 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
290 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
291
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600292 hasWideColorDisplay =
293 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700294 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700295 getBool<V1_2::ISurfaceFlingerConfigs,
296 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
297
298 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
299 if (surfaceFlingerConfigsServiceV1_2) {
300 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
301 [&](Dataspace tmpDataSpace, ui::PixelFormat tmpPixelFormat) {
302 compositionDataSpace = tmpDataSpace;
303 compositionPixelFormat = tmpPixelFormat;
304 });
305 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600306
Peiyong Linb3839ad2018-09-05 15:37:19 -0700307 useContextPriority = getBool<ISurfaceFlingerConfigs,
308 &ISurfaceFlingerConfigs::useContextPriority>(true);
309
Iris Chang7501ed62018-04-30 14:45:42 +0800310 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700311 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
312 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800313 V1_1::DisplayOrientation::ORIENTATION_0);
314
315 switch (primaryDisplayOrientation) {
316 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700317 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800318 break;
319 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700320 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800321 break;
322 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700323 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800324 break;
325 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700326 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800327 break;
328 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700329 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800330
Lloyd Pique41be5d22018-06-21 13:11:48 -0700331 // Note: We create a local temporary with the real DispSync implementation
332 // type temporarily so we can initialize it with the configured values,
333 // before storing it for more generic use using the interface type.
334 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
335 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
336 SurfaceFlinger::dispSyncPresentTimeOffset);
337 mPrimaryDispSync = std::move(primaryDispSync);
Saurabh Shahf4174532017-07-13 10:45:07 -0700338
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800339 // debugging stuff...
340 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700341
Mathias Agopianb4b17302013-03-20 18:36:41 -0700342 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700343 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700344
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800345 property_get("debug.sf.showupdates", value, "0");
346 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700347
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700348 property_get("debug.sf.ddms", value, "0");
349 mDebugDDMS = atoi(value);
350 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700351 if (!startDdmConnection()) {
352 // start failed, and DDMS debugging not enabled
353 mDebugDDMS = 0;
354 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700355 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700356 ALOGI_IF(mDebugRegion, "showupdates enabled");
357 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700358
359 property_get("debug.sf.disable_backpressure", value, "0");
360 mPropagateBackpressure = !atoi(value);
361 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700362
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800363 property_get("debug.sf.enable_hwc_vds", value, "0");
364 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800365 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800366
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800367 property_get("ro.sf.disable_triple_buffer", value, "1");
368 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800369 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700370
Yiwei Zhang243b3782018-05-15 17:40:04 -0700371 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700372 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
373 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
374
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200375 property_get("debug.sf.early_phase_offset_ns", value, "-1");
376 const int earlySfOffsetNs = atoi(value);
377
378 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
379 const int earlyGlSfOffsetNs = atoi(value);
380
381 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
382 const int earlyAppOffsetNs = atoi(value);
383
384 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
385 const int earlyGlAppOffsetNs = atoi(value);
386
Ana Krulec98b5b242018-08-10 15:03:23 -0700387 property_get("debug.sf.use_scheduler", value, "0");
388 mUseScheduler = atoi(value);
389
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200390 const VSyncModulator::Offsets earlyOffsets =
391 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
392 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
393 const VSyncModulator::Offsets earlyGlOffsets =
394 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
395 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
396 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
397 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700398
Romain Guy11d63f42017-07-20 12:47:14 -0700399 // We should be reading 'persist.sys.sf.color_saturation' here
400 // but since /data may be encrypted, we need to wait until after vold
401 // comes online to attempt to read the property. The property is
402 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800403
404 if (useTrebleTestingOverride()) {
405 // Without the override SurfaceFlinger cannot connect to HIDL
406 // services that are not listed in the manifests. Considered
407 // deriving the setting from the set service name, but it
408 // would be brittle if the name that's not 'default' is used
409 // for production purposes later on.
410 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
411 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800412}
413
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800414void SurfaceFlinger::onFirstRef()
415{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800416 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800417}
418
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800419SurfaceFlinger::~SurfaceFlinger()
420{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800421}
422
Dan Stozac7014012014-02-14 15:03:43 -0800423void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800424{
425 // the window manager died on us. prepare its eulogy.
426
Andy McFadden13a082e2012-08-24 10:16:42 -0700427 // restore initial conditions (default device unblank, etc)
428 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800429
430 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700431 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800432}
433
Robert Carr1db73f62016-12-21 12:58:51 -0800434static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700435 status_t err = client->initCheck();
436 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800437 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800438 }
Robert Carr1db73f62016-12-21 12:58:51 -0800439 return nullptr;
440}
441
442sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
443 return initClient(new Client(this));
444}
445
446sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
447 const sp<IGraphicBufferProducer>& gbp) {
448 if (authenticateSurfaceTexture(gbp) == false) {
449 return nullptr;
450 }
451 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
452 if (layer == nullptr) {
453 return nullptr;
454 }
455
456 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800457}
458
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700459sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
460 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700461{
462 class DisplayToken : public BBinder {
463 sp<SurfaceFlinger> flinger;
464 virtual ~DisplayToken() {
465 // no more references, this display must be terminated
466 Mutex::Autolock _l(flinger->mStateLock);
467 flinger->mCurrentState.displays.removeItem(this);
468 flinger->setTransactionFlags(eDisplayTransactionNeeded);
469 }
470 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700471 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700472 : flinger(flinger) {
473 }
474 };
475
476 sp<BBinder> token = new DisplayToken(this);
477
478 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700479 DisplayDeviceState info;
480 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700481 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700482 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700483 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800484 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700485 return token;
486}
487
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700488void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700489 Mutex::Autolock _l(mStateLock);
490
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700491 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700492 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700493 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700494 return;
495 }
496
497 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700498 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700499 ALOGE("destroyDisplay called for non-virtual display");
500 return;
501 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700502 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700503 mCurrentState.displays.removeItemsAt(idx);
504 setTransactionFlags(eDisplayTransactionNeeded);
505}
506
Mathias Agopiane57f2922012-08-09 16:29:12 -0700507sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700508 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700509 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800510 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700511 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700512 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700513}
514
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800515void SurfaceFlinger::bootFinished()
516{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700517 if (mStartPropertySetThread->join() != NO_ERROR) {
518 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800519 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800520 const nsecs_t now = systemTime();
521 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000522 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700523
524 // wait patiently for the window manager death
525 const String16 name("window");
526 sp<IBinder> window(defaultServiceManager()->getService(name));
527 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700528 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700529 }
530
Steven Thomas050b2c82017-03-06 11:45:16 -0800531 if (mVrFlinger) {
532 mVrFlinger->OnBootFinished();
533 }
534
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700535 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700536 // formerly we would just kill the process, but we now ask it to exit so it
537 // can choose where to stop the animation.
538 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700539
540 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
541 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
542 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700543
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800544 postMessageAsync(new LambdaMessage([this] {
545 readPersistentProperties();
546 mBootStage = BootStage::FINISHED;
547 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800548}
549
Dan Stoza436ccf32018-06-21 12:10:12 -0700550uint32_t SurfaceFlinger::getNewTexture() {
551 {
552 std::lock_guard lock(mTexturePoolMutex);
553 if (!mTexturePool.empty()) {
554 uint32_t name = mTexturePool.back();
555 mTexturePool.pop_back();
556 ATRACE_INT("TexturePoolSize", mTexturePool.size());
557 return name;
558 }
559
560 // The pool was too small, so increase it for the future
561 ++mTexturePoolSize;
562 }
563
564 // The pool was empty, so we need to get a new texture name directly using a
565 // blocking call to the main thread
566 uint32_t name = 0;
567 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
568 return name;
569}
570
Mathias Agopian3f844832013-08-07 21:24:32 -0700571void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700572 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700573}
574
Wei Wangf9b05ee2017-07-19 20:59:39 -0700575// Do not call property_set on main thread which will be blocked by init
576// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700577void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700578 ALOGI( "SurfaceFlinger's main thread ready to run. "
579 "Initializing graphics H/W...");
580
Thierry Strudel2924d012017-08-14 15:19:37 -0700581 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900582
Steven Thomasb02664d2017-07-26 18:48:28 -0700583 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800584
Steven Thomasb02664d2017-07-26 18:48:28 -0700585 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700586 if (mUseScheduler) {
Ana Krulece588e312018-09-18 12:32:24 -0700587 mScheduler = std::make_unique<Scheduler>(
588 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Ana Krulec98b5b242018-08-10 15:03:23 -0700589 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700590 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700591 [this] { resyncWithRateLimit(); },
592 impl::EventThread::InterceptVSyncsCallback());
593 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700594 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700595 [this] { resyncWithRateLimit(); },
596 [this](nsecs_t timestamp) {
597 mInterceptor->saveVSyncEvent(timestamp);
598 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800599
Ana Krulec98b5b242018-08-10 15:03:23 -0700600 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700601 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
602 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700603 } else {
604 mEventThreadSource =
605 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
606 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
607 mEventThread =
608 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
609 [this] { resyncWithRateLimit(); },
610 impl::EventThread::InterceptVSyncsCallback(),
611 "appEventThread");
612 mSfEventThreadSource =
613 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
614 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
615
616 mSFEventThread =
617 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
618 [this] { resyncWithRateLimit(); },
619 [this](nsecs_t timestamp) {
620 mInterceptor->saveVSyncEvent(timestamp);
621 },
622 "sfEventThread");
623 mEventQueue->setEventThread(mSFEventThread.get());
624 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
625 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800626
Steven Thomasb02664d2017-07-26 18:48:28 -0700627 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700628 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700629 renderEngineFeature |= (useColorManagement ?
630 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700631 renderEngineFeature |= (useContextPriority ?
632 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700633
634 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
635 getBE().mRenderEngine =
Peiyong Linf11f39b2018-09-05 14:37:41 -0700636 renderengine::RenderEngine::create(static_cast<int32_t>(compositionPixelFormat),
637 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800638 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700639
640 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
641 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800642 getBE().mHwc.reset(
643 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700644 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800645 // Process any initial hotplug and resulting display changes.
646 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700647 const auto display = getDefaultDisplayDeviceLocked();
648 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
649 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
650 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800651
Lloyd Piquefcd86612017-12-14 17:15:36 -0800652 // make the default display GLContext current so that we can create textures
653 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700654 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800655
Steven Thomas050b2c82017-03-06 11:45:16 -0800656 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700657 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700658 // This callback is called from the vr flinger dispatch thread. We
659 // need to call signalTransaction(), which requires holding
660 // mStateLock when we're not on the main thread. Acquiring
661 // mStateLock from the vr flinger dispatch thread might trigger a
662 // deadlock in surface flinger (see b/66916578), so post a message
663 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700664 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700665 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
666 mVrFlingerRequestsDisplay = requestDisplay;
667 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700668 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800669 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700670 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
671 getHwComposer()
672 .getHwcDisplayId(display->getId())
673 .value_or(0),
674 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800675 if (!mVrFlinger) {
676 ALOGE("Failed to start vrflinger");
677 }
678 }
679
Lloyd Pique379adc12018-01-22 17:31:47 -0800680 mEventControlThread = std::make_unique<impl::EventControlThread>(
681 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700682
Mathias Agopian92a979a2012-08-02 18:32:23 -0700683 // initialize our drawing state
684 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700685
Andy McFadden13a082e2012-08-24 10:16:42 -0700686 // set initial conditions (e.g. unblank default device)
687 initializeDisplays();
688
David Sodmanbc815282017-11-05 18:57:52 -0800689 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700690
Wei Wangf9b05ee2017-07-19 20:59:39 -0700691 // Inform native graphics APIs whether the present timestamp is supported:
692 if (getHwComposer().hasCapability(
693 HWC2::Capability::PresentFenceIsNotReliable)) {
694 mStartPropertySetThread = new StartPropertySetThread(false);
695 } else {
696 mStartPropertySetThread = new StartPropertySetThread(true);
697 }
698
699 if (mStartPropertySetThread->Start() != NO_ERROR) {
700 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800701 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800702
Chia-I Wud49d6692018-06-27 07:17:41 +0800703 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
704 // is used to saturate legacy sRGB content. However, to make sure the same color under
705 // Display P3 will be saturated to the same color, we intentionally break the API spec
706 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
707 // such saturation matrix on Display P3 is understood fully, the API should always return
708 // identify matrix.
709 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
710 Dataspace::SRGB_LINEAR);
711
712 // we will apply this on Display P3.
713 if (mEnhancedSaturationMatrix != mat4()) {
714 ColorSpace srgb(ColorSpace::sRGB());
715 ColorSpace displayP3(ColorSpace::DisplayP3());
716 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
717 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
718 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
719 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800720
Dan Stoza9e56aa02015-11-02 13:00:03 -0800721 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700722}
723
Romain Guy11d63f42017-07-20 12:47:14 -0700724void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700725 Mutex::Autolock _l(mStateLock);
726
Romain Guy11d63f42017-07-20 12:47:14 -0700727 char value[PROPERTY_VALUE_MAX];
728
729 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800730 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700731 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800732 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100733
734 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700735 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700736}
737
Mathias Agopiana67e4182012-06-19 17:26:12 -0700738void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800739 // Start boot animation service by setting a property mailbox
740 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700741 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800742 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700743 if (mStartPropertySetThread->join() != NO_ERROR) {
744 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800745 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700746}
747
Mathias Agopian875d8e12013-06-07 15:35:48 -0700748size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800749 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700750}
751
Mathias Agopian875d8e12013-06-07 15:35:48 -0700752size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800753 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700754}
755
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800756// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800757
Jamie Gennis582270d2011-08-17 18:19:00 -0700758bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800759 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800760 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800761 return authenticateSurfaceTextureLocked(bufferProducer);
762}
763
764bool SurfaceFlinger::authenticateSurfaceTextureLocked(
765 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800766 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800767 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800768}
769
Brian Anderson6b376712017-04-04 10:51:39 -0700770status_t SurfaceFlinger::getSupportedFrameTimestamps(
771 std::vector<FrameEvent>* outSupported) const {
772 *outSupported = {
773 FrameEvent::REQUESTED_PRESENT,
774 FrameEvent::ACQUIRE,
775 FrameEvent::LATCH,
776 FrameEvent::FIRST_REFRESH_START,
777 FrameEvent::LAST_REFRESH_START,
778 FrameEvent::GPU_COMPOSITION_DONE,
779 FrameEvent::DEQUEUE_READY,
780 FrameEvent::RELEASE,
781 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700782 ConditionalLock _l(mStateLock,
783 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700784 if (!getHwComposer().hasCapability(
785 HWC2::Capability::PresentFenceIsNotReliable)) {
786 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
787 }
788 return NO_ERROR;
789}
790
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700791status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
792 Vector<DisplayInfo>* configs) {
793 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700794 return BAD_VALUE;
795 }
796
Jesse Hall692c7232012-11-08 15:41:56 -0800797 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700798 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
799 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700800 type = i;
801 break;
802 }
803 }
804
805 if (type < 0) {
806 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700807 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700808
Mathias Agopian8b736f12012-08-13 17:54:26 -0700809 // TODO: Not sure if display density should handled by SF any longer
810 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700811 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700812 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700813 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800814 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700815 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700816 }
817 return density;
818 }
819 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700820 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700821 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700822 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700823 return getDensityFromProperty("ro.sf.lcd_density"); }
824 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700825
Dan Stoza7f7da322014-05-02 15:26:25 -0700826 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700827
Steven Thomas6d8110b2017-08-31 18:24:21 -0700828 ConditionalLock _l(mStateLock,
829 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800830 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700831 DisplayInfo info = DisplayInfo();
832
Dan Stoza9e56aa02015-11-02 13:00:03 -0800833 float xdpi = hwConfig->getDpiX();
834 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700835
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700836 info.w = hwConfig->getWidth();
837 info.h = hwConfig->getHeight();
838 // Default display viewport to display width and height
839 info.viewportW = info.w;
840 info.viewportH = info.h;
841
Dan Stoza7f7da322014-05-02 15:26:25 -0700842 if (type == DisplayDevice::DISPLAY_PRIMARY) {
843 // The density of the device is provided by a build property
844 float density = Density::getBuildDensity() / 160.0f;
845 if (density == 0) {
846 // the build doesn't provide a density -- this is wrong!
847 // use xdpi instead
848 ALOGE("ro.sf.lcd_density must be defined as a build property");
849 density = xdpi / 160.0f;
850 }
851 if (Density::getEmuDensity()) {
852 // if "qemu.sf.lcd_density" is specified, it overrides everything
853 xdpi = ydpi = density = Density::getEmuDensity();
854 density /= 160.0f;
855 }
856 info.density = density;
857
858 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700859 const auto display = getDefaultDisplayDeviceLocked();
860 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700861
862 // This is for screenrecord
863 const Rect viewport = display->getViewport();
864 if (viewport.isValid()) {
865 info.viewportW = uint32_t(viewport.getWidth());
866 info.viewportH = uint32_t(viewport.getHeight());
867 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700868 } else {
869 // TODO: where should this value come from?
870 static const int TV_DENSITY = 213;
871 info.density = TV_DENSITY / 160.0f;
872 info.orientation = 0;
873 }
874
Dan Stoza7f7da322014-05-02 15:26:25 -0700875 info.xdpi = xdpi;
876 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800877 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900878 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800879
Andy McFadden91b2ca82014-06-13 14:04:23 -0700880 // This is how far in advance a buffer must be queued for
881 // presentation at a given time. If you want a buffer to appear
882 // on the screen at time N, you must submit the buffer before
883 // (N - presentationDeadline).
884 //
885 // Normally it's one full refresh period (to give SF a chance to
886 // latch the buffer), but this can be reduced by configuring a
887 // DispSync offset. Any additional delays introduced by the hardware
888 // composer or panel must be accounted for here.
889 //
890 // We add an additional 1ms to allow for processing time and
891 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800892 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800893 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700894
895 // All non-virtual displays are currently considered secure.
896 info.secure = true;
897
Iris Chang7501ed62018-04-30 14:45:42 +0800898 if (type == DisplayDevice::DISPLAY_PRIMARY &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700899 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800900 std::swap(info.w, info.h);
901 }
902
Michael Wright28f24d02016-07-12 13:30:53 -0700903 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700904 }
905
Dan Stoza7f7da322014-05-02 15:26:25 -0700906 return NO_ERROR;
907}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700908
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700909status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
910 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700911 return BAD_VALUE;
912 }
913
Ana Krulece588e312018-09-18 12:32:24 -0700914 // FIXME for now we always return stats for the primary display.
915 if (mUseScheduler) {
916 mScheduler->getDisplayStatInfo(stats);
917 } else {
918 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
919 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
920 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700921 return NO_ERROR;
922}
923
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700924int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
925 const auto display = getDisplayDevice(displayToken);
926 if (!display) {
927 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800928 return BAD_VALUE;
929 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700930
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700931 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700932}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700933
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700934void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
935 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700936 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700937 return;
938 }
939
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700940 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700941 ALOGW("Trying to set config for virtual display");
942 return;
943 }
944
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700945 display->setActiveConfig(mode);
946 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700947}
948
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700949status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700950 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700951 Vector<DisplayInfo> configs;
952 getDisplayConfigs(displayToken, &configs);
953 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
954 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
955 configs.size());
956 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700957 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700958 const auto display = getDisplayDevice(displayToken);
959 if (!display) {
960 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
961 displayToken.get());
962 } else if (display->isVirtual()) {
963 ALOGW("Attempt to set active config %d for virtual display", mode);
964 } else {
965 setActiveConfigInternal(display, mode);
966 }
967 }));
968
Mathias Agopian888c8222012-08-04 21:10:38 -0700969 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700970}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700971status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
972 Vector<ColorMode>* outColorModes) {
973 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700974 return BAD_VALUE;
975 }
976
Michael Wright28f24d02016-07-12 13:30:53 -0700977 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700978 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
979 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700980 type = i;
981 break;
982 }
983 }
984
985 if (type < 0) {
986 return type;
987 }
988
Peiyong Lina52f0292018-03-14 17:26:31 -0700989 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700990 {
991 ConditionalLock _l(mStateLock,
992 std::this_thread::get_id() != mMainThreadId);
993 modes = getHwComposer().getColorModes(type);
994 }
Michael Wright28f24d02016-07-12 13:30:53 -0700995 outColorModes->clear();
996 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
997
998 return NO_ERROR;
999}
1000
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001001ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1002 if (const auto display = getDisplayDevice(displayToken)) {
1003 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001004 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001005 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001006}
1007
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001008void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1009 Dataspace dataSpace, RenderIntent renderIntent) {
1010 ColorMode currentMode = display->getActiveColorMode();
1011 Dataspace currentDataSpace = display->getCompositionDataSpace();
1012 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001013
Peiyong Lin38e9a562018-04-10 16:24:20 -07001014 if (mode == currentMode && dataSpace == currentDataSpace &&
1015 renderIntent == currentRenderIntent) {
1016 return;
1017 }
1018
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001019 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001020 ALOGW("Trying to set config for virtual display");
1021 return;
1022 }
1023
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001024 display->setActiveColorMode(mode);
1025 display->setCompositionDataSpace(dataSpace);
1026 display->setActiveRenderIntent(renderIntent);
1027 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001028
1029 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001030 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1031 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001032}
1033
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001034status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001035 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001036 Vector<ColorMode> modes;
1037 getDisplayColorModes(displayToken, &modes);
1038 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1039 if (mode < ColorMode::NATIVE || !exists) {
1040 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1041 decodeColorMode(mode).c_str(), mode, displayToken.get());
1042 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001043 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001044 const auto display = getDisplayDevice(displayToken);
1045 if (!display) {
1046 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1047 decodeColorMode(mode).c_str(), mode, displayToken.get());
1048 } else if (display->isVirtual()) {
1049 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1050 decodeColorMode(mode).c_str(), mode);
1051 } else {
1052 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1053 RenderIntent::COLORIMETRIC);
1054 }
1055 }));
1056
Michael Wright28f24d02016-07-12 13:30:53 -07001057 return NO_ERROR;
1058}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001059
Svetoslavd85084b2014-03-20 10:28:31 -07001060status_t SurfaceFlinger::clearAnimationFrameStats() {
1061 Mutex::Autolock _l(mStateLock);
1062 mAnimFrameTracker.clearStats();
1063 return NO_ERROR;
1064}
1065
1066status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1067 Mutex::Autolock _l(mStateLock);
1068 mAnimFrameTracker.getStats(outStats);
1069 return NO_ERROR;
1070}
1071
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001072status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1073 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001074 Mutex::Autolock _l(mStateLock);
1075
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001076 const auto display = getDisplayDeviceLocked(displayToken);
1077 if (!display) {
1078 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001079 return BAD_VALUE;
1080 }
1081
Peiyong Linfb069302018-04-25 14:34:31 -07001082 // At this point the DisplayDeivce should already be set up,
1083 // meaning the luminance information is already queried from
1084 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001085 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001086 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1087 capabilities.getDesiredMaxLuminance(),
1088 capabilities.getDesiredMaxAverageLuminance(),
1089 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001090
1091 return NO_ERROR;
1092}
1093
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001094status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001095 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001096 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001097
Chia-I Wu90f669f2017-10-05 14:24:41 -07001098 if (mInjectVSyncs == enable) {
1099 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001100 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001101
Ana Krulec98b5b242018-08-10 15:03:23 -07001102 // TODO(akrulec): Part of the Injector should be refactored, so that it
1103 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001104 if (enable) {
1105 ALOGV("VSync Injections enabled");
1106 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001107 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001108 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001109 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001110 impl::EventThread::InterceptVSyncsCallback(),
1111 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001112 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001113 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001114 } else {
1115 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001116 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001117 }
1118
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001119 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001120 }));
1121
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001122 return NO_ERROR;
1123}
1124
1125status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001126 Mutex::Autolock _l(mStateLock);
1127
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001128 if (!mInjectVSyncs) {
1129 ALOGE("VSync Injections not enabled");
1130 return BAD_VALUE;
1131 }
1132 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1133 ALOGV("Injecting VSync inside SurfaceFlinger");
1134 mVSyncInjector->onInjectSyncEvent(when);
1135 }
1136 return NO_ERROR;
1137}
1138
Lloyd Pique755e3192018-01-31 16:46:15 -08001139status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1140 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001141 // Try to acquire a lock for 1s, fail gracefully
1142 const status_t err = mStateLock.timedLock(s2ns(1));
1143 const bool locked = (err == NO_ERROR);
1144 if (!locked) {
1145 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1146 return TIMED_OUT;
1147 }
1148
1149 outLayers->clear();
1150 mCurrentState.traverseInZOrder([&](Layer* layer) {
1151 outLayers->push_back(layer->getLayerDebugInfo());
1152 });
1153
1154 mStateLock.unlock();
1155 return NO_ERROR;
1156}
1157
Peiyong Lin0256f722018-08-31 15:45:10 -07001158status_t SurfaceFlinger::getCompositionPreference(Dataspace* outDataSpace,
1159 ui::PixelFormat* outPixelFormat) const {
1160 *outDataSpace = compositionDataSpace;
1161 *outPixelFormat = compositionPixelFormat;
1162 return NO_ERROR;
1163}
1164
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001165// ----------------------------------------------------------------------------
1166
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001167sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1168 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001169 if (mUseScheduler) {
1170 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1171 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1172 } else {
1173 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1174 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001175 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001176 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1177 return mSFEventThread->createEventConnection();
1178 } else {
1179 return mEventThread->createEventConnection();
1180 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001181 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001182}
1183
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001184// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001185
1186void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001187 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001188}
1189
1190void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001191 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001192}
1193
1194void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001195 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001196}
1197
1198void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001199 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001200 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001201}
1202
1203status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001204 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001205 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001206}
1207
1208status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001209 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001210 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001211 if (res == NO_ERROR) {
1212 msg->wait();
1213 }
1214 return res;
1215}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001216
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001217void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001218 do {
1219 waitForEvent();
1220 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001221}
1222
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001223void SurfaceFlinger::enableHardwareVsync() {
1224 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001225 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001226 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001227 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001228 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001229 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001230}
1231
Jesse Hall948fe0c2013-10-14 12:56:09 -07001232void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001233 Mutex::Autolock _l(mHWVsyncLock);
1234
Jesse Hall948fe0c2013-10-14 12:56:09 -07001235 if (makeAvailable) {
1236 mHWVsyncAvailable = true;
1237 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001238 // Hardware vsync is not currently available, so abort the resync
1239 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001240 return;
1241 }
1242
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001243 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1244 if (!getHwComposer().isConnected(displayId)) {
1245 return;
1246 }
1247
1248 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001249 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001250
Ana Krulece588e312018-09-18 12:32:24 -07001251 if (mUseScheduler) {
1252 mScheduler->setVsyncPeriod(period);
1253 } else {
1254 mPrimaryDispSync->reset();
1255 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001256
Ana Krulece588e312018-09-18 12:32:24 -07001257 if (!mPrimaryHWVsyncEnabled) {
1258 mPrimaryDispSync->beginResync();
1259 mEventControlThread->setVsyncEnabled(true);
1260 mPrimaryHWVsyncEnabled = true;
1261 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001262 }
1263}
1264
Jesse Hall948fe0c2013-10-14 12:56:09 -07001265void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001266 Mutex::Autolock _l(mHWVsyncLock);
1267 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001268 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001269 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001270 mPrimaryHWVsyncEnabled = false;
1271 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001272 if (makeUnavailable) {
1273 mHWVsyncAvailable = false;
1274 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001275}
1276
Tim Murray4a4e4a22016-04-19 16:29:23 +00001277void SurfaceFlinger::resyncWithRateLimit() {
1278 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001279
1280 // No explicit locking is needed here since EventThread holds a lock while calling this method
1281 static nsecs_t sLastResyncAttempted = 0;
1282 const nsecs_t now = systemTime();
1283 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001284 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001285 }
Dan Stoza57164302017-05-08 14:03:54 -07001286 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001287}
1288
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001289void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1290 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001291 ATRACE_NAME("SF onVsync");
1292
Steven Thomas3cfac282017-02-06 12:29:30 -08001293 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001294 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001295 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001296 return;
1297 }
1298
1299 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001300 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001301 return;
1302 }
1303
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001304 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1305 // For now, we don't do anything with external display vsyncs.
1306 return;
1307 }
1308
Ana Krulece588e312018-09-18 12:32:24 -07001309 if (mUseScheduler) {
1310 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001311 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001312 bool needsHwVsync = false;
1313 { // Scope for the lock
1314 Mutex::Autolock _l(mHWVsyncLock);
1315 if (mPrimaryHWVsyncEnabled) {
1316 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1317 }
1318 }
1319
1320 if (needsHwVsync) {
1321 enableHardwareVsync();
1322 } else {
1323 disableHardwareVsync(false);
1324 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001325 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001326}
1327
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001328void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001329 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1330 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001331}
1332
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001333void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001334 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001335 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001336 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001337
Lloyd Piqueba04e622017-12-14 17:11:26 -08001338 // Ignore events that do not have the right sequenceId.
1339 if (sequenceId != getBE().mComposerSequenceId) {
1340 return;
1341 }
1342
Steven Thomasb02664d2017-07-26 18:48:28 -07001343 // Only lock if we're not on the main thread. This function is normally
1344 // called on a hwbinder thread, but for the primary display it's called on
1345 // the main thread with the state lock already held, so don't attempt to
1346 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001347 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001348
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001349 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001350
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001351 if (std::this_thread::get_id() == mMainThreadId) {
1352 // Process all pending hot plug events immediately if we are on the main thread.
1353 processDisplayHotplugEventsLocked();
1354 }
1355
Lloyd Piqueba04e622017-12-14 17:11:26 -08001356 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001357}
1358
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001359void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001360 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001361 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001362 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001363 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001364 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001365}
1366
Dan Stoza9e56aa02015-11-02 13:00:03 -08001367void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001368 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001369 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001370 getHwComposer().setVsyncEnabled(disp,
1371 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001372}
1373
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001374// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001375void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001376 if (mUseScheduler) {
1377 mScheduler->disableHardwareVsync(true);
1378 } else {
1379 disableHardwareVsync(true);
1380 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001381 // Clear the drawing state so that the logic inside of
1382 // handleTransactionLocked will fire. It will determine the delta between
1383 // mCurrentState and mDrawingState and re-apply all changes when we make the
1384 // transition.
1385 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001386 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001387 mDisplays.clear();
1388}
1389
Steven Thomas050b2c82017-03-06 11:45:16 -08001390void SurfaceFlinger::updateVrFlinger() {
1391 if (!mVrFlinger)
1392 return;
1393 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001394 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001395 return;
1396 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001397
David Sodman105b7dc2017-11-04 20:28:14 -07001398 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001399 ALOGE("Vr flinger is only supported for remote hardware composer"
1400 " service connections. Ignoring request to transition to vr"
1401 " flinger.");
1402 mVrFlingerRequestsDisplay = false;
1403 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001404 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001405
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001406 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001407
Steven Thomas0123ac62018-07-12 11:32:34 -07001408 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001409 LOG_ALWAYS_FATAL_IF(!display);
1410 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001411 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1412 // called below. Clear the reference now so we don't accidentally use it
1413 // later.
1414 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001415
Steven Thomasb02664d2017-07-26 18:48:28 -07001416 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001417 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001418 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001419
Steven Thomasb02664d2017-07-26 18:48:28 -07001420 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001421 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001422 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1423 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001424 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001425
David Sodman105b7dc2017-11-04 20:28:14 -07001426 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1427 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001428
1429 if (vrFlingerRequestsDisplay) {
1430 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001431 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001432
1433 mVisibleRegionsDirty = true;
1434 invalidateHwcGeometry();
1435
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001436 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001437 display = getDefaultDisplayDeviceLocked();
1438 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001439 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001440
Steven Thomasb02664d2017-07-26 18:48:28 -07001441 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001442 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001443 const nsecs_t period = activeConfig->getVsyncPeriod();
1444 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001445
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001446 // The present fences returned from vr_hwc are not an accurate
1447 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001448 if (mUseScheduler) {
1449 mScheduler->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() || !hasSyncFramework);
1450 } else {
1451 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1452 !hasSyncFramework);
1453 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001454
Steven Thomasb02664d2017-07-26 18:48:28 -07001455 // Use phase of 0 since phase is not known.
1456 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001457 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1458 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001459
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001460 resyncToHardwareVsync(false);
1461
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001462 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001463 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001464}
1465
Mathias Agopian4fec8732012-06-29 14:12:52 -07001466void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001467 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001468 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001469 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001470 bool frameMissed = !mHadClientComposition &&
1471 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001472 (mPreviousPresentFence->getSignalTime() ==
1473 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001474 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001475 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001476 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001477 mTimeStats.incrementMissedFrames();
1478 if (mPropagateBackpressure) {
1479 signalLayerUpdate();
1480 break;
1481 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001482 }
Dan Stoza50182882016-07-08 12:02:20 -07001483
Steven Thomas050b2c82017-03-06 11:45:16 -08001484 // Now that we're going to make it to the handleMessageTransaction()
1485 // call below it's safe to call updateVrFlinger(), which will
1486 // potentially trigger a display handoff.
1487 updateVrFlinger();
1488
Dan Stoza6b9454d2014-11-07 16:00:59 -08001489 bool refreshNeeded = handleMessageTransaction();
1490 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001491 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001492 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001493 // Signal a refresh if a transaction modified the window state,
1494 // a new buffer was latched, or if HWC has requested a full
1495 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001496 signalRefresh();
1497 }
1498 break;
1499 }
1500 case MessageQueue::REFRESH: {
1501 handleMessageRefresh();
1502 break;
1503 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001504 }
1505}
1506
Dan Stoza6b9454d2014-11-07 16:00:59 -08001507bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001508 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001509 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001510 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001511 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001512 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001513 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001514}
1515
Mathias Agopian4fec8732012-06-29 14:12:52 -07001516void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001517 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001518
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001519 mRefreshPending = false;
1520
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001521 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001522 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001523 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001524 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001525 for (const auto& [token, display] : mDisplays) {
1526 beginFrame(display);
1527 prepareFrame(display);
1528 doDebugFlashRegions(display, repaintEverything);
1529 doComposition(display, repaintEverything);
1530 }
1531
Adrian Roos1e1a1282017-11-01 19:05:31 +01001532 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001533 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001534
1535 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001536 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001537
Dan Stozabfbffeb2016-07-21 14:49:33 -07001538 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001539 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001540 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001541 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001542 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001543
Alec Mouri86770e52018-09-24 22:40:58 +00001544 // Setup RenderEngine sync fences if native sync is supported.
1545 if (getBE().mRenderEngine->useNativeFenceSync()) {
1546 if (mHadClientComposition) {
1547 base::unique_fd flushFence(getRenderEngine().flush());
1548 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1549 getBE().flushFence = new Fence(std::move(flushFence));
1550 } else {
1551 // Cleanup for hygiene.
1552 getBE().flushFence = Fence::NO_FENCE;
1553 }
1554 }
1555
Jorim Jaggi90535212018-05-23 23:44:06 +02001556 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001557
David Sodman7e4ae112018-02-09 15:02:28 -08001558 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001559 for (const auto& [token, display] : mDisplays) {
1560 const auto displayId = display->getId();
David Sodman7e4ae112018-02-09 15:02:28 -08001561 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[displayId]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001562 compositionInfo.hwc.hwcLayer = nullptr;
1563 }
David Sodmanba340492018-08-05 21:51:33 -07001564 }
David Sodman7e4ae112018-02-09 15:02:28 -08001565
1566 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001567}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001568
David Sodmanfa9b2af2017-12-24 13:28:59 -08001569
1570bool SurfaceFlinger::handleMessageInvalidate() {
1571 ATRACE_CALL();
1572 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001573}
1574
David Sodman79bba0e2018-08-05 18:07:49 -07001575void SurfaceFlinger::calculateWorkingSet() {
1576 ATRACE_CALL();
1577 ALOGV(__FUNCTION__);
1578
David Sodman79bba0e2018-08-05 18:07:49 -07001579 // build the h/w work list
1580 if (CC_UNLIKELY(mGeometryInvalid)) {
1581 mGeometryInvalid = false;
1582 for (const auto& [token, display] : mDisplays) {
1583 const auto displayId = display->getId();
1584 if (displayId >= 0) {
1585 const Vector<sp<Layer>>& currentLayers(
1586 display->getVisibleLayersSortedByZ());
1587 for (size_t i = 0; i < currentLayers.size(); i++) {
1588 const auto& layer = currentLayers[i];
1589
1590 if (!layer->hasHwcLayer(displayId)) {
1591 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1592 layer->forceClientComposition(displayId);
1593 continue;
1594 }
1595 }
1596
1597 layer->setGeometry(display, i);
1598 if (mDebugDisableHWC || mDebugRegion) {
1599 layer->forceClientComposition(displayId);
1600 }
1601 }
1602 }
1603 }
1604 }
1605
1606 // Set the per-frame data
1607 for (const auto& [token, display] : mDisplays) {
1608 const auto displayId = display->getId();
1609 if (displayId < 0) {
1610 continue;
1611 }
1612
1613 if (mDrawingState.colorMatrixChanged) {
1614 display->setColorTransform(mDrawingState.colorMatrix);
1615 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1616 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1617 "display %d: %d", displayId, result);
1618 }
1619 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1620 if (layer->isHdrY410()) {
1621 layer->forceClientComposition(displayId);
1622 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1623 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1624 !display->hasHDR10Support()) {
1625 layer->forceClientComposition(displayId);
1626 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1627 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1628 !display->hasHLGSupport()) {
1629 layer->forceClientComposition(displayId);
1630 }
1631
Peiyong Lind3788632018-09-18 16:01:31 -07001632 // TODO(b/111562338) remove when composer 2.3 is shipped.
1633 if (layer->hasColorTransform()) {
1634 layer->forceClientComposition(displayId);
1635 }
1636
David Sodman79bba0e2018-08-05 18:07:49 -07001637 if (layer->getForceClientComposition(displayId)) {
1638 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1639 layer->setCompositionType(displayId, HWC2::Composition::Client);
1640 continue;
1641 }
1642
1643 layer->setPerFrameData(display);
1644 }
1645
Peiyong Lin13effd12018-07-24 17:01:47 -07001646 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001647 ColorMode colorMode;
1648 Dataspace dataSpace;
1649 RenderIntent renderIntent;
1650 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1651 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1652 }
1653 }
1654
1655 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001656
1657 for (const auto& [token, display] : mDisplays) {
David Sodman15fb96e2018-01-07 10:23:24 -08001658 const auto displayId = display->getId();
1659 getBE().mCompositionInfo[displayId].clear();
David Sodmanba340492018-08-05 21:51:33 -07001660 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1661 auto displayId = display->getId();
1662 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1663 if (!layer->setHwcLayer(displayId)) {
1664 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1665 }
David Sodman15fb96e2018-01-07 10:23:24 -08001666 layer->getBE().compositionInfo.hwc.displayId = displayId;
1667 getBE().mCompositionInfo[displayId].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001668 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1669 }
1670 }
David Sodman79bba0e2018-08-05 18:07:49 -07001671}
1672
David Sodmanfa9b2af2017-12-24 13:28:59 -08001673void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001674{
David Sodmanfb95bcc2017-12-22 15:45:30 -08001675 const auto displayId = display->getId();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001676 // is debugging enabled
1677 if (CC_LIKELY(!mDebugRegion))
1678 return;
1679
David Sodmanfa9b2af2017-12-24 13:28:59 -08001680 if (display->isPoweredOn()) {
1681 // transform the dirty region into this screen's coordinate space
1682 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1683 if (!dirtyRegion.isEmpty()) {
1684 // redraw the whole screen
1685 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001686
David Sodmanfa9b2af2017-12-24 13:28:59 -08001687 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001688 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001689 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001690
David Sodmanfa9b2af2017-12-24 13:28:59 -08001691 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001692 }
1693 }
1694
David Sodmanfa9b2af2017-12-24 13:28:59 -08001695 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001696
1697 if (mDebugRegion > 1) {
1698 usleep(mDebugRegion * 1000);
1699 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001700
David Sodmanfa9b2af2017-12-24 13:28:59 -08001701 if (display->isPoweredOn()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08001702 status_t result = display->prepareFrame(
1703 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001704 ALOGE_IF(result != NO_ERROR,
1705 "prepareFrame for display %d failed:"
1706 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001707 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001708 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001709}
1710
Adrian Roos1e1a1282017-11-01 19:05:31 +01001711void SurfaceFlinger::doTracing(const char* where) {
1712 ATRACE_CALL();
1713 ATRACE_NAME(where);
1714 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001715 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001716 }
1717}
1718
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001719void SurfaceFlinger::logLayerStats() {
1720 ATRACE_CALL();
1721 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001722 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001723 if (display->isPrimary()) {
1724 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001725 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001726 }
1727 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001728
1729 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001730 }
1731}
1732
David Sodman2b406362017-12-15 13:33:47 -08001733void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001734{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001735 ATRACE_CALL();
1736 ALOGV("preComposition");
1737
David Sodman2b406362017-12-15 13:33:47 -08001738 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1739
Mathias Agopiancd60f992012-08-16 16:28:27 -07001740 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001741 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001742 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001743 needExtraInvalidate = true;
1744 }
Robert Carr2047fae2016-11-28 14:09:09 -08001745 });
1746
Mathias Agopiancd60f992012-08-16 16:28:27 -07001747 if (needExtraInvalidate) {
1748 signalLayerUpdate();
1749 }
1750}
1751
Ana Krulece588e312018-09-18 12:32:24 -07001752void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1753 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001754 // Update queue of past composite+present times and determine the
1755 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001756 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001757 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001758 while (!getBE().mCompositePresentTimes.empty()) {
1759 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001760 // Cached values should have been updated before calling this method,
1761 // which helps avoid duplicate syscalls.
1762 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1763 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1764 break;
1765 }
1766 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001767 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001768 }
1769
1770 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001771 while (getBE().mCompositePresentTimes.size() > 16) {
1772 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001773 }
1774
Ana Krulece588e312018-09-18 12:32:24 -07001775 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001776}
1777
Ana Krulece588e312018-09-18 12:32:24 -07001778void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1779 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001780 // Integer division and modulo round toward 0 not -inf, so we need to
1781 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001782 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1783 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1784 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001785
Brian Andersond0010582017-03-07 13:20:31 -08001786 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1787 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001788 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001789 }
1790
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001791 // Snap the latency to a value that removes scheduling jitter from the
1792 // composition and present times, which often have >1ms of jitter.
1793 // Reducing jitter is important if an app attempts to extrapolate
1794 // something (such as user input) to an accurate diasplay time.
1795 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1796 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001797 nsecs_t bias = stats.vsyncPeriod / 2;
1798 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1799 nsecs_t snappedCompositeToPresentLatency =
1800 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001801
David Sodman99974d22017-11-28 12:04:33 -08001802 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001803 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1804 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001805 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001806}
1807
David Sodman2b406362017-12-15 13:33:47 -08001808void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001809{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001810 ATRACE_CALL();
1811 ALOGV("postComposition");
1812
Brian Anderson3546a3f2016-07-14 11:51:14 -07001813 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001814 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001815 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001816 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001817 }
1818
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001819 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001820 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001821
David Sodman73beded2017-11-15 11:56:06 -08001822 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001823 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001824 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001825 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001826 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001827 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001828 } else {
1829 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1830 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001831
David Sodman73beded2017-11-15 11:56:06 -08001832 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001833 mPreviousPresentFence =
1834 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1835 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001836 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001837
Ana Krulece588e312018-09-18 12:32:24 -07001838 DisplayStatInfo stats;
1839 if (mUseScheduler) {
1840 mScheduler->getDisplayStatInfo(&stats);
1841 } else {
1842 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1843 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
1844 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001845
David Sodman2b406362017-12-15 13:33:47 -08001846 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001847 // when we started doing work for this frame, but that should be okay
1848 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07001849 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001850 CompositorTiming compositorTiming;
1851 {
David Sodman99974d22017-11-28 12:04:33 -08001852 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1853 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001854 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001855
Robert Carr2047fae2016-11-28 14:09:09 -08001856 mDrawingState.traverseInZOrder([&](Layer* layer) {
1857 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001858 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001859 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001860 recordBufferingStats(layer->getName().string(),
1861 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001862 }
Robert Carr2047fae2016-11-28 14:09:09 -08001863 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001864
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001865 if (presentFenceTime->isValid()) {
Ana Krulece588e312018-09-18 12:32:24 -07001866 if (mUseScheduler) {
1867 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001868 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001869 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
1870 enableHardwareVsync();
1871 } else {
1872 disableHardwareVsync(false);
1873 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001874 }
1875 }
1876
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001877 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001878 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07001879 if (mUseScheduler) {
1880 mScheduler->enableHardwareVsync();
1881 } else {
1882 enableHardwareVsync();
1883 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001884 }
1885 }
1886
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001887 if (mAnimCompositionPending) {
1888 mAnimCompositionPending = false;
1889
Brian Anderson4e606e32017-03-16 15:34:57 -07001890 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001891 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001892 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001893 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001894 // The HWC doesn't support present fences, so use the refresh
1895 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001896 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001897 mAnimFrameTracker.setActualPresentTime(presentTime);
1898 }
1899 mAnimFrameTracker.advanceFrame();
1900 }
Dan Stozab90cf072015-03-05 11:05:59 -08001901
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001902 mTimeStats.incrementTotalFrames();
1903 if (mHadClientComposition) {
1904 mTimeStats.incrementClientCompositionFrames();
1905 }
1906
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001907 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001908 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001909 return;
1910 }
1911
1912 nsecs_t currentTime = systemTime();
1913 if (mHasPoweredOff) {
1914 mHasPoweredOff = false;
1915 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001916 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001917 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001918 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1919 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001920 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001921 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001922 }
David Sodman4a36e932017-11-07 14:29:47 -08001923 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001924 }
David Sodman4a36e932017-11-07 14:29:47 -08001925 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001926
1927 {
1928 std::lock_guard lock(mTexturePoolMutex);
1929 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1930 if (refillCount > 0) {
1931 const size_t offset = mTexturePool.size();
1932 mTexturePool.resize(mTexturePoolSize);
1933 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1934 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1935 }
1936 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001937}
1938
1939void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001940 ATRACE_CALL();
1941 ALOGV("rebuildLayerStacks");
1942
Mathias Agopiancd60f992012-08-16 16:28:27 -07001943 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001944 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001945 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001946 mVisibleRegionsDirty = false;
1947 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001948
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001949 for (const auto& pair : mDisplays) {
1950 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001951 Region opaqueRegion;
1952 Region dirtyRegion;
1953 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001954 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001955 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001956 const Rect bounds = display->getBounds();
1957 if (display->isPoweredOn()) {
1958 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001959
Jeff Sharkey76488112017-02-27 14:15:18 -07001960 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001961 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001962 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001963 Region drawRegion(tr.transform(
1964 layer->visibleNonTransparentRegion));
1965 drawRegion.andSelf(bounds);
1966 if (!drawRegion.isEmpty()) {
1967 layersSortedByZ.add(layer);
1968 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001969 // Clear out the HWC layer if this layer was
1970 // previously visible, but no longer is
1971 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001972 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001973 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001974 // WM changes display->layerStack upon sleep/awake.
1975 // Here we make sure we delete the HWC layers even if
1976 // WM changed their layer stack.
1977 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001978 }
1979
1980 // If a layer is not going to get a release fence because
1981 // it is invisible, but it is also going to release its
1982 // old buffer, add it to the list of layers needing
1983 // fences.
1984 if (hwcLayerDestroyed) {
1985 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1986 mLayersWithQueuedFrames.cend(), layer);
1987 if (found != mLayersWithQueuedFrames.cend()) {
1988 layersNeedingFences.add(layer);
1989 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001990 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001991 });
1992 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001993 display->setVisibleLayersSortedByZ(layersSortedByZ);
1994 display->setLayersNeedingFences(layersNeedingFences);
1995 display->undefinedRegion.set(bounds);
1996 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1997 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001998 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001999 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002000}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002001
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002002// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002003// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002004// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002005// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002006// The returned HDR data space is one of
2007// - Dataspace::UNKNOWN
2008// - Dataspace::BT2020_HLG
2009// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002010Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2011 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07002012 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002013 *outHdrDataSpace = Dataspace::UNKNOWN;
2014
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002015 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002016 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002017 case Dataspace::V0_SCRGB:
2018 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002019 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002020 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002021 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002022 case Dataspace::BT2020_PQ:
2023 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002024 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002025 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002026 case Dataspace::BT2020_HLG:
2027 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002028 // When there's mixed PQ content and HLG content, we set the HDR
2029 // data space to be BT2020_PQ and convert HLG to PQ.
2030 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2031 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002032 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002033 break;
2034 default:
2035 break;
2036 }
Romain Guy54f154a2017-10-24 21:40:32 +01002037 }
2038
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002039 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002040}
2041
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002042// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002043void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2044 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002045 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2046 *outMode = ColorMode::NATIVE;
2047 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002048 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002049 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002050 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002051
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002052 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002053 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002054
Peiyong Lindfde5112018-06-05 10:58:41 -07002055 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002056 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002057 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002058 if (isHdr) {
2059 bestDataSpace = hdrDataSpace;
2060 }
2061
Chia-I Wu0d711262018-05-21 15:19:35 -07002062 RenderIntent intent;
2063 switch (mDisplayColorSetting) {
2064 case DisplayColorSetting::MANAGED:
2065 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002066 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002067 break;
2068 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002069 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002070 break;
2071 default: // vendor display color setting
2072 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2073 break;
2074 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002075
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002076 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002077}
2078
David Sodmanfa9b2af2017-12-24 13:28:59 -08002079void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002080{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002081 bool dirty = !display->getDirtyRegion(false).isEmpty();
2082 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2083 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002084
David Sodmanfa9b2af2017-12-24 13:28:59 -08002085 // If nothing has changed (!dirty), don't recompose.
2086 // If something changed, but we don't currently have any visible layers,
2087 // and didn't when we last did a composition, then skip it this time.
2088 // The second rule does two things:
2089 // - When all layers are removed from a display, we'll emit one black
2090 // frame, then nothing more until we get new layers.
2091 // - When a display is created with a private layer stack, we won't
2092 // emit any black frames until a layer is added to the layer stack.
2093 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002094
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002095 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2096 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002097 mustRecompose ? "doing" : "skipping",
2098 dirty ? "+" : "-",
2099 empty ? "+" : "-",
2100 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002101
David Sodmanfa9b2af2017-12-24 13:28:59 -08002102 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002103
David Sodmanfa9b2af2017-12-24 13:28:59 -08002104 if (mustRecompose) {
2105 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002106 }
2107}
2108
David Sodmanfa9b2af2017-12-24 13:28:59 -08002109void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002110{
David Sodmanfb95bcc2017-12-22 15:45:30 -08002111 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002112 if (!display->isPoweredOn()) {
2113 return;
David Sodman2b406362017-12-15 13:33:47 -08002114 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002115
David Sodmanfb95bcc2017-12-22 15:45:30 -08002116 status_t result = display->prepareFrame(
2117 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08002118 ALOGE_IF(result != NO_ERROR,
2119 "prepareFrame for display %d failed:"
2120 " %d (%s)",
2121 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002122}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002123
David Sodmanfa9b2af2017-12-24 13:28:59 -08002124void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002125 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002126 ALOGV("doComposition");
2127
David Sodmanfa9b2af2017-12-24 13:28:59 -08002128 if (display->isPoweredOn()) {
2129 // transform the dirty region into this screen's coordinate space
2130 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002131
David Sodmanfa9b2af2017-12-24 13:28:59 -08002132 // repaint the framebuffer (if needed)
2133 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002134
David Sodmanfa9b2af2017-12-24 13:28:59 -08002135 display->dirtyRegion.clear();
2136 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002137 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002138 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002139}
2140
David Sodmanfa9b2af2017-12-24 13:28:59 -08002141void SurfaceFlinger::postFrame()
2142{
2143 // |mStateLock| not needed as we are on the main thread
2144 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2145 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2146 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2147 logFrameStats();
2148 }
2149 }
2150}
2151
2152void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002153{
Mathias Agopian841cde52012-03-01 15:44:37 -08002154 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002155 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002156
David Sodmanfa9b2af2017-12-24 13:28:59 -08002157 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002158
David Sodmanfa9b2af2017-12-24 13:28:59 -08002159 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002160 const auto displayId = display->getId();
2161 if (displayId >= 0) {
2162 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002163 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002164 display->onSwapBuffersCompleted();
2165 display->makeCurrent();
David Sodman15094112018-10-11 09:39:37 -07002166 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002167 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002168
Chia-I Wu7b549592017-11-15 09:14:57 -08002169 // The layer buffer from the previous frame (if any) is released
2170 // by HWC only when the release fence from this frame (if any) is
2171 // signaled. Always get the release fence from HWC first.
David Sodman15094112018-10-11 09:39:37 -07002172 auto hwcLayer = layer->getHwcLayer(displayId);
2173 if (displayId >= 0) {
2174 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002175 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002176
2177 // If the layer was client composited in the previous frame, we
2178 // need to merge with the previous client target acquire fence.
2179 // Since we do not track that, always merge with the current
2180 // client target acquire fence when it is available, even though
2181 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002182 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002183 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002184 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002185 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002186
David Sodman15094112018-10-11 09:39:37 -07002187 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002188 }
Chia-I Wu83806892017-11-16 10:50:20 -08002189
2190 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002191 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002192 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002193 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002194 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002195 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002196 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002197 }
2198 }
2199
Dominik Laskowski7e045462018-05-30 13:02:02 -07002200 if (displayId >= 0) {
2201 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002202 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002203 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002204}
2205
Mathias Agopian87baae12012-07-31 12:38:26 -07002206void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002207{
Mathias Agopian841cde52012-03-01 15:44:37 -08002208 ATRACE_CALL();
2209
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002210 // here we keep a copy of the drawing state (that is the state that's
2211 // going to be overwritten by handleTransactionLocked()) outside of
2212 // mStateLock so that the side-effects of the State assignment
2213 // don't happen with mStateLock held (which can cause deadlocks).
2214 State drawingState(mDrawingState);
2215
Mathias Agopianca4d3602011-05-19 15:38:14 -07002216 Mutex::Autolock _l(mStateLock);
2217 const nsecs_t now = systemTime();
2218 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002219
Mathias Agopianca4d3602011-05-19 15:38:14 -07002220 // Here we're guaranteed that some transaction flags are set
2221 // so we can call handleTransactionLocked() unconditionally.
2222 // We call getTransactionFlags(), which will also clear the flags,
2223 // with mStateLock held to guarantee that mCurrentState won't change
2224 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002225
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002226 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002227 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002228 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002229
Mathias Agopianca4d3602011-05-19 15:38:14 -07002230 mLastTransactionTime = systemTime() - now;
2231 mDebugInTransaction = 0;
2232 invalidateHwcGeometry();
2233 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002234}
2235
Dominik Laskowski7e045462018-05-30 13:02:02 -07002236DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002237 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002238 // Figure out whether the event is for the primary display or an
2239 // external display by matching the Hwc display id against one for a
2240 // connected display. If we did not find a match, we then check what
2241 // displays are not already connected to determine the type. If we don't
2242 // have a connected primary display, we assume the new display is meant to
2243 // be the primary display, and then if we don't have an external display,
2244 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002245 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2246 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002247 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002248 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002249 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002250 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002251 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002252 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002253 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002254 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002255 return DisplayDevice::DISPLAY_EXTERNAL;
2256 }
2257
2258 return DisplayDevice::DISPLAY_ID_INVALID;
2259}
2260
Lloyd Piqueba04e622017-12-14 17:11:26 -08002261void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2262 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002263 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002264 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002265 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002266 continue;
2267 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002268
2269 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2270 ALOGE("External displays are not supported by the vr hardware composer.");
2271 continue;
2272 }
2273
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002274 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002275 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002276 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002277 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002278 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002279
2280 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002281 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002282 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002283 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002284 DisplayDeviceState info;
2285 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002286 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2287 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002288 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002289 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002290 mInterceptor->saveDisplayCreation(info);
2291 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002292 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002293 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002294
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002295 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002296 if (idx >= 0) {
2297 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002298 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002299 mCurrentState.displays.removeItemsAt(idx);
2300 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002301 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002302 }
2303
2304 processDisplayChangesLocked();
2305 }
2306
2307 mPendingHotplugEvents.clear();
2308}
2309
Lloyd Pique99d3da52018-01-22 17:48:03 -08002310sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002311 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002312 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002313 DisplayDeviceCreationArgs creationArgs(this, displayToken, state.type, displayId);
2314 creationArgs.isSecure = state.isSecure;
2315 creationArgs.displaySurface = dispSurface;
2316 creationArgs.hasWideColorGamut = false;
2317 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002318
Peiyong Lin13effd12018-07-24 17:01:47 -07002319 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002320 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002321 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002322 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002323 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002324 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002325
Dominik Laskowski7e045462018-05-30 13:02:02 -07002326 std::vector<RenderIntent> renderIntents =
2327 getHwComposer().getRenderIntents(displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002328 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002329 }
tangrobin6753a022018-08-10 10:58:54 +08002330 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002331
tangrobin6753a022018-08-10 10:58:54 +08002332 if (displayId >= 0) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002333 getHwComposer().getHdrCapabilities(displayId, &creationArgs.hdrCapabilities);
2334 creationArgs.supportedPerFrameMetadata =
2335 getHwComposer().getSupportedPerFrameMetadata(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002336 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002337
2338 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2339 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002340 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002341
2342 /*
2343 * Create our display's surface
2344 */
Peiyong Lin833074a2018-08-28 11:53:54 -07002345 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002346 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002347 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002348 renderSurface->setNativeWindow(nativeWindow.get());
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002349 creationArgs.displayWidth = renderSurface->getWidth();
2350 creationArgs.displayHeight = renderSurface->getHeight();
2351 creationArgs.renderSurface = std::move(renderSurface);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002352
2353 // Make sure that composition can never be stalled by a virtual display
2354 // consumer that isn't processing buffers fast enough. We have to do this
2355 // in two places:
2356 // * Here, in case the display is composed entirely by HWC.
2357 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2358 // window's swap interval in eglMakeCurrent, so they'll override the
2359 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002360 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002361 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2362 }
2363
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002364 creationArgs.displayInstallOrientation = state.type == DisplayDevice::DISPLAY_PRIMARY
2365 ? primaryDisplayOrientation
2366 : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002367
Lloyd Pique99d3da52018-01-22 17:48:03 -08002368 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002369 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002370
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002371 sp<DisplayDevice> display = new DisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002372
2373 if (maxFrameBufferAcquiredBuffers >= 3) {
2374 nativeWindowSurface->preallocateBuffers();
2375 }
2376
2377 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002378 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002379 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002380 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002381 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002382 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002383 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002384 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002385 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002386 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002387 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002388 display->setLayerStack(state.layerStack);
2389 display->setProjection(state.orientation, state.viewport, state.frame);
2390 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002391
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002392 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002393}
2394
Lloyd Pique347200f2017-12-14 17:00:15 -08002395void SurfaceFlinger::processDisplayChangesLocked() {
2396 // here we take advantage of Vector's copy-on-write semantics to
2397 // improve performance by skipping the transaction entirely when
2398 // know that the lists are identical
2399 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2400 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2401 if (!curr.isIdenticalTo(draw)) {
2402 mVisibleRegionsDirty = true;
2403 const size_t cc = curr.size();
2404 size_t dc = draw.size();
2405
2406 // find the displays that were removed
2407 // (ie: in drawing state but not in current state)
2408 // also handle displays that changed
2409 // (ie: displays that are in both lists)
2410 for (size_t i = 0; i < dc;) {
2411 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2412 if (j < 0) {
2413 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002414 // Call makeCurrent() on the primary display so we can
2415 // be sure that nothing associated with this display
2416 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002417 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2418 defaultDisplay->makeCurrent();
2419 }
2420 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2421 display->disconnect(getHwComposer());
2422 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002423 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002424 if (mUseScheduler) {
2425 mScheduler->hotplugReceived(mAppConnectionHandle,
2426 EventThread::DisplayType::Primary, false);
2427 } else {
2428 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2429 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002430 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002431 if (mUseScheduler) {
2432 mScheduler->hotplugReceived(mAppConnectionHandle,
2433 EventThread::DisplayType::External, false);
2434 } else {
2435 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2436 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002437 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002438 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002439 } else {
2440 // this display is in both lists. see if something changed.
2441 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002442 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002443 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2444 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2445 if (state_binder != draw_binder) {
2446 // changing the surface is like destroying and
2447 // recreating the DisplayDevice, so we just remove it
2448 // from the drawing state, so that it get re-added
2449 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002450 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2451 display->disconnect(getHwComposer());
2452 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002453 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002454 mDrawingState.displays.removeItemsAt(i);
2455 dc--;
2456 // at this point we must loop to the next item
2457 continue;
2458 }
2459
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002460 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002461 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002462 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002463 }
2464 if ((state.orientation != draw[i].orientation) ||
2465 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002466 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002467 }
2468 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002469 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002470 }
2471 }
2472 }
2473 ++i;
2474 }
2475
2476 // find displays that were added
2477 // (ie: in current state but not in drawing state)
2478 for (size_t i = 0; i < cc; i++) {
2479 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2480 const DisplayDeviceState& state(curr[i]);
2481
2482 sp<DisplaySurface> dispSurface;
2483 sp<IGraphicBufferProducer> producer;
2484 sp<IGraphicBufferProducer> bqProducer;
2485 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002486 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002487
Dominik Laskowski7e045462018-05-30 13:02:02 -07002488 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002489 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002490 // Virtual displays without a surface are dormant:
2491 // they have external state (layer stack, projection,
2492 // etc.) but no internal state (i.e. a DisplayDevice).
2493 if (state.surface != nullptr) {
2494 // Allow VR composer to use virtual displays.
2495 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2496 int width = 0;
2497 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2498 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2499 int height = 0;
2500 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2501 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2502 int intFormat = 0;
2503 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2504 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002505 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002506
Dominik Laskowski7e045462018-05-30 13:02:02 -07002507 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2508 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002509 }
2510
2511 // TODO: Plumb requested format back up to consumer
2512
2513 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002514 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002515 bqProducer, bqConsumer,
2516 state.displayName);
2517
2518 dispSurface = vds;
2519 producer = vds;
2520 }
2521 } else {
2522 ALOGE_IF(state.surface != nullptr,
2523 "adding a supported display, but rendering "
2524 "surface is provided (%p), ignoring it",
2525 state.surface.get());
2526
Dominik Laskowski7e045462018-05-30 13:02:02 -07002527 displayId = state.type;
2528 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002529 producer = bqProducer;
2530 }
2531
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002532 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002533 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002534 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002535 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002536 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002537 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002538 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002539 if (mUseScheduler) {
2540 mScheduler->hotplugReceived(mAppConnectionHandle,
2541 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002542 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002543 } else {
2544 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2545 true);
2546 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002547 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002548 if (mUseScheduler) {
2549 mScheduler->hotplugReceived(mAppConnectionHandle,
2550 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002551 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002552 } else {
2553 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2554 true);
2555 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002556 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002557 }
2558 }
2559 }
2560 }
2561 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002562
2563 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002564}
2565
Mathias Agopian87baae12012-07-31 12:38:26 -07002566void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002567{
Dan Stoza7dde5992015-05-22 09:51:44 -07002568 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002569 mCurrentState.traverseInZOrder([](Layer* layer) {
2570 layer->notifyAvailableFrames();
2571 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002572
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002573 /*
2574 * Traversal of the children
2575 * (perform the transaction for each of them if needed)
2576 */
2577
Mathias Agopian3559b072012-08-15 13:46:03 -07002578 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002579 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002580 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002581 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002582
2583 const uint32_t flags = layer->doTransaction(0);
2584 if (flags & Layer::eVisibleRegion)
2585 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002586 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002587 }
2588
2589 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002590 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002591 */
2592
Mathias Agopiane57f2922012-08-09 16:29:12 -07002593 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002594 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002595 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002596 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002597
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002598 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002599 // The transform hint might have changed for some layers
2600 // (either because a display has changed, or because a layer
2601 // as changed).
2602 //
2603 // Walk through all the layers in currentLayers,
2604 // and update their transform hint.
2605 //
2606 // If a layer is visible only on a single display, then that
2607 // display is used to calculate the hint, otherwise we use the
2608 // default display.
2609 //
2610 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2611 // the hint is set before we acquire a buffer from the surface texture.
2612 //
2613 // NOTE: layer transactions have taken place already, so we use their
2614 // drawing state. However, SurfaceFlinger's own transaction has not
2615 // happened yet, so we must use the current state layer list
2616 // (soon to become the drawing state list).
2617 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002618 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002619 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002620 bool first = true;
2621 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002622 // NOTE: we rely on the fact that layers are sorted by
2623 // layerStack first (so we don't have to traverse the list
2624 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002625 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002626 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002627 currentlayerStack = layerStack;
2628 // figure out if this layerstack is mirrored
2629 // (more than one display) if so, pick the default display,
2630 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002631 hintDisplay = nullptr;
2632 for (const auto& [token, display] : mDisplays) {
2633 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2634 if (hintDisplay) {
2635 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002636 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002637 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002638 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002639 }
2640 }
2641 }
2642 }
Chet Haase91d25932013-04-11 15:24:55 -07002643
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002644 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002645 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2646 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002647
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002648 // could be null when this layer is using a layerStack
2649 // that is not visible on any display. Also can occur at
2650 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002651 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002652 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002653
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002654 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002655 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002656 if (hintDisplay) {
2657 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002658 }
Robert Carr2047fae2016-11-28 14:09:09 -08002659
2660 first = false;
2661 });
Mathias Agopian84300952012-11-21 16:02:13 -08002662 }
2663
2664
Mathias Agopian3559b072012-08-15 13:46:03 -07002665 /*
2666 * Perform our own transaction if needed
2667 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002668
2669 if (mLayersAdded) {
2670 mLayersAdded = false;
2671 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002672 mVisibleRegionsDirty = true;
2673 }
2674
2675 // some layers might have been removed, so
2676 // we need to update the regions they're exposing.
2677 if (mLayersRemoved) {
2678 mLayersRemoved = false;
2679 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002680 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002681 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002682 // this layer is not visible anymore
2683 // TODO: we could traverse the tree from front to back and
2684 // compute the actual visible region
2685 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002686 Region visibleReg;
2687 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002688 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002689 }
Robert Carr2047fae2016-11-28 14:09:09 -08002690 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002691 }
2692
2693 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002694
2695 updateCursorAsync();
2696}
2697
2698void SurfaceFlinger::updateCursorAsync()
2699{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002700 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002701 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002702 continue;
2703 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002704
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002705 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2706 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002707 }
2708 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002709}
2710
2711void SurfaceFlinger::commitTransaction()
2712{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002713 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002714 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002715 for (const auto& l : mLayersPendingRemoval) {
2716 recordBufferingStats(l->getName().string(),
2717 l->getOccupancyHistory(true));
2718 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002719 }
2720 mLayersPendingRemoval.clear();
2721 }
2722
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002723 // If this transaction is part of a window animation then the next frame
2724 // we composite should be considered an animation as well.
2725 mAnimCompositionPending = mAnimTransactionPending;
2726
Mathias Agopian4fec8732012-06-29 14:12:52 -07002727 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002728 // clear the "changed" flags in current state
2729 mCurrentState.colorMatrixChanged = false;
2730
Robert Carr1f0a16a2016-10-24 16:27:39 -07002731 mDrawingState.traverseInZOrder([](Layer* layer) {
2732 layer->commitChildList();
2733 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002734 mTransactionPending = false;
2735 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002736 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002737}
2738
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002739void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2740 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002741 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002742 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002743
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002744 Region aboveOpaqueLayers;
2745 Region aboveCoveredLayers;
2746 Region dirty;
2747
Mathias Agopian87baae12012-07-31 12:38:26 -07002748 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002749
Robert Carr2047fae2016-11-28 14:09:09 -08002750 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002751 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002752 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002753
Jesse Hall01e29052013-02-19 16:13:35 -08002754 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002755 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002756 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002757 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002758
Mathias Agopianab028732010-03-16 16:41:46 -07002759 /*
2760 * opaqueRegion: area of a surface that is fully opaque.
2761 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002762 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002763
2764 /*
2765 * visibleRegion: area of a surface that is visible on screen
2766 * and not fully transparent. This is essentially the layer's
2767 * footprint minus the opaque regions above it.
2768 * Areas covered by a translucent surface are considered visible.
2769 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002770 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002771
2772 /*
2773 * coveredRegion: area of a surface that is covered by all
2774 * visible regions above it (which includes the translucent areas).
2775 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002776 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002777
Jesse Halla8026d22012-09-25 13:25:04 -07002778 /*
2779 * transparentRegion: area of a surface that is hinted to be completely
2780 * transparent. This is only used to tell when the layer has no visible
2781 * non-transparent regions and can be removed from the layer list. It
2782 * does not affect the visibleRegion of this layer or any layers
2783 * beneath it. The hint may not be correct if apps don't respect the
2784 * SurfaceView restrictions (which, sadly, some don't).
2785 */
2786 Region transparentRegion;
2787
Mathias Agopianab028732010-03-16 16:41:46 -07002788
2789 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002790 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002791 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002792 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002793 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002794 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002795 if (!visibleRegion.isEmpty()) {
2796 // Remove the transparent area from the visible region
2797 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002798 if (tr.preserveRects()) {
2799 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002800 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002801 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002802 // transformation too complex, can't do the
2803 // transparent region optimization.
2804 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002805 }
Mathias Agopianab028732010-03-16 16:41:46 -07002806 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002807
Mathias Agopianab028732010-03-16 16:41:46 -07002808 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002809 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002810 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002811 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002812 // the opaque region is the layer's footprint
2813 opaqueRegion = visibleRegion;
2814 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002815 }
2816 }
2817
Robert Carre5f4f692018-01-12 13:12:28 -08002818 if (visibleRegion.isEmpty()) {
2819 layer->clearVisibilityRegions();
2820 return;
2821 }
2822
Mathias Agopianab028732010-03-16 16:41:46 -07002823 // Clip the covered region to the visible region
2824 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2825
2826 // Update aboveCoveredLayers for next (lower) layer
2827 aboveCoveredLayers.orSelf(visibleRegion);
2828
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002829 // subtract the opaque region covered by the layers above us
2830 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002831
2832 // compute this layer's dirty region
2833 if (layer->contentDirty) {
2834 // we need to invalidate the whole region
2835 dirty = visibleRegion;
2836 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002837 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002838 layer->contentDirty = false;
2839 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002840 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002841 * the exposed region consists of two components:
2842 * 1) what's VISIBLE now and was COVERED before
2843 * 2) what's EXPOSED now less what was EXPOSED before
2844 *
2845 * note that (1) is conservative, we start with the whole
2846 * visible region but only keep what used to be covered by
2847 * something -- which mean it may have been exposed.
2848 *
2849 * (2) handles areas that were not covered by anything but got
2850 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002851 */
Mathias Agopianab028732010-03-16 16:41:46 -07002852 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002853 const Region oldVisibleRegion = layer->visibleRegion;
2854 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002855 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2856 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002857 }
2858 dirty.subtractSelf(aboveOpaqueLayers);
2859
2860 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002861 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002862
Mathias Agopianab028732010-03-16 16:41:46 -07002863 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002864 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002865
Jesse Halla8026d22012-09-25 13:25:04 -07002866 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002867 layer->setVisibleRegion(visibleRegion);
2868 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002869 layer->setVisibleNonTransparentRegion(
2870 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002871 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002872
Mathias Agopian87baae12012-07-31 12:38:26 -07002873 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874}
2875
Chia-I Wuab0c3192017-08-01 11:29:00 -07002876void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002877 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002878 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2879 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002880 }
2881 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002882}
2883
Dan Stoza6b9454d2014-11-07 16:00:59 -08002884bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002885{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002886 ALOGV("handlePageFlip");
2887
Brian Andersond6927fb2016-07-23 23:37:30 -07002888 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002889
Mathias Agopian4fec8732012-06-29 14:12:52 -07002890 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002891 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002892 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002893
2894 // Store the set of layers that need updates. This set must not change as
2895 // buffers are being latched, as this could result in a deadlock.
2896 // Example: Two producers share the same command stream and:
2897 // 1.) Layer 0 is latched
2898 // 2.) Layer 0 gets a new frame
2899 // 2.) Layer 1 gets a new frame
2900 // 3.) Layer 1 is latched.
2901 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2902 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002903 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002904 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002905 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002906 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2907 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002908 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002909 } else {
2910 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002911 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002912 } else {
2913 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002914 }
Robert Carr2047fae2016-11-28 14:09:09 -08002915 });
2916
Dan Stoza9e56aa02015-11-02 13:00:03 -08002917 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri86770e52018-09-24 22:40:58 +00002918 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
Dan Stozaee44edd2015-03-23 15:50:23 -07002919 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002920 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002921 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002922 newDataLatched = true;
2923 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002924 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002925
Alec Mouri86770e52018-09-24 22:40:58 +00002926 // Clear the renderengine fence here...
2927 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
2928 // clear instead of sp::clear.
2929 getBE().flushFence = Fence::NO_FENCE;
2930
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002931 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002932
2933 // If we will need to wake up at some time in the future to deal with a
2934 // queued frame that shouldn't be displayed during this vsync period, wake
2935 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002936 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002937 signalLayerUpdate();
2938 }
2939
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002940 // enter boot animation on first buffer latch
2941 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2942 ALOGI("Enter boot animation");
2943 mBootStage = BootStage::BOOTANIMATION;
2944 }
2945
Dan Stoza6b9454d2014-11-07 16:00:59 -08002946 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002947 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002948}
2949
Mathias Agopianad456f92011-01-13 17:53:01 -08002950void SurfaceFlinger::invalidateHwcGeometry()
2951{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002952 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002953}
2954
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002955void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2956 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002957 // We only need to actually compose the display if:
2958 // 1) It is being handled by hardware composer, which may need this to
2959 // keep its virtual display state machine in sync, or
2960 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002961 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002962 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002963 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002964 return;
2965 }
2966
Dan Stoza9e56aa02015-11-02 13:00:03 -08002967 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002968 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002969
2970 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002971 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002972}
2973
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002974bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002975 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002976
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002977 const Region bounds(display->bounds());
2978 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002979 const auto displayId = display->getId();
2980 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002981 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002982
Peiyong Lind3788632018-09-18 16:01:31 -07002983 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002984 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002985 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002986
Dan Stoza9e56aa02015-11-02 13:00:03 -08002987 if (hasClientComposition) {
2988 ALOGV("hasClientComposition");
2989
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002990 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002991 if (display->hasWideColorGamut()) {
2992 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002993 }
2994 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002995 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002996 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002997
Dominik Laskowski7e045462018-05-30 13:02:02 -07002998 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002999 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3000 HWC2::Capability::SkipClientColorTransform);
3001
Peiyong Lind3788632018-09-18 16:01:31 -07003002 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003003 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3004 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003005 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003006 }
3007
Chia-I Wud49d6692018-06-27 07:17:41 +08003008 // The current enhanced saturation matrix is designed to enhance Display P3,
3009 // thus we only apply this matrix when the render intent is not colorimetric
3010 // and the output color space is Display P3.
3011 needsEnhancedColorMatrix =
3012 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3013 outputDataspace == Dataspace::DISPLAY_P3);
3014 if (needsEnhancedColorMatrix) {
3015 colorMatrix *= mEnhancedSaturationMatrix;
3016 }
3017
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003018 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003019 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003020 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003021 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003022
3023 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003024 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3025 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3026 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003027 }
3028 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003029 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003030
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003031 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003032 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003033 // when using overlays, we assume a fully transparent framebuffer
3034 // NOTE: we could reduce how much we need to clear, for instance
3035 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003036 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003037 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003038 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003039 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003040 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003041 // we're left with the letterbox region
3042 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003043 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003044
3045 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003046 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003047
Mathias Agopianb9494d52012-04-18 02:28:45 -07003048 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003049 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003050 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003051 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003052 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003053 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003054
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003055 const Rect& bounds = display->getBounds();
3056 const Rect& scissor = display->getScissor();
3057 if (scissor != bounds) {
3058 // scissor doesn't match the screen's dimensions, so we
3059 // need to clear everything outside of it and enable
3060 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003061
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003062 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003063 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003064 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003065 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003066
Mathias Agopian85d751c2012-08-29 16:59:24 -07003067 /*
3068 * and then, render the layers targeted at the framebuffer
3069 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003070
Dan Stoza9e56aa02015-11-02 13:00:03 -08003071 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003072 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003073 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003074 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003075 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003076 displayTransform.transform(layer->visibleRegion)));
3077 ALOGV("Layer: %s", layer->getName().string());
3078 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003079 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003080 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003081 case HWC2::Composition::Cursor:
3082 case HWC2::Composition::Device:
3083 case HWC2::Composition::Sideband:
3084 case HWC2::Composition::SolidColor: {
David Sodmanc1498e62018-09-12 14:36:26 -07003085 const Layer::State& state(layer->getDrawingState());
3086 if (layer->getClearClientTarget(displayId) && !firstLayer &&
3087 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3088 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003089 // never clear the very first layer since we're
3090 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003091 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003092 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003093 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003094 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003095 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003096 if (layer->hasColorTransform()) {
3097 mat4 tmpMatrix;
3098 if (applyColorMatrix) {
3099 tmpMatrix = mDrawingState.colorMatrix;
3100 }
3101 tmpMatrix *= layer->getColorTransform();
3102 if (needsEnhancedColorMatrix) {
3103 tmpMatrix *= mEnhancedSaturationMatrix;
3104 }
3105 getRenderEngine().setColorTransform(tmpMatrix);
3106 } else {
3107 getRenderEngine().setColorTransform(colorMatrix);
3108 }
David Sodmanc1498e62018-09-12 14:36:26 -07003109 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003110 break;
3111 }
3112 default:
3113 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003114 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003115 } else {
3116 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003117 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003118 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003119 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003120
Peiyong Lind3788632018-09-18 16:01:31 -07003121 // Clear color transform matrix at the end of the frame.
3122 getRenderEngine().setColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003123
Mathias Agopianf45c5102012-10-24 16:29:17 -07003124 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003125 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003126 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003127}
3128
Chia-I Wu28e3a252018-09-07 12:05:02 -07003129void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003130 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003131 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003132}
3133
Dan Stoza7d89d062015-04-30 13:29:25 -07003134status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003135 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003136 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003137 const sp<Layer>& lbc,
3138 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003139{
Dan Stoza7d89d062015-04-30 13:29:25 -07003140 // add this layer to the current state list
3141 {
3142 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003143 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003144 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3145 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003146 return NO_MEMORY;
3147 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003148 if (parent == nullptr) {
3149 mCurrentState.layersSortedByZ.add(lbc);
3150 } else {
Rob Carr4bba3702018-10-08 21:53:30 +00003151 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003152 ALOGE("addClientLayer called with a removed parent");
3153 return NAME_NOT_FOUND;
3154 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003155 parent->addChild(lbc);
3156 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003157
Yiwei Zhang243b3782018-05-15 17:40:04 -07003158 if (gbc != nullptr) {
3159 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3160 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3161 mMaxGraphicBufferProducerListSize,
3162 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3163 mGraphicBufferProducerList.size(),
3164 mMaxGraphicBufferProducerListSize, mNumLayers);
3165 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003166 mLayersAdded = true;
3167 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003168 }
3169
Mathias Agopian96f08192010-06-02 23:28:45 -07003170 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003171 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003172
Dan Stoza7d89d062015-04-30 13:29:25 -07003173 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003174}
3175
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003176status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003177 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003178 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3179}
Robert Carr7f9b8992017-03-10 11:08:39 -08003180
chaviwca27f252018-02-06 16:46:39 -08003181status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3182 bool topLevelOnly) {
Rob Carr4bba3702018-10-08 21:53:30 +00003183 if (layer->isPendingRemoval()) {
chaviw8b3871a2017-11-01 17:41:01 -07003184 return NO_ERROR;
3185 }
3186
Robert Carr1f0a16a2016-10-24 16:27:39 -07003187 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003188 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003189 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003190 if (topLevelOnly) {
3191 return NO_ERROR;
3192 }
Rob Carr4bba3702018-10-08 21:53:30 +00003193
3194 sp<Layer> ancestor = p;
3195 while (ancestor->getParent() != nullptr) {
3196 ancestor = ancestor->getParent();
3197 }
3198 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3199 ALOGE("removeLayer called with a layer whose parent has been removed");
3200 return NAME_NOT_FOUND;
3201 }
3202
Chia-I Wufae51c42017-06-15 12:53:59 -07003203 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003204 } else {
3205 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003206 }
3207
Rob Carr4bba3702018-10-08 21:53:30 +00003208 // As a matter of normal operation, the LayerCleaner will produce a second
3209 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3210 // so we will succeed in promoting it, but it's already been removed
3211 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3212 // otherwise something has gone wrong and we are leaking the layer.
3213 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
3214 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3215 layer->getName().string(),
3216 (p != nullptr) ? p->getName().string() : "no-parent");
3217 return BAD_VALUE;
3218 } else if (index < 0) {
3219 return NO_ERROR;
3220 }
3221
Chia-I Wuc6657022017-08-15 11:18:17 -07003222 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003223 mLayersPendingRemoval.add(layer);
3224 mLayersRemoved = true;
Rob Carr4bba3702018-10-08 21:53:30 +00003225 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003226 setTransactionFlags(eTransactionNeeded);
3227 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003228}
3229
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003230uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003231 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003232}
3233
Mathias Agopian3f844832013-08-07 21:24:32 -07003234uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003235 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003236}
3237
Mathias Agopian3f844832013-08-07 21:24:32 -07003238uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003239 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003240}
3241
3242uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003243 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003244 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003245 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003246 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003247 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003248 }
3249 return old;
3250}
3251
chaviwca27f252018-02-06 16:46:39 -08003252bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3253 for (const ComposerState& state : states) {
3254 // Here we need to check that the interface we're given is indeed
3255 // one of our own. A malicious client could give us a nullptr
3256 // IInterface, or one of its own or even one of our own but a
3257 // different type. All these situations would cause us to crash.
3258 if (state.client == nullptr) {
3259 return true;
3260 }
3261
3262 sp<IBinder> binder = IInterface::asBinder(state.client);
3263 if (binder == nullptr) {
3264 return true;
3265 }
3266
3267 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3268 return true;
3269 }
3270 }
3271 return false;
3272}
3273
Mathias Agopian8b33f032012-07-24 20:43:54 -07003274void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003275 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003276 const Vector<DisplayState>& displays,
3277 uint32_t flags)
3278{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003279 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003280 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003281 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003282
chaviwca27f252018-02-06 16:46:39 -08003283 if (containsAnyInvalidClientState(states)) {
3284 return;
3285 }
3286
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003287 if (flags & eAnimation) {
3288 // For window updates that are part of an animation we must wait for
3289 // previous animation "frames" to be handled.
3290 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003291 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003292 if (CC_UNLIKELY(err != NO_ERROR)) {
3293 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003294 // caller after a few seconds.
3295 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3296 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003297 mAnimTransactionPending = false;
3298 break;
3299 }
3300 }
3301 }
3302
chaviwca27f252018-02-06 16:46:39 -08003303 for (const DisplayState& display : displays) {
3304 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003305 }
3306
chaviwca27f252018-02-06 16:46:39 -08003307 for (const ComposerState& state : states) {
3308 transactionFlags |= setClientStateLocked(state);
3309 }
3310
3311 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3312 // as destroyed should only occur after setting all other states. This is to allow for a
3313 // child re-parent to happen before marking its original parent as destroyed (which would
3314 // then mark the child as destroyed).
3315 for (const ComposerState& state : states) {
3316 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003317 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003318
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003319 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3320 // anyway. This can be used as a flush mechanism for previous async transactions.
3321 // Empty animation transaction can be used to simulate back-pressure, so also force a
3322 // transaction for empty animation transactions.
3323 if (transactionFlags == 0 &&
3324 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003325 transactionFlags = eTransactionNeeded;
3326 }
3327
Mathias Agopian386aa982011-11-07 21:58:03 -08003328 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003329 if (mInterceptor->isEnabled()) {
3330 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003331 }
Irvel468051e2016-06-13 16:44:44 -07003332
Mathias Agopian386aa982011-11-07 21:58:03 -08003333 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003334 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3335 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003336 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003337
3338 // if this is a synchronous transaction, wait for it to take effect
3339 // before returning.
3340 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003341 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003342 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003343 if (flags & eAnimation) {
3344 mAnimTransactionPending = true;
3345 }
3346 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003347 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3348 if (CC_UNLIKELY(err != NO_ERROR)) {
3349 // just in case something goes wrong in SF, return to the
3350 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003351 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3352 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003353 break;
3354 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003355 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003356 }
3357}
3358
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003359uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3360 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3361 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003362
Mathias Agopiane57f2922012-08-09 16:29:12 -07003363 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003364 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3365
3366 const uint32_t what = s.what;
3367 if (what & DisplayState::eSurfaceChanged) {
3368 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3369 state.surface = s.surface;
3370 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003371 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003372 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003373 if (what & DisplayState::eLayerStackChanged) {
3374 if (state.layerStack != s.layerStack) {
3375 state.layerStack = s.layerStack;
3376 flags |= eDisplayTransactionNeeded;
3377 }
3378 }
3379 if (what & DisplayState::eDisplayProjectionChanged) {
3380 if (state.orientation != s.orientation) {
3381 state.orientation = s.orientation;
3382 flags |= eDisplayTransactionNeeded;
3383 }
3384 if (state.frame != s.frame) {
3385 state.frame = s.frame;
3386 flags |= eDisplayTransactionNeeded;
3387 }
3388 if (state.viewport != s.viewport) {
3389 state.viewport = s.viewport;
3390 flags |= eDisplayTransactionNeeded;
3391 }
3392 }
3393 if (what & DisplayState::eDisplaySizeChanged) {
3394 if (state.width != s.width) {
3395 state.width = s.width;
3396 flags |= eDisplayTransactionNeeded;
3397 }
3398 if (state.height != s.height) {
3399 state.height = s.height;
3400 flags |= eDisplayTransactionNeeded;
3401 }
3402 }
3403
Mathias Agopiane57f2922012-08-09 16:29:12 -07003404 return flags;
3405}
3406
Robert Carrd4ae7f32018-06-07 16:10:57 -07003407bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3408 IPCThreadState* ipc = IPCThreadState::self();
3409 const int pid = ipc->getCallingPid();
3410 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003411 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003412 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003413 return false;
3414 }
3415 return true;
3416}
3417
chaviwca27f252018-02-06 16:46:39 -08003418uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3419 const layer_state_t& s = composerState.state;
3420 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3421
Mathias Agopian13127d82013-03-05 17:47:11 -08003422 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003423 if (layer == nullptr) {
3424 return 0;
3425 }
3426
Rob Carr4bba3702018-10-08 21:53:30 +00003427 if (layer->isPendingRemoval()) {
chaviw8b3871a2017-11-01 17:41:01 -07003428 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3429 return 0;
3430 }
3431
3432 uint32_t flags = 0;
3433
3434 const uint32_t what = s.what;
3435 bool geometryAppliesWithResize =
3436 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003437
3438 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3439 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003440 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003441 layer->pushPendingState();
3442 }
3443
chaviw8b3871a2017-11-01 17:41:01 -07003444 if (what & layer_state_t::ePositionChanged) {
3445 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3446 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003447 }
chaviw8b3871a2017-11-01 17:41:01 -07003448 }
3449 if (what & layer_state_t::eLayerChanged) {
3450 // NOTE: index needs to be calculated before we update the state
3451 const auto& p = layer->getParent();
3452 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003453 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003454 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003455 mCurrentState.layersSortedByZ.removeAt(idx);
3456 mCurrentState.layersSortedByZ.add(layer);
3457 // we need traversal (state changed)
3458 // AND transaction (list changed)
3459 flags |= eTransactionNeeded|eTraversalNeeded;
3460 }
chaviw8b3871a2017-11-01 17:41:01 -07003461 } else {
3462 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003463 flags |= eTransactionNeeded|eTraversalNeeded;
3464 }
3465 }
chaviw8b3871a2017-11-01 17:41:01 -07003466 }
3467 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003468 // NOTE: index needs to be calculated before we update the state
3469 const auto& p = layer->getParent();
3470 if (p == nullptr) {
3471 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3472 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3473 mCurrentState.layersSortedByZ.removeAt(idx);
3474 mCurrentState.layersSortedByZ.add(layer);
3475 // we need traversal (state changed)
3476 // AND transaction (list changed)
3477 flags |= eTransactionNeeded|eTraversalNeeded;
3478 }
3479 } else {
3480 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3481 flags |= eTransactionNeeded|eTraversalNeeded;
3482 }
chaviw8b3871a2017-11-01 17:41:01 -07003483 }
3484 }
3485 if (what & layer_state_t::eSizeChanged) {
3486 if (layer->setSize(s.w, s.h)) {
3487 flags |= eTraversalNeeded;
3488 }
3489 }
3490 if (what & layer_state_t::eAlphaChanged) {
3491 if (layer->setAlpha(s.alpha))
3492 flags |= eTraversalNeeded;
3493 }
3494 if (what & layer_state_t::eColorChanged) {
3495 if (layer->setColor(s.color))
3496 flags |= eTraversalNeeded;
3497 }
Peiyong Lind3788632018-09-18 16:01:31 -07003498 if (what & layer_state_t::eColorTransformChanged) {
3499 if (layer->setColorTransform(s.colorTransform)) {
3500 flags |= eTraversalNeeded;
3501 }
3502 }
chaviw8b3871a2017-11-01 17:41:01 -07003503 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003504 // TODO: b/109894387
3505 //
3506 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3507 // rotation. To see the problem observe that if we have a square parent, and a child
3508 // of the same size, then we rotate the child 45 degrees around it's center, the child
3509 // must now be cropped to a non rectangular 8 sided region.
3510 //
3511 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3512 // private API, and the WindowManager only uses rotation in one case, which is on a top
3513 // level layer in which cropping is not an issue.
3514 //
3515 // However given that abuse of rotation matrices could lead to surfaces extending outside
3516 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3517 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3518 // transformations.
3519 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003520 flags |= eTraversalNeeded;
3521 }
3522 if (what & layer_state_t::eTransparentRegionChanged) {
3523 if (layer->setTransparentRegionHint(s.transparentRegion))
3524 flags |= eTraversalNeeded;
3525 }
3526 if (what & layer_state_t::eFlagsChanged) {
3527 if (layer->setFlags(s.flags, s.mask))
3528 flags |= eTraversalNeeded;
3529 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003530 if (what & layer_state_t::eCropChanged_legacy) {
3531 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003532 flags |= eTraversalNeeded;
3533 }
chaviw8b3871a2017-11-01 17:41:01 -07003534 if (what & layer_state_t::eLayerStackChanged) {
3535 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3536 // We only allow setting layer stacks for top level layers,
3537 // everything else inherits layer stack from its parent.
3538 if (layer->hasParent()) {
3539 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3540 layer->getName().string());
3541 } else if (idx < 0) {
3542 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3543 "that also does not appear in the top level layer list. Something"
3544 " has gone wrong.", layer->getName().string());
3545 } else if (layer->setLayerStack(s.layerStack)) {
3546 mCurrentState.layersSortedByZ.removeAt(idx);
3547 mCurrentState.layersSortedByZ.add(layer);
3548 // we need traversal (state changed)
3549 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003550 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003551 }
3552 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003553 if (what & layer_state_t::eDeferTransaction_legacy) {
3554 if (s.barrierHandle_legacy != nullptr) {
3555 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3556 } else if (s.barrierGbp_legacy != nullptr) {
3557 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003558 if (authenticateSurfaceTextureLocked(gbp)) {
3559 const auto& otherLayer =
3560 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003561 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003562 } else {
3563 ALOGE("Attempt to defer transaction to to an"
3564 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003565 }
3566 }
chaviw8b3871a2017-11-01 17:41:01 -07003567 // We don't trigger a traversal here because if no other state is
3568 // changed, we don't want this to cause any more work
3569 }
3570 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003571 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003572 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003573 if (!hadParent) {
3574 mCurrentState.layersSortedByZ.remove(layer);
3575 }
chaviw8b3871a2017-11-01 17:41:01 -07003576 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003577 }
chaviw8b3871a2017-11-01 17:41:01 -07003578 }
3579 if (what & layer_state_t::eReparentChildren) {
3580 if (layer->reparentChildren(s.reparentHandle)) {
3581 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003582 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003583 }
chaviw8b3871a2017-11-01 17:41:01 -07003584 if (what & layer_state_t::eDetachChildren) {
3585 layer->detachChildren();
3586 }
3587 if (what & layer_state_t::eOverrideScalingModeChanged) {
3588 layer->setOverrideScalingMode(s.overrideScalingMode);
3589 // We don't trigger a traversal here because if no other state is
3590 // changed, we don't want this to cause any more work
3591 }
Marissa Wall61c58622018-07-18 10:12:20 -07003592 if (what & layer_state_t::eTransformChanged) {
3593 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3594 }
3595 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3596 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3597 flags |= eTraversalNeeded;
3598 }
3599 if (what & layer_state_t::eCropChanged) {
3600 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3601 }
3602 if (what & layer_state_t::eBufferChanged) {
3603 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3604 }
3605 if (what & layer_state_t::eAcquireFenceChanged) {
3606 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3607 }
3608 if (what & layer_state_t::eDataspaceChanged) {
3609 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3610 }
3611 if (what & layer_state_t::eHdrMetadataChanged) {
3612 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3613 }
3614 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3615 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3616 }
3617 if (what & layer_state_t::eApiChanged) {
3618 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3619 }
3620 if (what & layer_state_t::eSidebandStreamChanged) {
3621 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3622 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003623 return flags;
3624}
3625
chaviwca27f252018-02-06 16:46:39 -08003626void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3627 const layer_state_t& state = composerState.state;
3628 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3629
3630 sp<Layer> layer(client->getLayerUser(state.surface));
3631 if (layer == nullptr) {
3632 return;
3633 }
3634
Rob Carr4bba3702018-10-08 21:53:30 +00003635 if (layer->isPendingRemoval()) {
chaviwca27f252018-02-06 16:46:39 -08003636 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3637 return;
3638 }
3639
3640 if (state.what & layer_state_t::eDestroySurface) {
3641 removeLayerLocked(mStateLock, layer);
3642 }
3643}
3644
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003645status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003646 const String8& name,
3647 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003648 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003649 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003650 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003651{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003652 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003653 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003654 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003655 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003656 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003657
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003658 status_t result = NO_ERROR;
3659
3660 sp<Layer> layer;
3661
Cody Northropbc755282017-03-31 12:00:08 -06003662 String8 uniqueName = getUniqueLayerName(name);
3663
Mathias Agopian3165cc22012-08-08 19:42:09 -07003664 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003665 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003666 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3667 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003668
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003669 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003670 case ISurfaceComposerClient::eFXSurfaceBufferState:
3671 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3672 break;
chaviw13fdc492017-06-27 12:40:18 -07003673 case ISurfaceComposerClient::eFXSurfaceColor:
3674 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003675 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003676 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003677 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003678 case ISurfaceComposerClient::eFXSurfaceContainer:
3679 result = createContainerLayer(client,
3680 uniqueName, w, h, flags,
3681 handle, &layer);
3682 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003683 default:
3684 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003685 break;
3686 }
3687
Dan Stoza7d89d062015-04-30 13:29:25 -07003688 if (result != NO_ERROR) {
3689 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003690 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003691
Chia-I Wuab0c3192017-08-01 11:29:00 -07003692 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3693 // TODO b/64227542
3694 if (windowType == 441731) {
3695 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3696 layer->setPrimaryDisplayOnly();
3697 }
3698
Albert Chaulk479c60c2017-01-27 14:21:34 -05003699 layer->setInfo(windowType, ownerUid);
3700
Robert Carr1f0a16a2016-10-24 16:27:39 -07003701 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003702 if (result != NO_ERROR) {
3703 return result;
3704 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003705 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003706
3707 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003708 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003709}
3710
Cody Northropbc755282017-03-31 12:00:08 -06003711String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3712{
3713 bool matchFound = true;
3714 uint32_t dupeCounter = 0;
3715
3716 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3717 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3718
Dan Stoza436ccf32018-06-21 12:10:12 -07003719 // Grab the state lock since we're accessing mCurrentState
3720 Mutex::Autolock lock(mStateLock);
3721
Cody Northropbc755282017-03-31 12:00:08 -06003722 // Loop over layers until we're sure there is no matching name
3723 while (matchFound) {
3724 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003725 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003726 if (layer->getName() == uniqueName) {
3727 matchFound = true;
3728 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3729 }
3730 });
3731 }
3732
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003733 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3734 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003735
3736 return uniqueName;
3737}
3738
Marissa Wallfd668622018-05-10 10:21:13 -07003739status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3740 uint32_t w, uint32_t h, uint32_t flags,
3741 PixelFormat& format, sp<IBinder>* handle,
3742 sp<IGraphicBufferProducer>* gbp,
3743 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003744 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003745 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003746 case PIXEL_FORMAT_TRANSPARENT:
3747 case PIXEL_FORMAT_TRANSLUCENT:
3748 format = PIXEL_FORMAT_RGBA_8888;
3749 break;
3750 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003751 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003752 break;
3753 }
3754
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003755 sp<BufferQueueLayer> layer =
3756 new BufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003757 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003758 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003759 *handle = layer->getHandle();
3760 *gbp = layer->getProducer();
3761 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003762 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003763
Marissa Wallfd668622018-05-10 10:21:13 -07003764 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003765 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003766}
3767
Marissa Wall61c58622018-07-18 10:12:20 -07003768status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3769 uint32_t w, uint32_t h, uint32_t flags,
3770 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003771 sp<BufferStateLayer> layer =
3772 new BufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003773 *handle = layer->getHandle();
3774 *outLayer = layer;
3775
3776 return NO_ERROR;
3777}
3778
chaviw13fdc492017-06-27 12:40:18 -07003779status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003780 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003781 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003782{
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003783 *outLayer = new ColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003784 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003785 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003786}
3787
Robert Carr6b3f6c52018-08-13 13:05:17 -07003788status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3789 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3790 sp<IBinder>* handle, sp<Layer>* outLayer)
3791{
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003792 *outLayer = new ContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003793 *handle = (*outLayer)->getHandle();
3794 return NO_ERROR;
3795}
3796
3797
Mathias Agopianac9fa422013-02-11 16:40:36 -08003798status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003799{
Robert Carr9524cb32017-02-13 11:32:32 -08003800 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003801 status_t err = NO_ERROR;
3802 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003803 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003804 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003805 err = removeLayer(l);
3806 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3807 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003808 }
3809 return err;
3810}
3811
Rob Carr4bba3702018-10-08 21:53:30 +00003812status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
3813{
3814 // called by ~LayerCleaner() when all references to the IBinder (handle)
3815 // are gone
3816 sp<Layer> l = layer.promote();
3817 if (l == nullptr) {
3818 // The layer has already been removed, carry on
3819 return NO_ERROR;
3820 }
3821 // If we have a parent, then we can continue to live as long as it does.
3822 return removeLayer(l, true);
3823}
3824
Mathias Agopianb60314a2012-04-10 22:09:54 -07003825// ---------------------------------------------------------------------------
3826
Andy McFadden13a082e2012-08-24 10:16:42 -07003827void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003828 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3829 if (!displayToken) return;
3830
Jesse Hall01e29052013-02-19 16:13:35 -08003831 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003832 Vector<ComposerState> state;
3833 Vector<DisplayState> displays;
3834 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003835 d.what = DisplayState::eDisplayProjectionChanged |
3836 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003837 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003838 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003839 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003840 d.frame.makeInvalid();
3841 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003842 d.width = 0;
3843 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003844 displays.add(d);
3845 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003846
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003847 const auto display = getDisplayDevice(displayToken);
3848 if (!display) return;
3849
3850 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3851
3852 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003853 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003854 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003855
Brian Andersond0010582017-03-07 13:20:31 -08003856 // Use phase of 0 since phase is not known.
3857 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07003858 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
3859 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003860}
3861
3862void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003863 // Async since we may be called from the main thread.
3864 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003865}
3866
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003867void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3868 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003869 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003870 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003871
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003872 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003873 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003874 return;
3875 }
3876
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003877 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003878 ALOGW("Trying to set power mode for virtual display");
3879 return;
3880 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003881
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003882 display->setPowerMode(mode);
3883
Lloyd Pique4dccc412018-01-22 17:21:36 -08003884 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003885 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003886 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003887 if (idx < 0) {
3888 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3889 return;
3890 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003891 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003892 }
3893
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003894 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003895 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003896 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003897 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003898 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003899 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003900 if (mUseScheduler) {
3901 mScheduler->onScreenAcquired(mAppConnectionHandle);
3902 } else {
3903 mEventThread->onScreenAcquired();
3904 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07003905 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003906 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003907
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003908 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003909 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003910 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003911
3912 struct sched_param param = {0};
3913 param.sched_priority = 1;
3914 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3915 ALOGW("Couldn't set SCHED_FIFO on display on");
3916 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003917 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003918 // Turn off the display
3919 struct sched_param param = {0};
3920 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3921 ALOGW("Couldn't set SCHED_OTHER on display off");
3922 }
3923
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003924 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07003925 if (mUseScheduler) {
3926 mScheduler->disableHardwareVsync(true);
3927 } else {
3928 disableHardwareVsync(true); // also cancels any in-progress resync
3929 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07003930 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003931 if (mUseScheduler) {
3932 mScheduler->onScreenReleased(mAppConnectionHandle);
3933 } else {
3934 mEventThread->onScreenReleased();
3935 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07003936 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003937
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003938 getHwComposer().setPowerMode(type, mode);
3939 mVisibleRegionsDirty = true;
3940 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003941 } else if (mode == HWC_POWER_MODE_DOZE ||
3942 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003943 // Update display while dozing
3944 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003945 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003946 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003947 if (mUseScheduler) {
3948 mScheduler->onScreenAcquired(mAppConnectionHandle);
3949 } else {
3950 mEventThread->onScreenAcquired();
3951 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003952 resyncToHardwareVsync(true);
3953 }
3954 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3955 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003956 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07003957 if (mUseScheduler) {
3958 mScheduler->disableHardwareVsync(true);
3959 } else {
3960 disableHardwareVsync(true); // also cancels any in-progress resync
3961 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003962 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003963 if (mUseScheduler) {
3964 mScheduler->onScreenReleased(mAppConnectionHandle);
3965 } else {
3966 mEventThread->onScreenReleased();
3967 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003968 }
3969 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003970 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003971 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003972 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003973 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003974
3975 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003976}
3977
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003978void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003979 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003980 const auto display = getDisplayDevice(displayToken);
3981 if (!display) {
3982 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3983 displayToken.get());
3984 } else if (display->isVirtual()) {
3985 ALOGW("Attempt to set power mode %d for virtual display", mode);
3986 } else {
3987 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003988 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003989 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003990}
3991
3992// ---------------------------------------------------------------------------
3993
Lloyd Pique755e3192018-01-31 16:46:15 -08003994status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3995 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003996 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003997
Mathias Agopianbd115332013-04-18 16:41:04 -07003998 IPCThreadState* ipc = IPCThreadState::self();
3999 const int pid = ipc->getCallingPid();
4000 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004001
Mathias Agopianbd115332013-04-18 16:41:04 -07004002 if ((uid != AID_SHELL) &&
4003 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004004 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004005 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004006 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004007 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004008 // (this would indicate SF is stuck, but we want to be able to
4009 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004010 status_t err = mStateLock.timedLock(s2ns(1));
4011 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004012 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004013 result.appendFormat(
4014 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4015 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004016 }
4017
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004018 bool dumpAll = true;
4019 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004020 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004021
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004022 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004023 if ((index < numArgs) &&
4024 (args[index] == String16("--list"))) {
4025 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004026 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004027 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004028 }
4029
4030 if ((index < numArgs) &&
4031 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004032 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004033 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004034 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004035 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004036
4037 if ((index < numArgs) &&
4038 (args[index] == String16("--latency-clear"))) {
4039 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004040 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004041 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004042 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004043
4044 if ((index < numArgs) &&
4045 (args[index] == String16("--dispsync"))) {
4046 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004047 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004048 dumpAll = false;
4049 }
Dan Stozab90cf072015-03-05 11:05:59 -08004050
4051 if ((index < numArgs) &&
4052 (args[index] == String16("--static-screen"))) {
4053 index++;
4054 dumpStaticScreenStats(result);
4055 dumpAll = false;
4056 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004057
4058 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004059 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004060 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004061 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004062 dumpAll = false;
4063 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004064
4065 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4066 index++;
4067 dumpWideColorInfo(result);
4068 dumpAll = false;
4069 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004070
4071 if ((index < numArgs) &&
4072 (args[index] == String16("--enable-layer-stats"))) {
4073 index++;
4074 mLayerStats.enable();
4075 dumpAll = false;
4076 }
4077
4078 if ((index < numArgs) &&
4079 (args[index] == String16("--disable-layer-stats"))) {
4080 index++;
4081 mLayerStats.disable();
4082 dumpAll = false;
4083 }
4084
4085 if ((index < numArgs) &&
4086 (args[index] == String16("--clear-layer-stats"))) {
4087 index++;
4088 mLayerStats.clear();
4089 dumpAll = false;
4090 }
4091
4092 if ((index < numArgs) &&
4093 (args[index] == String16("--dump-layer-stats"))) {
4094 index++;
4095 mLayerStats.dump(result);
4096 dumpAll = false;
4097 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004098
4099 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004100 (args[index] == String16("--frame-composition"))) {
4101 index++;
4102 dumpFrameCompositionInfo(result);
4103 dumpAll = false;
4104 }
4105
4106 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004107 (args[index] == String16("--display-identification"))) {
4108 index++;
4109 dumpDisplayIdentificationData(result);
4110 dumpAll = false;
4111 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004112
4113 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4114 index++;
4115 mTimeStats.parseArgs(asProto, args, index, result);
4116 dumpAll = false;
4117 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004118 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004119
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004120 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004121 if (asProto) {
4122 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4123 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4124 } else {
4125 dumpAllLocked(args, index, result);
4126 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004127 }
4128
Mathias Agopian9795c422009-08-26 16:36:26 -07004129 if (locked) {
4130 mStateLock.unlock();
4131 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004132 }
4133 write(fd, result.string(), result.size());
4134 return NO_ERROR;
4135}
4136
Dan Stozac7014012014-02-14 15:03:43 -08004137void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4138 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004139{
Robert Carr2047fae2016-11-28 14:09:09 -08004140 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004141 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004142 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004143}
4144
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004145void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004146 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004147{
4148 String8 name;
4149 if (index < args.size()) {
4150 name = String8(args[index]);
4151 index++;
4152 }
4153
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004154 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4155 getHwComposer().isConnected(displayId)) {
4156 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4157 const nsecs_t period = activeConfig->getVsyncPeriod();
4158 result.appendFormat("%" PRId64 "\n", period);
4159 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004160
4161 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004162 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004163 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004164 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004165 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004166 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004167 }
Robert Carr2047fae2016-11-28 14:09:09 -08004168 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004169 }
4170}
4171
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004172void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004173 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004174{
4175 String8 name;
4176 if (index < args.size()) {
4177 name = String8(args[index]);
4178 index++;
4179 }
4180
Robert Carr2047fae2016-11-28 14:09:09 -08004181 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004182 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004183 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004184 }
Robert Carr2047fae2016-11-28 14:09:09 -08004185 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004186
Svetoslavd85084b2014-03-20 10:28:31 -07004187 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004188}
4189
Jamie Gennis6547ff42013-07-16 20:12:42 -07004190// This should only be called from the main thread. Otherwise it would need
4191// the lock and should use mCurrentState rather than mDrawingState.
4192void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004193 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004194 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004195 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004196
4197 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4198}
4199
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004200void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004201{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004202 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004203
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004204 if (isLayerTripleBufferingDisabled())
4205 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004206
4207 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004208 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004209 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004210 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004211 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4212 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004213 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004214}
4215
Dan Stozab90cf072015-03-05 11:05:59 -08004216void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4217{
4218 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004219 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4220 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004221 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004222 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004223 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4224 b + 1, bucketTimeSec, percent);
4225 }
David Sodman4a36e932017-11-07 14:29:47 -08004226 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004227 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004228 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004229 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004230 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004231}
4232
Dan Stozae77c7662016-05-13 11:37:28 -07004233void SurfaceFlinger::recordBufferingStats(const char* layerName,
4234 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004235 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4236 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004237 for (const auto& segment : history) {
4238 if (!segment.usedThirdBuffer) {
4239 stats.twoBufferTime += segment.totalTime;
4240 }
4241 if (segment.occupancyAverage < 1.0f) {
4242 stats.doubleBufferedTime += segment.totalTime;
4243 } else if (segment.occupancyAverage < 2.0f) {
4244 stats.tripleBufferedTime += segment.totalTime;
4245 }
4246 ++stats.numSegments;
4247 stats.totalTime += segment.totalTime;
4248 }
4249}
4250
Brian Andersond6927fb2016-07-23 23:37:30 -07004251void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4252 result.appendFormat("Layer frame timestamps:\n");
4253
4254 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4255 const size_t count = currentLayers.size();
4256 for (size_t i=0 ; i<count ; i++) {
4257 currentLayers[i]->dumpFrameEvents(result);
4258 }
4259}
4260
Dan Stozae77c7662016-05-13 11:37:28 -07004261void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4262 result.append("Buffering stats:\n");
4263 result.append(" [Layer name] <Active time> <Two buffer> "
4264 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004265 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004266 typedef std::tuple<std::string, float, float, float> BufferTuple;
4267 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004268 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004269 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004270 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004271 if (stats.numSegments == 0) {
4272 continue;
4273 }
4274 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4275 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4276 stats.totalTime;
4277 float doubleBufferRatio = static_cast<float>(
4278 stats.doubleBufferedTime) / stats.totalTime;
4279 float tripleBufferRatio = static_cast<float>(
4280 stats.tripleBufferedTime) / stats.totalTime;
4281 sorted.insert({activeTime, {name, twoBufferRatio,
4282 doubleBufferRatio, tripleBufferRatio}});
4283 }
4284 for (const auto& sortedPair : sorted) {
4285 float activeTime = sortedPair.first;
4286 const BufferTuple& values = sortedPair.second;
4287 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4288 std::get<0>(values).c_str(), activeTime,
4289 std::get<1>(values), std::get<2>(values),
4290 std::get<3>(values));
4291 }
4292 result.append("\n");
4293}
4294
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004295void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004296 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004297 const int32_t displayId = display->getId();
4298 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4299 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004300 continue;
4301 }
4302
Dominik Laskowski7e045462018-05-30 13:02:02 -07004303 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004304 uint8_t port;
4305 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004306 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004307 result.append("no identification data\n");
4308 continue;
4309 }
4310
4311 if (!isEdid(data)) {
4312 result.append("unknown identification data: ");
4313 for (uint8_t byte : data) {
4314 result.appendFormat("%x ", byte);
4315 }
4316 result.append("\n");
4317 continue;
4318 }
4319
4320 const auto edid = parseEdid(data);
4321 if (!edid) {
4322 result.append("invalid EDID: ");
4323 for (uint8_t byte : data) {
4324 result.appendFormat("%x ", byte);
4325 }
4326 result.append("\n");
4327 continue;
4328 }
4329
4330 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4331 result.append(edid->displayName.data(), edid->displayName.length());
4332 result.append("\"\n");
4333 }
4334 result.append("\n");
4335}
4336
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004337void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004338 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4339 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004340 result.appendFormat("DisplayColorSetting: %s\n",
4341 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004342
4343 // TODO: print out if wide-color mode is active or not
4344
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004345 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004346 const int32_t displayId = display->getId();
4347 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004348 continue;
4349 }
4350
Dominik Laskowski7e045462018-05-30 13:02:02 -07004351 result.appendFormat("Display %d color modes:\n", displayId);
4352 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004353 for (auto&& mode : modes) {
4354 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4355 }
4356
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004357 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004358 result.appendFormat(" Current color mode: %s (%d)\n",
4359 decodeColorMode(currentMode).c_str(), currentMode);
4360 }
4361 result.append("\n");
4362}
4363
David Sodman7e4ae112018-02-09 15:02:28 -08004364void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4365 std::string stringResult;
4366
4367 for (const auto& [token, display] : mDisplays) {
4368 const auto displayId = display->getId();
4369 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
4370 continue;
4371 }
4372
4373 const auto& compositionInfoIt = getBE().mEndOfFrameCompositionInfo.find(displayId);
4374 if (compositionInfoIt == getBE().mEndOfFrameCompositionInfo.end()) {
4375 break;
4376 }
4377 const auto& compositionInfoList = compositionInfoIt->second;
4378 stringResult += base::StringPrintf("Display: %d\n", displayId);
4379 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4380 for (const auto& compositionInfo : compositionInfoList) {
4381 compositionInfo.dump(stringResult, nullptr);
4382 stringResult += base::StringPrintf("\n");
4383 }
4384 }
4385
4386 result.append(stringResult.c_str());
4387}
4388
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004389LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004390 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004391 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4392 const State& state = useDrawing ? mDrawingState : mCurrentState;
4393 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004394 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004395 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004396 });
4397
4398 return layersProto;
4399}
4400
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004401LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004402 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004403
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004404 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004405 resolution->set_w(display.getWidth());
4406 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004407
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004408 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4409 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4410 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004411
Dominik Laskowski7e045462018-05-30 13:02:02 -07004412 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004413 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004414 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004415 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004416 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004417 }
4418 });
4419
4420 return layersProto;
4421}
4422
Mathias Agopian74d211a2013-04-22 16:55:35 +02004423void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4424 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004425{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004426 bool colorize = false;
4427 if (index < args.size()
4428 && (args[index] == String16("--color"))) {
4429 colorize = true;
4430 index++;
4431 }
4432
4433 Colorizer colorizer(colorize);
4434
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004435 // figure out if we're stuck somewhere
4436 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004437 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004438 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4439
4440 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004441 * Dump library configuration.
4442 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004443
4444 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004445 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004446 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004447 appendSfConfigString(result);
4448 appendUiConfigString(result);
4449 appendGuiConfigString(result);
4450 result.append("\n");
4451
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004452 result.append("\nDisplay identification data:\n");
4453 dumpDisplayIdentificationData(result);
4454
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004455 result.append("\nWide-Color information:\n");
4456 dumpWideColorInfo(result);
4457
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004458 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004459 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004460 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004461 result.append(SyncFeatures::getInstance().toString());
4462 result.append("\n");
4463
Andy McFadden41d67d72014-04-25 16:58:34 -07004464 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004465 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004466 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004467
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004468 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4469 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004470 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4471 getHwComposer().isConnected(displayId)) {
4472 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004473 result.appendFormat("Display %d: "
4474 "app phase %" PRId64 " ns, "
4475 "sf phase %" PRId64 " ns, "
4476 "early app phase %" PRId64 " ns, "
4477 "early sf phase %" PRId64 " ns, "
4478 "early app gl phase %" PRId64 " ns, "
4479 "early sf gl phase %" PRId64 " ns, "
4480 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4481 displayId,
4482 vsyncPhaseOffsetNs,
4483 sfVsyncPhaseOffsetNs,
4484 appEarlyOffset,
4485 sfEarlyOffset,
4486 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004487 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004488 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004489 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004490 result.append("\n");
4491
Dan Stozab90cf072015-03-05 11:05:59 -08004492 // Dump static screen stats
4493 result.append("\n");
4494 dumpStaticScreenStats(result);
4495 result.append("\n");
4496
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004497 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4498
Dan Stozae77c7662016-05-13 11:37:28 -07004499 dumpBufferingStats(result);
4500
Andy McFadden4803b742012-09-24 19:07:20 -07004501 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004502 * Dump the visible layer list
4503 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004504 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004505 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004506 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4507 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004508 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004509
Chia-I Wu2f884132018-09-13 15:17:58 -07004510 {
4511 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4512 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4513 result.append(LayerProtoParser::layerTreeToString(layerTree).c_str());
4514 result.append("\n");
4515 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004516
David Sodman7e4ae112018-02-09 15:02:28 -08004517 result.append("\nFrame-Composition information:\n");
4518 dumpFrameCompositionInfo(result);
4519 result.append("\n");
4520
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004521 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004522 * Dump Display state
4523 */
4524
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004525 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004526 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004527 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004528 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004529 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004530 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004531 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004532
4533 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004534 * Dump SurfaceFlinger global state
4535 */
4536
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004537 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004538 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004539 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004540
Mathias Agopian888c8222012-08-04 21:10:38 -07004541 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004542 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004543
David Sodmanbc815282017-11-05 18:57:52 -08004544 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004545
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004546 if (display) {
4547 display->undefinedRegion.dump(result, "undefinedRegion");
4548 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4549 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004550 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004551 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004552 " gpu_to_cpu_unsupported : %d\n",
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004553 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004554
4555 if (display) {
4556 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4557 result.appendFormat(" refresh-rate : %f fps\n"
4558 " x-dpi : %f\n"
4559 " y-dpi : %f\n",
4560 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4561 activeConfig->getDpiY());
4562 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004563
Mathias Agopian74d211a2013-04-22 16:55:35 +02004564 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004565 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004566
Ana Krulec98b5b242018-08-10 15:03:23 -07004567 result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004568 /*
4569 * VSYNC state
4570 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004571 if (mUseScheduler) {
4572 mScheduler->dump(mAppConnectionHandle, result);
4573 } else {
4574 mEventThread->dump(result);
4575 }
Dan Stozae22aec72016-08-01 13:20:59 -07004576 result.append("\n");
4577
4578 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004579 * Tracing state
4580 */
4581 mTracing.dump(result);
4582 result.append("\n");
4583
4584 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004585 * HWC layer minidump
4586 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004587 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004588 const int32_t displayId = display->getId();
4589 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004590 continue;
4591 }
4592
Dominik Laskowski7e045462018-05-30 13:02:02 -07004593 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004594 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004595 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004596 result.append("\n");
4597 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004598
4599 /*
4600 * Dump HWComposer state
4601 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004602 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004603 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004604 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004605 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004606 result.appendFormat(" h/w composer %s\n",
4607 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004608 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004609
4610 /*
4611 * Dump gralloc state
4612 */
4613 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4614 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004615
4616 /*
4617 * Dump VrFlinger state if in use.
4618 */
4619 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4620 result.append("VrFlinger state:\n");
4621 result.append(mVrFlinger->Dump().c_str());
4622 result.append("\n");
4623 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004624}
4625
Dominik Laskowski7e045462018-05-30 13:02:02 -07004626const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004627 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004628 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004629 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004630 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004631 }
4632 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004633
4634 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4635 static const Vector<sp<Layer>> empty;
4636 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004637}
4638
Keun young Park63f165f2012-08-31 10:53:36 -07004639bool SurfaceFlinger::startDdmConnection()
4640{
4641 void* libddmconnection_dso =
4642 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4643 if (!libddmconnection_dso) {
4644 return false;
4645 }
4646 void (*DdmConnection_start)(const char* name);
4647 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004648 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004649 if (!DdmConnection_start) {
4650 dlclose(libddmconnection_dso);
4651 return false;
4652 }
4653 (*DdmConnection_start)(getServiceName());
4654 return true;
4655}
4656
Chia-I Wu28f320b2018-05-03 11:02:56 -07004657void SurfaceFlinger::updateColorMatrixLocked() {
4658 mat4 colorMatrix;
4659 if (mGlobalSaturationFactor != 1.0f) {
4660 // Rec.709 luma coefficients
4661 float3 luminance{0.213f, 0.715f, 0.072f};
4662 luminance *= 1.0f - mGlobalSaturationFactor;
4663 mat4 saturationMatrix = mat4(
4664 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4665 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4666 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4667 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4668 );
4669 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4670 } else {
4671 colorMatrix = mClientColorMatrix * mDaltonizer();
4672 }
4673
4674 if (mCurrentState.colorMatrix != colorMatrix) {
4675 mCurrentState.colorMatrix = colorMatrix;
4676 mCurrentState.colorMatrixChanged = true;
4677 setTransactionFlags(eTransactionNeeded);
4678 }
4679}
4680
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004681status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004682#pragma clang diagnostic push
4683#pragma clang diagnostic error "-Wswitch-enum"
4684 switch (static_cast<ISurfaceComposerTag>(code)) {
4685 // These methods should at minimum make sure that the client requested
4686 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004687 case BOOT_FINISHED:
4688 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004689 case CREATE_CONNECTION:
4690 case CREATE_DISPLAY:
4691 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004692 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004693 case GET_ACTIVE_COLOR_MODE:
4694 case GET_ANIMATION_FRAME_STATS:
4695 case GET_HDR_CAPABILITIES:
4696 case SET_ACTIVE_CONFIG:
4697 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004698 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004699 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004700 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4701 IPCThreadState* ipc = IPCThreadState::self();
4702 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4703 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004704 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004705 }
Robert Carr1db73f62016-12-21 12:58:51 -08004706 return OK;
4707 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004708 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004709 IPCThreadState* ipc = IPCThreadState::self();
4710 const int pid = ipc->getCallingPid();
4711 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004712 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4713 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004714 return PERMISSION_DENIED;
4715 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004716 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004717 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004718 // Used by apps to hook Choreographer to SurfaceFlinger.
4719 case CREATE_DISPLAY_EVENT_CONNECTION:
4720 // The following calls are currently used by clients that do not
4721 // request necessary permissions. However, they do not expose any secret
4722 // information, so it is OK to pass them.
4723 case AUTHENTICATE_SURFACE:
4724 case GET_ACTIVE_CONFIG:
4725 case GET_BUILT_IN_DISPLAY:
4726 case GET_DISPLAY_COLOR_MODES:
4727 case GET_DISPLAY_CONFIGS:
4728 case GET_DISPLAY_STATS:
4729 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4730 // Calling setTransactionState is safe, because you need to have been
4731 // granted a reference to Client* and Handle* to do anything with it.
4732 case SET_TRANSACTION_STATE:
4733 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004734 case CREATE_SCOPED_CONNECTION:
4735 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004736 return OK;
4737 }
4738 case CAPTURE_LAYERS:
4739 case CAPTURE_SCREEN: {
4740 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004741 IPCThreadState* ipc = IPCThreadState::self();
4742 const int pid = ipc->getCallingPid();
4743 const int uid = ipc->getCallingUid();
4744 if ((uid != AID_GRAPHICS) &&
4745 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4746 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4747 return PERMISSION_DENIED;
4748 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004749 return OK;
4750 }
4751 // The following codes are deprecated and should never be allowed to access SF.
4752 case CONNECT_DISPLAY_UNUSED:
4753 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4754 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4755 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004756 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004757 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004758
4759 // These codes are used for the IBinder protocol to either interrogate the recipient
4760 // side of the transaction for its canonical interface descriptor or to dump its state.
4761 // We let them pass by default.
4762 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4763 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4764 code == IBinder::SYSPROPS_TRANSACTION) {
4765 return OK;
4766 }
4767 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4768 // in onTransact verifies that the user is root, and has access to use SF.
4769 if (code >= 1000 && code <= 1029) {
4770 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4771 return OK;
4772 }
4773 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4774 return PERMISSION_DENIED;
4775#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004776}
4777
Ana Krulec13be8ad2018-08-21 02:43:56 +00004778status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4779 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004780 status_t credentialCheck = CheckTransactCodeCredentials(code);
4781 if (credentialCheck != OK) {
4782 return credentialCheck;
4783 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004784
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004785 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4786 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004787 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004788 IPCThreadState* ipc = IPCThreadState::self();
4789 const int uid = ipc->getCallingUid();
4790 if (CC_UNLIKELY(uid != AID_SYSTEM
4791 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004792 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004793 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004794 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004795 return PERMISSION_DENIED;
4796 }
4797 int n;
4798 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004799 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004800 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004801 return NO_ERROR;
4802 case 1002: // SHOW_UPDATES
4803 n = data.readInt32();
4804 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004805 invalidateHwcGeometry();
4806 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004807 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004808 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004809 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004810 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004811 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004812 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004813 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004814 setTransactionFlags(
4815 eTransactionNeeded|
4816 eDisplayTransactionNeeded|
4817 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004818 return NO_ERROR;
4819 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004820 case 1006:{ // send empty update
4821 signalRefresh();
4822 return NO_ERROR;
4823 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004824 case 1008: // toggle use of hw composer
4825 n = data.readInt32();
4826 mDebugDisableHWC = n ? 1 : 0;
4827 invalidateHwcGeometry();
4828 repaintEverything();
4829 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004830 case 1009: // toggle use of transform hint
4831 n = data.readInt32();
4832 mDebugDisableTransformHint = n ? 1 : 0;
4833 invalidateHwcGeometry();
4834 repaintEverything();
4835 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004836 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004837 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004838 reply->writeInt32(0);
4839 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004840 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004841 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004842 return NO_ERROR;
4843 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004844 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004845 if (!display) {
4846 return NAME_NOT_FOUND;
4847 }
4848
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004849 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004850 return NO_ERROR;
4851 }
4852 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004853 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004854 // daltonize
4855 n = data.readInt32();
4856 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004857 case 1:
4858 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4859 break;
4860 case 2:
4861 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4862 break;
4863 case 3:
4864 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4865 break;
4866 default:
4867 mDaltonizer.setType(ColorBlindnessType::None);
4868 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004869 }
4870 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004871 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004872 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004873 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004874 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004875
4876 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004877 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004878 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004879 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004880 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004881 // apply a color matrix
4882 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004883 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004884 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004885 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004886 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004887 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004888 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004889 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004890 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004891 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004892 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004893
4894 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4895 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004896 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004897 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4898 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4899 }
4900
Chia-I Wu28f320b2018-05-03 11:02:56 -07004901 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004902 return NO_ERROR;
4903 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004904 // This is an experimental interface
4905 // Needs to be shifted to proper binder interface when we productize
4906 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004907 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07004908 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07004909 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004910 return NO_ERROR;
4911 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004912 case 1017: {
4913 n = data.readInt32();
4914 mForceFullDamage = static_cast<bool>(n);
4915 return NO_ERROR;
4916 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004917 case 1018: { // Modify Choreographer's phase offset
4918 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004919 if (mUseScheduler) {
4920 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
4921 } else {
4922 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4923 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004924 return NO_ERROR;
4925 }
4926 case 1019: { // Modify SurfaceFlinger's phase offset
4927 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004928 if (mUseScheduler) {
4929 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
4930 } else {
4931 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4932 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004933 return NO_ERROR;
4934 }
Irvel468051e2016-06-13 16:44:44 -07004935 case 1020: { // Layer updates interceptor
4936 n = data.readInt32();
4937 if (n) {
4938 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004939 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004940 }
4941 else{
4942 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004943 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004944 }
4945 return NO_ERROR;
4946 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004947 case 1021: { // Disable HWC virtual displays
4948 n = data.readInt32();
4949 mUseHwcVirtualDisplays = !n;
4950 return NO_ERROR;
4951 }
Romain Guy0147a172017-06-01 13:53:56 -07004952 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004953 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004954 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004955
Chia-I Wu28f320b2018-05-03 11:02:56 -07004956 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004957 return NO_ERROR;
4958 }
Romain Guy54f154a2017-10-24 21:40:32 +01004959 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004960 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004961 invalidateHwcGeometry();
4962 repaintEverything();
4963 return NO_ERROR;
4964 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004965 // TODO(b/111505327): Find out whether the usage of 1024 can switch to 1030,
4966 // deprecate 1024 if they can.
4967 case 1024: { // Does device have wide color gamut display?
Romain Guy54f154a2017-10-24 21:40:32 +01004968 reply->writeBool(hasWideColorDisplay);
4969 return NO_ERROR;
4970 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004971 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004972 n = data.readInt32();
4973 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004974 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004975 mTracing.enable();
4976 doTracing("tracing.enable");
4977 reply->writeInt32(NO_ERROR);
4978 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004979 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004980 status_t err = mTracing.disable();
4981 reply->writeInt32(err);
4982 }
4983 return NO_ERROR;
4984 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004985 case 1026: { // Get layer tracing status
4986 reply->writeBool(mTracing.isEnabled());
4987 return NO_ERROR;
4988 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004989 // Is a DisplayColorSetting supported?
4990 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004991 const auto display = getDefaultDisplayDevice();
4992 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004993 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004994 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004995
4996 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4997 switch (setting) {
4998 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07004999 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005000 break;
5001 case DisplayColorSetting::UNMANAGED:
5002 reply->writeBool(true);
5003 break;
5004 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005005 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005006 break;
5007 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005008 reply->writeBool(
5009 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005010 break;
5011 }
5012 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005013 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005014 // Is VrFlinger active?
5015 case 1028: {
5016 Mutex::Autolock _l(mStateLock);
5017 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5018 return NO_ERROR;
5019 }
David Sodman6d46c1e2018-07-13 12:59:48 -07005020 case 1029: {
5021 // Code 1029 is an experimental feature that allows applications to
5022 // simulate a high frequency panel by setting a multiplier and divisor
5023 // on the VSYNC-sf clock. If either the multiplier or divisor are
David Sodman44b5de02018-08-21 16:28:53 -07005024 // 0, then the code simply return the current multiplier and divisor.
5025 HWC2::Device::FrequencyScaler frequencyScaler;
5026 frequencyScaler.multiplier = data.readInt32();
5027 frequencyScaler.divisor = data.readInt32();
David Sodman6d46c1e2018-07-13 12:59:48 -07005028
David Sodman44b5de02018-08-21 16:28:53 -07005029 if ((frequencyScaler.multiplier == 0) || (frequencyScaler.divisor == 0)) {
5030 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5031 reply->writeInt32(frequencyScaler.multiplier);
5032 reply->writeInt32(frequencyScaler.divisor);
5033 return NO_ERROR;
David Sodman6d46c1e2018-07-13 12:59:48 -07005034 }
5035
David Sodman44b5de02018-08-21 16:28:53 -07005036 if ((frequencyScaler.multiplier == 1) && (frequencyScaler.divisor == 1)) {
Ana Krulece588e312018-09-18 12:32:24 -07005037 if (mUseScheduler) {
5038 mScheduler->enableHardwareVsync();
5039 } else {
5040 enableHardwareVsync();
5041 }
David Sodman6d46c1e2018-07-13 12:59:48 -07005042 } else {
Ana Krulece588e312018-09-18 12:32:24 -07005043 if (mUseScheduler) {
5044 mScheduler->disableHardwareVsync(true);
5045 } else {
5046 disableHardwareVsync(true);
5047 }
David Sodman6d46c1e2018-07-13 12:59:48 -07005048 }
David Sodman44b5de02018-08-21 16:28:53 -07005049 mPrimaryDispSync->scalePeriod(frequencyScaler);
5050 getBE().mHwc->setDisplayFrequencyScaleParameters(frequencyScaler);
David Sodman6d46c1e2018-07-13 12:59:48 -07005051
David Sodman44b5de02018-08-21 16:28:53 -07005052 ATRACE_INT("PeriodMultiplier", frequencyScaler.multiplier);
5053 ATRACE_INT("PeriodDivisor", frequencyScaler.divisor);
5054
5055 const hwc2_display_t hwcDisplayId = getBE().mHwc->getActiveConfig(
5056 DisplayDevice::DISPLAY_PRIMARY)->getDisplayId();
5057
5058 onHotplugReceived(getBE().mComposerSequenceId,
5059 hwcDisplayId, HWC2::Connection::Disconnected);
5060 onHotplugReceived(getBE().mComposerSequenceId,
5061 hwcDisplayId, HWC2::Connection::Connected);
5062 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5063 reply->writeInt32(frequencyScaler.multiplier);
5064 reply->writeInt32(frequencyScaler.divisor);
5065
David Sodman6d46c1e2018-07-13 12:59:48 -07005066 return NO_ERROR;
5067 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005068 // Is device color managed?
5069 case 1030: {
5070 reply->writeBool(useColorManagement);
5071 return NO_ERROR;
5072 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005073 }
5074 }
5075 return err;
5076}
5077
Steven Thomas6d8110b2017-08-31 18:24:21 -07005078void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005079 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005080 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005081}
5082
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005083// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5084class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005085public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005086 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5087 ~WindowDisconnector() {
5088 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005089 }
5090
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005091private:
5092 ANativeWindow* mWindow;
5093 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005094};
5095
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005096status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
5097 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005098 uint32_t reqWidth, uint32_t reqHeight,
5099 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005100 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005101 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005102
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005103 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005104
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005105 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5106
Chia-I Wu20261cb2018-08-23 12:55:44 -07005107 sp<DisplayDevice> display;
5108 {
5109 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005110
Chia-I Wu20261cb2018-08-23 12:55:44 -07005111 display = getDisplayDeviceLocked(displayToken);
5112 if (!display) return BAD_VALUE;
5113
Chia-I Wu8730ba82018-08-29 09:25:59 -07005114 // ignore sourceCrop (i.e., use the projected logical display
5115 // viewport) until the framework is fixed
5116 sourceCrop.clear();
Chia-I Wucb023152018-08-28 12:57:23 -07005117
5118 // set the requested width/height to the logical display viewport size
5119 // by default
5120 if (reqWidth == 0 || reqHeight == 0) {
5121 reqWidth = uint32_t(display->getViewport().width());
5122 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005123 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005124 }
5125
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005126 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005127
5128 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005129 display, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005130 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005131}
5132
5133status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08005134 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005135 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005136 ATRACE_CALL();
5137
5138 class LayerRenderArea : public RenderArea {
5139 public:
Robert Carr578038f2018-03-09 12:25:24 -08005140 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
5141 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
Chia-I Wu9d1abea2018-08-23 13:44:43 -07005142 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08005143 mLayer(layer),
5144 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005145 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005146 mFlinger(flinger),
5147 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005148 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005149 Rect getBounds() const override {
5150 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005151 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005152 }
Marissa Wall61c58622018-07-18 10:12:20 -07005153 int getHeight() const override {
5154 return mLayer->getActiveHeight(mLayer->getDrawingState());
5155 }
5156 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005157 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005158 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005159 Rect getSourceCrop() const override {
5160 if (mCrop.isEmpty()) {
5161 return getBounds();
5162 } else {
5163 return mCrop;
5164 }
5165 }
Robert Carr578038f2018-03-09 12:25:24 -08005166 class ReparentForDrawing {
5167 public:
5168 const sp<Layer>& oldParent;
5169 const sp<Layer>& newParent;
5170
5171 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5172 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005173 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005174 }
Robert Carr15eae092018-03-23 13:43:53 -07005175 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005176 };
5177
5178 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005179 const Rect sourceCrop = getSourceCrop();
5180 // no need to check rotation because there is none
5181 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5182 sourceCrop.height() != getReqHeight();
5183
Robert Carr578038f2018-03-09 12:25:24 -08005184 if (!mChildrenOnly) {
5185 mTransform = mLayer->getTransform().inverse();
5186 drawLayers();
5187 } else {
5188 Rect bounds = getBounds();
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005189 screenshotParentLayer = new ContainerLayer(
5190 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5191 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005192
5193 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5194 drawLayers();
5195 }
5196 }
chaviwa76b2712017-09-20 12:02:26 -07005197
chaviwa76b2712017-09-20 12:02:26 -07005198 private:
chaviw7206d492017-11-10 16:16:12 -08005199 const sp<Layer> mLayer;
5200 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005201
5202 // In the "childrenOnly" case we reparent the children to a screenshot
5203 // layer which has no properties set and which does not draw.
5204 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005205 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005206 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005207
5208 SurfaceFlinger* mFlinger;
5209 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005210 };
5211
5212 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5213 auto parent = layerHandle->owner.promote();
5214
Rob Carr4bba3702018-10-08 21:53:30 +00005215 if (parent == nullptr || parent->isPendingRemoval()) {
chaviw7206d492017-11-10 16:16:12 -08005216 ALOGE("captureLayers called with a removed parent");
5217 return NAME_NOT_FOUND;
5218 }
5219
Robert Carr578038f2018-03-09 12:25:24 -08005220 const int uid = IPCThreadState::self()->getCallingUid();
5221 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5222 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5223 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5224 return PERMISSION_DENIED;
5225 }
5226
chaviw7206d492017-11-10 16:16:12 -08005227 Rect crop(sourceCrop);
5228 if (sourceCrop.width() <= 0) {
5229 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005230 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005231 }
5232
5233 if (sourceCrop.height() <= 0) {
5234 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005235 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005236 }
5237
5238 int32_t reqWidth = crop.width() * frameScale;
5239 int32_t reqHeight = crop.height() * frameScale;
5240
Chia-I Wu20261cb2018-08-23 12:55:44 -07005241 // really small crop or frameScale
5242 if (reqWidth <= 0) {
5243 reqWidth = 1;
5244 }
5245 if (reqHeight <= 0) {
5246 reqHeight = 1;
5247 }
5248
Robert Carr578038f2018-03-09 12:25:24 -08005249 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005250
Robert Carr578038f2018-03-09 12:25:24 -08005251 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005252 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5253 if (!layer->isVisible()) {
5254 return;
Robert Carr578038f2018-03-09 12:25:24 -08005255 } else if (childrenOnly && layer == parent.get()) {
5256 return;
chaviwa76b2712017-09-20 12:02:26 -07005257 }
5258 visitor(layer);
5259 });
5260 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005261 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005262}
5263
5264status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5265 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005266 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005267 bool useIdentityTransform) {
5268 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005269
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005270 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5271 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5272 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5273 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005274
5275 // This mutex protects syncFd and captureResult for communication of the return values from the
5276 // main thread back to this Binder thread
5277 std::mutex captureMutex;
5278 std::condition_variable captureCondition;
5279 std::unique_lock<std::mutex> captureLock(captureMutex);
5280 int syncFd = -1;
5281 std::optional<status_t> captureResult;
5282
Robert Carr03480e22018-01-04 16:02:06 -08005283 const int uid = IPCThreadState::self()->getCallingUid();
5284 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5285
Dominik Laskowski8c001672018-05-30 16:52:06 -07005286 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005287 // If there is a refresh pending, bug out early and tell the binder thread to try again
5288 // after the refresh.
5289 if (mRefreshPending) {
5290 ATRACE_NAME("Skipping screenshot for now");
5291 std::unique_lock<std::mutex> captureLock(captureMutex);
5292 captureResult = std::make_optional<status_t>(EAGAIN);
5293 captureCondition.notify_one();
5294 return;
5295 }
5296
5297 status_t result = NO_ERROR;
5298 int fd = -1;
5299 {
5300 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005301 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005302 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5303 useIdentityTransform, forSystem, &fd);
5304 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005305 }
5306
5307 {
5308 std::unique_lock<std::mutex> captureLock(captureMutex);
5309 syncFd = fd;
5310 captureResult = std::make_optional<status_t>(result);
5311 captureCondition.notify_one();
5312 }
5313 });
5314
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005315 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005316 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005317 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005318 while (*captureResult == EAGAIN) {
5319 captureResult.reset();
5320 result = postMessageAsync(message);
5321 if (result != NO_ERROR) {
5322 return result;
5323 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005324 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005325 }
5326 result = *captureResult;
5327 }
5328
5329 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005330 sync_wait(syncFd, -1);
5331 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005332 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005333
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005334 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005335}
5336
chaviwa76b2712017-09-20 12:02:26 -07005337void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005338 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005339 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005340 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005341
Lloyd Pique144e1162017-12-20 16:44:52 -08005342 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005343
chaviwa76b2712017-09-20 12:02:26 -07005344 const auto reqWidth = renderArea.getReqWidth();
5345 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005346 const auto sourceCrop = renderArea.getSourceCrop();
5347 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005348
Chia-I Wu36574d92018-05-16 10:54:36 -07005349 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5350 engine.setOutputDataSpace(Dataspace::SRGB);
5351 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005352
Mathias Agopian180f10d2013-04-10 22:55:41 -07005353 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005354 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005355
5356 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005357 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005358 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005359
chaviw50da5042018-04-09 13:49:37 -07005360 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005361 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005362 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005363
chaviwa76b2712017-09-20 12:02:26 -07005364 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005365 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005366 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005367 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005368 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005369}
5370
chaviwa76b2712017-09-20 12:02:26 -07005371status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5372 TraverseLayersFunction traverseLayers,
5373 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005374 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005375 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005376 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005377 ATRACE_CALL();
5378
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005379 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005380
5381 traverseLayers([&](Layer* layer) {
5382 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5383 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005384
Robert Carr03480e22018-01-04 16:02:06 -08005385 // We allow the system server to take screenshots of secure layers for
5386 // use in situations like the Screen-rotation animation and place
5387 // the impetus on WindowManager to not persist them.
5388 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005389 ALOGW("FB is protected: PERMISSION_DENIED");
5390 return PERMISSION_DENIED;
5391 }
5392
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005393 // this binds the given EGLImage as a framebuffer for the
5394 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005395 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005396 if (bufferBond.getStatus() != NO_ERROR) {
5397 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005398 return INVALID_OPERATION;
5399 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005400
Dan Stozaabcda352017-06-01 14:37:39 -07005401 // this will in fact render into our dequeued buffer
5402 // via an FBO, which means we didn't have to create
5403 // an EGLSurface and therefore we're not
5404 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005405 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005406
Alec Mouri492bc572018-09-11 21:40:04 +00005407 base::unique_fd syncFd = getRenderEngine().flush();
5408 if (syncFd < 0) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005409 getRenderEngine().finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005410 }
Alec Mouri492bc572018-09-11 21:40:04 +00005411 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005412
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005413 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005414}
5415
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005416// ---------------------------------------------------------------------------
5417
Dan Stoza412903f2017-04-27 13:42:17 -07005418void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5419 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005420}
5421
Dan Stoza412903f2017-04-27 13:42:17 -07005422void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5423 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005424}
5425
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005426void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005427 const LayerVector::Visitor& visitor) {
5428 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005429 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005430 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005431 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005432 continue;
5433 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005434 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005435 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005436 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005437 return;
5438 }
chaviwa76b2712017-09-20 12:02:26 -07005439 if (!layer->isVisible()) {
5440 return;
5441 }
5442 visitor(layer);
5443 });
5444 }
5445}
5446
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005447}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005448
Lloyd Pique074e8122018-07-26 12:57:23 -07005449
Mathias Agopian3f844832013-08-07 21:24:32 -07005450#if defined(__gl_h_)
5451#error "don't include gl/gl.h in this file"
5452#endif
5453
5454#if defined(__gl2_h_)
5455#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005456#endif