blob: 643b1ce3367fbff001129000e07aeb700fb97fa6 [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"
Lloyd Pique90c115d2018-09-18 21:39:42 -070078#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070080#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081
Steven Thomasb02664d2017-07-26 18:48:28 -070082#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070083#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070084#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070085#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070086#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070087#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070088#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070089#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070090#include "Scheduler/EventControlThread.h"
91#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070092#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070093#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070094#include "Scheduler/Scheduler.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070095
Mathias Agopianff2ed702013-09-01 21:36:12 -070096#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070097
David Sodman7e4ae112018-02-09 15:02:28 -080098#include "android-base/stringprintf.h"
99
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900100#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800101#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700102#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800103#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900104#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900105
chaviw1d044282017-09-27 12:19:28 -0700106#include <layerproto/LayerProtoParser.h>
107
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800108#define DISPLAY_COUNT 1
109
110namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700111
Jaesoo Lee43518572017-01-23 19:03:16 +0900112using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900113using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700114using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700115using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700116using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700117using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900118
Steven Thomasb02664d2017-07-26 18:48:28 -0700119namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700120
121#pragma clang diagnostic push
122#pragma clang diagnostic error "-Wswitch-enum"
123
124bool isWideColorMode(const ColorMode colorMode) {
125 switch (colorMode) {
126 case ColorMode::DISPLAY_P3:
127 case ColorMode::ADOBE_RGB:
128 case ColorMode::DCI_P3:
129 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700130 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700131 case ColorMode::BT2100_PQ:
132 case ColorMode::BT2100_HLG:
133 return true;
134 case ColorMode::NATIVE:
135 case ColorMode::STANDARD_BT601_625:
136 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
137 case ColorMode::STANDARD_BT601_525:
138 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
139 case ColorMode::STANDARD_BT709:
140 case ColorMode::SRGB:
141 return false;
142 }
143 return false;
144}
145
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700146ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
147 switch (rotation) {
148 case ISurfaceComposer::eRotateNone:
149 return ui::Transform::ROT_0;
150 case ISurfaceComposer::eRotate90:
151 return ui::Transform::ROT_90;
152 case ISurfaceComposer::eRotate180:
153 return ui::Transform::ROT_180;
154 case ISurfaceComposer::eRotate270:
155 return ui::Transform::ROT_270;
156 }
157 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
158 return ui::Transform::ROT_0;
159}
160
Peiyong Linfca547f2018-07-09 13:03:33 -0700161#pragma clang diagnostic pop
162
Steven Thomasb02664d2017-07-26 18:48:28 -0700163class ConditionalLock {
164public:
165 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
166 if (lock) {
167 mMutex.lock();
168 }
169 }
170 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
171private:
172 Mutex& mMutex;
173 bool mLocked;
174};
Peiyong Linfca547f2018-07-09 13:03:33 -0700175
Steven Thomasb02664d2017-07-26 18:48:28 -0700176} // namespace anonymous
177
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800178// ---------------------------------------------------------------------------
179
Mathias Agopian99b49842011-06-27 16:05:52 -0700180const String16 sHardwareTest("android.permission.HARDWARE_TEST");
181const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
182const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
183const String16 sDump("android.permission.DUMP");
184
185// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800186int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
187int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700188int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700189bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800190uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800191bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800192bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800193int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800194// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600195bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700196int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700197bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700198bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700199Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
200ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
201Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
202ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700203
Kalle Raitaa099a242017-01-11 11:17:29 -0800204std::string getHwcServiceName() {
205 char value[PROPERTY_VALUE_MAX] = {};
206 property_get("debug.sf.hwc_service_name", value, "default");
207 ALOGI("Using HWComposer service: '%s'", value);
208 return std::string(value);
209}
210
211bool useTrebleTestingOverride() {
212 char value[PROPERTY_VALUE_MAX] = {};
213 property_get("debug.sf.treble_testing_override", value, "false");
214 ALOGI("Treble testing override: '%s'", value);
215 return std::string(value) == "true";
216}
217
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800218std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
219 switch(displayColorSetting) {
220 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700221 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800222 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700223 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800224 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700225 return std::string("Enhanced");
226 default:
227 return std::string("Unknown ") +
228 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800229 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800230}
231
David Sodmanbc815282017-11-05 18:57:52 -0800232SurfaceFlingerBE::SurfaceFlingerBE()
233 : mHwcServiceName(getHwcServiceName()),
234 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800235 mFrameBuckets(),
236 mTotalTime(0),
237 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800238 mComposerSequenceId(0) {
239}
240
Lloyd Pique90c115d2018-09-18 21:39:42 -0700241SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
242 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800243 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700244 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700245 mTransactionPending(false),
246 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700247 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700248 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800249 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700250 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800251 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800252 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800253 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800254 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800255 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700256 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700257 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700258 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700259 mDebugInTransaction(0),
260 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700261 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700262 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700263 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800264 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800265 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800266 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700267 mVrFlingerRequestsDisplay(false),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700268 mMainThreadId(std::this_thread::get_id()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800269
Lloyd Pique90c115d2018-09-18 21:39:42 -0700270SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
271 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800272 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800273
274 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
275 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
276
277 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
278 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
279
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800280 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
281 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800282
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700283 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
284 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
285
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700286 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
287 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
288
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800289 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
290 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
291
Steven Thomas050b2c82017-03-06 11:45:16 -0800292 // Vr flinger is only enabled on Daydream ready devices.
293 useVrFlinger = getBool< ISurfaceFlingerConfigs,
294 &ISurfaceFlingerConfigs::useVrFlinger>(false);
295
Fabien Sanglard1971b632017-03-10 14:50:03 -0800296 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
297 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
298
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600299 hasWideColorDisplay =
300 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700301 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700302 getBool<V1_2::ISurfaceFlingerConfigs,
303 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
304
305 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
306 if (surfaceFlingerConfigsServiceV1_2) {
307 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
Peiyong Linc6780972018-10-28 15:24:08 -0700308 [&](auto tmpDefaultDataspace, auto tmpDefaultPixelFormat,
309 auto tmpWideColorGamutDataspace, auto tmpWideColorGamutPixelFormat) {
310 defaultCompositionDataspace = tmpDefaultDataspace;
311 defaultCompositionPixelFormat = tmpDefaultPixelFormat;
312 wideColorGamutCompositionDataspace = tmpWideColorGamutDataspace;
313 wideColorGamutCompositionPixelFormat = tmpWideColorGamutPixelFormat;
314 });
Peiyong Lin0256f722018-08-31 15:45:10 -0700315 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600316
Peiyong Linb3839ad2018-09-05 15:37:19 -0700317 useContextPriority = getBool<ISurfaceFlingerConfigs,
318 &ISurfaceFlingerConfigs::useContextPriority>(true);
319
Iris Chang7501ed62018-04-30 14:45:42 +0800320 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700321 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
322 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800323 V1_1::DisplayOrientation::ORIENTATION_0);
324
325 switch (primaryDisplayOrientation) {
326 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700327 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800328 break;
329 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700330 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800331 break;
332 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700333 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800334 break;
335 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700336 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800337 break;
338 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700339 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800340
Lloyd Pique90c115d2018-09-18 21:39:42 -0700341 mPrimaryDispSync =
342 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
343 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700344
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800345 // debugging stuff...
346 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700347
Mathias Agopianb4b17302013-03-20 18:36:41 -0700348 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700349 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700350
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800351 property_get("debug.sf.showupdates", value, "0");
352 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700353
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700354 property_get("debug.sf.ddms", value, "0");
355 mDebugDDMS = atoi(value);
356 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700357 if (!startDdmConnection()) {
358 // start failed, and DDMS debugging not enabled
359 mDebugDDMS = 0;
360 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700361 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700362 ALOGI_IF(mDebugRegion, "showupdates enabled");
363 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700364
365 property_get("debug.sf.disable_backpressure", value, "0");
366 mPropagateBackpressure = !atoi(value);
367 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700368
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800369 property_get("debug.sf.enable_hwc_vds", value, "0");
370 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800371 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800372
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800373 property_get("ro.sf.disable_triple_buffer", value, "1");
374 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800375 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700376
Yiwei Zhang243b3782018-05-15 17:40:04 -0700377 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700378 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
379 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
380
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200381 property_get("debug.sf.early_phase_offset_ns", value, "-1");
382 const int earlySfOffsetNs = atoi(value);
383
384 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
385 const int earlyGlSfOffsetNs = atoi(value);
386
387 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
388 const int earlyAppOffsetNs = atoi(value);
389
390 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
391 const int earlyGlAppOffsetNs = atoi(value);
392
Ana Krulec98b5b242018-08-10 15:03:23 -0700393 property_get("debug.sf.use_scheduler", value, "0");
394 mUseScheduler = atoi(value);
395
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200396 const VSyncModulator::Offsets earlyOffsets =
397 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
398 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
399 const VSyncModulator::Offsets earlyGlOffsets =
400 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
401 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
402 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
403 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700404
Romain Guy11d63f42017-07-20 12:47:14 -0700405 // We should be reading 'persist.sys.sf.color_saturation' here
406 // but since /data may be encrypted, we need to wait until after vold
407 // comes online to attempt to read the property. The property is
408 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800409
410 if (useTrebleTestingOverride()) {
411 // Without the override SurfaceFlinger cannot connect to HIDL
412 // services that are not listed in the manifests. Considered
413 // deriving the setting from the set service name, but it
414 // would be brittle if the name that's not 'default' is used
415 // for production purposes later on.
416 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
417 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800418}
419
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800420void SurfaceFlinger::onFirstRef()
421{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800422 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800423}
424
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800425SurfaceFlinger::~SurfaceFlinger()
426{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800427}
428
Dan Stozac7014012014-02-14 15:03:43 -0800429void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800430{
431 // the window manager died on us. prepare its eulogy.
432
Andy McFadden13a082e2012-08-24 10:16:42 -0700433 // restore initial conditions (default device unblank, etc)
434 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800435
436 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700437 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800438}
439
Robert Carr1db73f62016-12-21 12:58:51 -0800440static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700441 status_t err = client->initCheck();
442 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800443 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800444 }
Robert Carr1db73f62016-12-21 12:58:51 -0800445 return nullptr;
446}
447
448sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
449 return initClient(new Client(this));
450}
451
452sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
453 const sp<IGraphicBufferProducer>& gbp) {
454 if (authenticateSurfaceTexture(gbp) == false) {
455 return nullptr;
456 }
457 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
458 if (layer == nullptr) {
459 return nullptr;
460 }
461
462 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800463}
464
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700465sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
466 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700467{
468 class DisplayToken : public BBinder {
469 sp<SurfaceFlinger> flinger;
470 virtual ~DisplayToken() {
471 // no more references, this display must be terminated
472 Mutex::Autolock _l(flinger->mStateLock);
473 flinger->mCurrentState.displays.removeItem(this);
474 flinger->setTransactionFlags(eDisplayTransactionNeeded);
475 }
476 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700477 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700478 : flinger(flinger) {
479 }
480 };
481
482 sp<BBinder> token = new DisplayToken(this);
483
484 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700485 DisplayDeviceState info;
486 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700487 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700488 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700489 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800490 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700491 return token;
492}
493
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700494void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700495 Mutex::Autolock _l(mStateLock);
496
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700497 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700498 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700499 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700500 return;
501 }
502
503 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700504 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700505 ALOGE("destroyDisplay called for non-virtual display");
506 return;
507 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700508 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700509 mCurrentState.displays.removeItemsAt(idx);
510 setTransactionFlags(eDisplayTransactionNeeded);
511}
512
Mathias Agopiane57f2922012-08-09 16:29:12 -0700513sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700514 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700515 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800516 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700517 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700518 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700519}
520
Ady Abraham37965d42018-11-01 13:43:32 -0700521status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
522 if (!outGetColorManagement) {
523 return BAD_VALUE;
524 }
525 *outGetColorManagement = useColorManagement;
526 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700527}
528
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800529void SurfaceFlinger::bootFinished()
530{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700531 if (mStartPropertySetThread->join() != NO_ERROR) {
532 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800533 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800534 const nsecs_t now = systemTime();
535 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000536 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700537
538 // wait patiently for the window manager death
539 const String16 name("window");
540 sp<IBinder> window(defaultServiceManager()->getService(name));
541 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700542 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700543 }
544
Steven Thomas050b2c82017-03-06 11:45:16 -0800545 if (mVrFlinger) {
546 mVrFlinger->OnBootFinished();
547 }
548
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700549 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700550 // formerly we would just kill the process, but we now ask it to exit so it
551 // can choose where to stop the animation.
552 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700553
554 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
555 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
556 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700557
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800558 postMessageAsync(new LambdaMessage([this] {
559 readPersistentProperties();
560 mBootStage = BootStage::FINISHED;
561 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800562}
563
Dan Stoza436ccf32018-06-21 12:10:12 -0700564uint32_t SurfaceFlinger::getNewTexture() {
565 {
566 std::lock_guard lock(mTexturePoolMutex);
567 if (!mTexturePool.empty()) {
568 uint32_t name = mTexturePool.back();
569 mTexturePool.pop_back();
570 ATRACE_INT("TexturePoolSize", mTexturePool.size());
571 return name;
572 }
573
574 // The pool was too small, so increase it for the future
575 ++mTexturePoolSize;
576 }
577
578 // The pool was empty, so we need to get a new texture name directly using a
579 // blocking call to the main thread
580 uint32_t name = 0;
581 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
582 return name;
583}
584
Mathias Agopian3f844832013-08-07 21:24:32 -0700585void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700586 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700587}
588
Wei Wangf9b05ee2017-07-19 20:59:39 -0700589// Do not call property_set on main thread which will be blocked by init
590// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700591void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700592 ALOGI( "SurfaceFlinger's main thread ready to run. "
593 "Initializing graphics H/W...");
594
Thierry Strudel2924d012017-08-14 15:19:37 -0700595 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900596
Steven Thomasb02664d2017-07-26 18:48:28 -0700597 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800598
Steven Thomasb02664d2017-07-26 18:48:28 -0700599 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700600 if (mUseScheduler) {
Lloyd Pique90c115d2018-09-18 21:39:42 -0700601 mScheduler = getFactory().createScheduler(
Ana Krulece588e312018-09-18 12:32:24 -0700602 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Ana Krulec98b5b242018-08-10 15:03:23 -0700603 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700604 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700605 [this] { resyncWithRateLimit(); },
606 impl::EventThread::InterceptVSyncsCallback());
607 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700608 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700609 [this] { resyncWithRateLimit(); },
610 [this](nsecs_t timestamp) {
611 mInterceptor->saveVSyncEvent(timestamp);
612 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800613
Ana Krulec98b5b242018-08-10 15:03:23 -0700614 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700615 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
616 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700617 } else {
618 mEventThreadSource =
619 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
620 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
621 mEventThread =
622 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
623 [this] { resyncWithRateLimit(); },
624 impl::EventThread::InterceptVSyncsCallback(),
625 "appEventThread");
626 mSfEventThreadSource =
627 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
628 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
629
630 mSFEventThread =
631 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
632 [this] { resyncWithRateLimit(); },
633 [this](nsecs_t timestamp) {
634 mInterceptor->saveVSyncEvent(timestamp);
635 },
636 "sfEventThread");
637 mEventQueue->setEventThread(mSFEventThread.get());
638 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
639 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800640
Steven Thomasb02664d2017-07-26 18:48:28 -0700641 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700642 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700643 renderEngineFeature |= (useColorManagement ?
644 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700645 renderEngineFeature |= (useContextPriority ?
646 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700647
648 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
649 getBE().mRenderEngine =
Peiyong Linc6780972018-10-28 15:24:08 -0700650 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
651 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800652 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700653
654 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
655 "Starting with vr flinger active is not currently supported.");
Lloyd Pique90c115d2018-09-18 21:39:42 -0700656 getBE().mHwc = getFactory().createHWComposer(getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -0700657 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800658 // Process any initial hotplug and resulting display changes.
659 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700660 const auto display = getDefaultDisplayDeviceLocked();
661 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
662 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
663 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800664
Lloyd Piquefcd86612017-12-14 17:15:36 -0800665 // make the default display GLContext current so that we can create textures
666 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700667 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800668
Steven Thomas050b2c82017-03-06 11:45:16 -0800669 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700670 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700671 // This callback is called from the vr flinger dispatch thread. We
672 // need to call signalTransaction(), which requires holding
673 // mStateLock when we're not on the main thread. Acquiring
674 // mStateLock from the vr flinger dispatch thread might trigger a
675 // deadlock in surface flinger (see b/66916578), so post a message
676 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700677 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700678 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
679 mVrFlingerRequestsDisplay = requestDisplay;
680 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700681 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800682 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700683 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
684 getHwComposer()
685 .getHwcDisplayId(display->getId())
686 .value_or(0),
687 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800688 if (!mVrFlinger) {
689 ALOGE("Failed to start vrflinger");
690 }
691 }
692
Lloyd Pique90c115d2018-09-18 21:39:42 -0700693 mEventControlThread = getFactory().createEventControlThread(
Lloyd Pique379adc12018-01-22 17:31:47 -0800694 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700695
Mathias Agopian92a979a2012-08-02 18:32:23 -0700696 // initialize our drawing state
697 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700698
Andy McFadden13a082e2012-08-24 10:16:42 -0700699 // set initial conditions (e.g. unblank default device)
700 initializeDisplays();
701
David Sodmanbc815282017-11-05 18:57:52 -0800702 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700703
Wei Wangf9b05ee2017-07-19 20:59:39 -0700704 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700705
706 const bool presentFenceReliable =
707 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
708 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700709
710 if (mStartPropertySetThread->Start() != NO_ERROR) {
711 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800712 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800713
Chia-I Wud49d6692018-06-27 07:17:41 +0800714 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
715 // is used to saturate legacy sRGB content. However, to make sure the same color under
716 // Display P3 will be saturated to the same color, we intentionally break the API spec
717 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
718 // such saturation matrix on Display P3 is understood fully, the API should always return
719 // identify matrix.
720 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
721 Dataspace::SRGB_LINEAR);
722
723 // we will apply this on Display P3.
724 if (mEnhancedSaturationMatrix != mat4()) {
725 ColorSpace srgb(ColorSpace::sRGB());
726 ColorSpace displayP3(ColorSpace::DisplayP3());
727 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
728 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
729 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
730 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800731
Dan Stoza9e56aa02015-11-02 13:00:03 -0800732 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700733}
734
Romain Guy11d63f42017-07-20 12:47:14 -0700735void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700736 Mutex::Autolock _l(mStateLock);
737
Romain Guy11d63f42017-07-20 12:47:14 -0700738 char value[PROPERTY_VALUE_MAX];
739
740 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800741 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700742 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800743 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100744
745 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700746 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700747}
748
Mathias Agopiana67e4182012-06-19 17:26:12 -0700749void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800750 // Start boot animation service by setting a property mailbox
751 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700752 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800753 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700754 if (mStartPropertySetThread->join() != NO_ERROR) {
755 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800756 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700757}
758
Mathias Agopian875d8e12013-06-07 15:35:48 -0700759size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800760 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700761}
762
Mathias Agopian875d8e12013-06-07 15:35:48 -0700763size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800764 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700765}
766
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800767// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800768
Jamie Gennis582270d2011-08-17 18:19:00 -0700769bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800770 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800771 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800772 return authenticateSurfaceTextureLocked(bufferProducer);
773}
774
775bool SurfaceFlinger::authenticateSurfaceTextureLocked(
776 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800777 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800778 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800779}
780
Brian Anderson6b376712017-04-04 10:51:39 -0700781status_t SurfaceFlinger::getSupportedFrameTimestamps(
782 std::vector<FrameEvent>* outSupported) const {
783 *outSupported = {
784 FrameEvent::REQUESTED_PRESENT,
785 FrameEvent::ACQUIRE,
786 FrameEvent::LATCH,
787 FrameEvent::FIRST_REFRESH_START,
788 FrameEvent::LAST_REFRESH_START,
789 FrameEvent::GPU_COMPOSITION_DONE,
790 FrameEvent::DEQUEUE_READY,
791 FrameEvent::RELEASE,
792 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700793 ConditionalLock _l(mStateLock,
794 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700795 if (!getHwComposer().hasCapability(
796 HWC2::Capability::PresentFenceIsNotReliable)) {
797 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
798 }
799 return NO_ERROR;
800}
801
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700802status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
803 Vector<DisplayInfo>* configs) {
804 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700805 return BAD_VALUE;
806 }
807
Jesse Hall692c7232012-11-08 15:41:56 -0800808 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700809 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
810 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700811 type = i;
812 break;
813 }
814 }
815
816 if (type < 0) {
817 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700818 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700819
Mathias Agopian8b736f12012-08-13 17:54:26 -0700820 // TODO: Not sure if display density should handled by SF any longer
821 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700822 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700823 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700824 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800825 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700826 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700827 }
828 return density;
829 }
830 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700831 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700832 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700833 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700834 return getDensityFromProperty("ro.sf.lcd_density"); }
835 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700836
Dan Stoza7f7da322014-05-02 15:26:25 -0700837 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700838
Steven Thomas6d8110b2017-08-31 18:24:21 -0700839 ConditionalLock _l(mStateLock,
840 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800841 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700842 DisplayInfo info = DisplayInfo();
843
Dan Stoza9e56aa02015-11-02 13:00:03 -0800844 float xdpi = hwConfig->getDpiX();
845 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700846
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700847 info.w = hwConfig->getWidth();
848 info.h = hwConfig->getHeight();
849 // Default display viewport to display width and height
850 info.viewportW = info.w;
851 info.viewportH = info.h;
852
Dan Stoza7f7da322014-05-02 15:26:25 -0700853 if (type == DisplayDevice::DISPLAY_PRIMARY) {
854 // The density of the device is provided by a build property
855 float density = Density::getBuildDensity() / 160.0f;
856 if (density == 0) {
857 // the build doesn't provide a density -- this is wrong!
858 // use xdpi instead
859 ALOGE("ro.sf.lcd_density must be defined as a build property");
860 density = xdpi / 160.0f;
861 }
862 if (Density::getEmuDensity()) {
863 // if "qemu.sf.lcd_density" is specified, it overrides everything
864 xdpi = ydpi = density = Density::getEmuDensity();
865 density /= 160.0f;
866 }
867 info.density = density;
868
869 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700870 const auto display = getDefaultDisplayDeviceLocked();
871 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700872
873 // This is for screenrecord
874 const Rect viewport = display->getViewport();
875 if (viewport.isValid()) {
876 info.viewportW = uint32_t(viewport.getWidth());
877 info.viewportH = uint32_t(viewport.getHeight());
878 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700879 } else {
880 // TODO: where should this value come from?
881 static const int TV_DENSITY = 213;
882 info.density = TV_DENSITY / 160.0f;
883 info.orientation = 0;
884 }
885
Dan Stoza7f7da322014-05-02 15:26:25 -0700886 info.xdpi = xdpi;
887 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800888 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900889 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800890
Andy McFadden91b2ca82014-06-13 14:04:23 -0700891 // This is how far in advance a buffer must be queued for
892 // presentation at a given time. If you want a buffer to appear
893 // on the screen at time N, you must submit the buffer before
894 // (N - presentationDeadline).
895 //
896 // Normally it's one full refresh period (to give SF a chance to
897 // latch the buffer), but this can be reduced by configuring a
898 // DispSync offset. Any additional delays introduced by the hardware
899 // composer or panel must be accounted for here.
900 //
901 // We add an additional 1ms to allow for processing time and
902 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800903 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800904 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700905
906 // All non-virtual displays are currently considered secure.
907 info.secure = true;
908
Iris Chang7501ed62018-04-30 14:45:42 +0800909 if (type == DisplayDevice::DISPLAY_PRIMARY &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700910 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800911 std::swap(info.w, info.h);
912 }
913
Michael Wright28f24d02016-07-12 13:30:53 -0700914 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700915 }
916
Dan Stoza7f7da322014-05-02 15:26:25 -0700917 return NO_ERROR;
918}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700919
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700920status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
921 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700922 return BAD_VALUE;
923 }
924
Ana Krulece588e312018-09-18 12:32:24 -0700925 // FIXME for now we always return stats for the primary display.
926 if (mUseScheduler) {
927 mScheduler->getDisplayStatInfo(stats);
928 } else {
929 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
930 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
931 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700932 return NO_ERROR;
933}
934
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700935int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
936 const auto display = getDisplayDevice(displayToken);
937 if (!display) {
938 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800939 return BAD_VALUE;
940 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700941
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700942 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700943}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700944
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700945void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
946 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700947 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700948 return;
949 }
950
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700951 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700952 ALOGW("Trying to set config for virtual display");
953 return;
954 }
955
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700956 display->setActiveConfig(mode);
957 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700958}
959
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700960status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700961 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700962 Vector<DisplayInfo> configs;
963 getDisplayConfigs(displayToken, &configs);
964 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
965 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
966 configs.size());
967 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700968 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700969 const auto display = getDisplayDevice(displayToken);
970 if (!display) {
971 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
972 displayToken.get());
973 } else if (display->isVirtual()) {
974 ALOGW("Attempt to set active config %d for virtual display", mode);
975 } else {
976 setActiveConfigInternal(display, mode);
977 }
978 }));
979
Mathias Agopian888c8222012-08-04 21:10:38 -0700980 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700981}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700982status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
983 Vector<ColorMode>* outColorModes) {
984 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700985 return BAD_VALUE;
986 }
987
Michael Wright28f24d02016-07-12 13:30:53 -0700988 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700989 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
990 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700991 type = i;
992 break;
993 }
994 }
995
996 if (type < 0) {
997 return type;
998 }
999
Peiyong Lina52f0292018-03-14 17:26:31 -07001000 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001001 {
1002 ConditionalLock _l(mStateLock,
1003 std::this_thread::get_id() != mMainThreadId);
1004 modes = getHwComposer().getColorModes(type);
1005 }
Michael Wright28f24d02016-07-12 13:30:53 -07001006 outColorModes->clear();
1007 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1008
1009 return NO_ERROR;
1010}
1011
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001012ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1013 if (const auto display = getDisplayDevice(displayToken)) {
1014 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001015 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001016 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001017}
1018
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001019void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1020 Dataspace dataSpace, RenderIntent renderIntent) {
1021 ColorMode currentMode = display->getActiveColorMode();
1022 Dataspace currentDataSpace = display->getCompositionDataSpace();
1023 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001024
Peiyong Lin38e9a562018-04-10 16:24:20 -07001025 if (mode == currentMode && dataSpace == currentDataSpace &&
1026 renderIntent == currentRenderIntent) {
1027 return;
1028 }
1029
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001030 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001031 ALOGW("Trying to set config for virtual display");
1032 return;
1033 }
1034
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001035 display->setActiveColorMode(mode);
1036 display->setCompositionDataSpace(dataSpace);
1037 display->setActiveRenderIntent(renderIntent);
1038 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001039
1040 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001041 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1042 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001043}
1044
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001045status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001046 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001047 Vector<ColorMode> modes;
1048 getDisplayColorModes(displayToken, &modes);
1049 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1050 if (mode < ColorMode::NATIVE || !exists) {
1051 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1052 decodeColorMode(mode).c_str(), mode, displayToken.get());
1053 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001054 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001055 const auto display = getDisplayDevice(displayToken);
1056 if (!display) {
1057 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1058 decodeColorMode(mode).c_str(), mode, displayToken.get());
1059 } else if (display->isVirtual()) {
1060 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1061 decodeColorMode(mode).c_str(), mode);
1062 } else {
1063 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1064 RenderIntent::COLORIMETRIC);
1065 }
1066 }));
1067
Michael Wright28f24d02016-07-12 13:30:53 -07001068 return NO_ERROR;
1069}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001070
Svetoslavd85084b2014-03-20 10:28:31 -07001071status_t SurfaceFlinger::clearAnimationFrameStats() {
1072 Mutex::Autolock _l(mStateLock);
1073 mAnimFrameTracker.clearStats();
1074 return NO_ERROR;
1075}
1076
1077status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1078 Mutex::Autolock _l(mStateLock);
1079 mAnimFrameTracker.getStats(outStats);
1080 return NO_ERROR;
1081}
1082
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001083status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1084 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001085 Mutex::Autolock _l(mStateLock);
1086
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001087 const auto display = getDisplayDeviceLocked(displayToken);
1088 if (!display) {
1089 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001090 return BAD_VALUE;
1091 }
1092
Peiyong Linfb069302018-04-25 14:34:31 -07001093 // At this point the DisplayDeivce should already be set up,
1094 // meaning the luminance information is already queried from
1095 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001096 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001097 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1098 capabilities.getDesiredMaxLuminance(),
1099 capabilities.getDesiredMaxAverageLuminance(),
1100 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001101
1102 return NO_ERROR;
1103}
1104
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001105status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001106 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001107 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001108
Chia-I Wu90f669f2017-10-05 14:24:41 -07001109 if (mInjectVSyncs == enable) {
1110 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001111 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001112
Ana Krulec98b5b242018-08-10 15:03:23 -07001113 // TODO(akrulec): Part of the Injector should be refactored, so that it
1114 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001115 if (enable) {
1116 ALOGV("VSync Injections enabled");
1117 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001118 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001119 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001120 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001121 impl::EventThread::InterceptVSyncsCallback(),
1122 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001123 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001124 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001125 } else {
1126 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001127 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001128 }
1129
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001130 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001131 }));
1132
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001133 return NO_ERROR;
1134}
1135
1136status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001137 Mutex::Autolock _l(mStateLock);
1138
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001139 if (!mInjectVSyncs) {
1140 ALOGE("VSync Injections not enabled");
1141 return BAD_VALUE;
1142 }
1143 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1144 ALOGV("Injecting VSync inside SurfaceFlinger");
1145 mVSyncInjector->onInjectSyncEvent(when);
1146 }
1147 return NO_ERROR;
1148}
1149
Lloyd Pique755e3192018-01-31 16:46:15 -08001150status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1151 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001152 // Try to acquire a lock for 1s, fail gracefully
1153 const status_t err = mStateLock.timedLock(s2ns(1));
1154 const bool locked = (err == NO_ERROR);
1155 if (!locked) {
1156 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1157 return TIMED_OUT;
1158 }
1159
1160 outLayers->clear();
1161 mCurrentState.traverseInZOrder([&](Layer* layer) {
1162 outLayers->push_back(layer->getLayerDebugInfo());
1163 });
1164
1165 mStateLock.unlock();
1166 return NO_ERROR;
1167}
1168
Peiyong Linc6780972018-10-28 15:24:08 -07001169status_t SurfaceFlinger::getCompositionPreference(
1170 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1171 Dataspace* outWideColorGamutDataspace,
1172 ui::PixelFormat* outWideColorGamutPixelFormat) const {
1173 *outDataspace = defaultCompositionDataspace;
1174 *outPixelFormat = defaultCompositionPixelFormat;
1175 *outWideColorGamutDataspace = wideColorGamutCompositionDataspace;
1176 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001177 return NO_ERROR;
1178}
1179
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001180// ----------------------------------------------------------------------------
1181
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001182sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1183 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001184 if (mUseScheduler) {
1185 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1186 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1187 } else {
1188 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1189 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001190 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001191 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1192 return mSFEventThread->createEventConnection();
1193 } else {
1194 return mEventThread->createEventConnection();
1195 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001196 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001197}
1198
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001199// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001200
1201void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001202 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001203}
1204
1205void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001206 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001207}
1208
1209void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001210 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001211}
1212
1213void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001214 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001215 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001216}
1217
1218status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001219 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001220 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001221}
1222
1223status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001224 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001225 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001226 if (res == NO_ERROR) {
1227 msg->wait();
1228 }
1229 return res;
1230}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001231
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001232void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001233 do {
1234 waitForEvent();
1235 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001236}
1237
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001238void SurfaceFlinger::enableHardwareVsync() {
1239 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001240 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001241 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001242 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001243 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001244 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001245}
1246
Jesse Hall948fe0c2013-10-14 12:56:09 -07001247void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001248 Mutex::Autolock _l(mHWVsyncLock);
1249
Jesse Hall948fe0c2013-10-14 12:56:09 -07001250 if (makeAvailable) {
1251 mHWVsyncAvailable = true;
1252 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001253 // Hardware vsync is not currently available, so abort the resync
1254 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001255 return;
1256 }
1257
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001258 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1259 if (!getHwComposer().isConnected(displayId)) {
1260 return;
1261 }
1262
1263 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001264 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001265
Ana Krulece588e312018-09-18 12:32:24 -07001266 if (mUseScheduler) {
1267 mScheduler->setVsyncPeriod(period);
1268 } else {
1269 mPrimaryDispSync->reset();
1270 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001271
Ana Krulece588e312018-09-18 12:32:24 -07001272 if (!mPrimaryHWVsyncEnabled) {
1273 mPrimaryDispSync->beginResync();
1274 mEventControlThread->setVsyncEnabled(true);
1275 mPrimaryHWVsyncEnabled = true;
1276 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001277 }
1278}
1279
Jesse Hall948fe0c2013-10-14 12:56:09 -07001280void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001281 Mutex::Autolock _l(mHWVsyncLock);
1282 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001283 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001284 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001285 mPrimaryHWVsyncEnabled = false;
1286 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001287 if (makeUnavailable) {
1288 mHWVsyncAvailable = false;
1289 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001290}
1291
Tim Murray4a4e4a22016-04-19 16:29:23 +00001292void SurfaceFlinger::resyncWithRateLimit() {
1293 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001294
1295 // No explicit locking is needed here since EventThread holds a lock while calling this method
1296 static nsecs_t sLastResyncAttempted = 0;
1297 const nsecs_t now = systemTime();
1298 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001299 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001300 }
Dan Stoza57164302017-05-08 14:03:54 -07001301 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001302}
1303
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001304void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1305 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001306 ATRACE_NAME("SF onVsync");
1307
Steven Thomas3cfac282017-02-06 12:29:30 -08001308 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001309 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001310 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001311 return;
1312 }
1313
1314 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001315 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001316 return;
1317 }
1318
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001319 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1320 // For now, we don't do anything with external display vsyncs.
1321 return;
1322 }
1323
Ana Krulece588e312018-09-18 12:32:24 -07001324 if (mUseScheduler) {
1325 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001326 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001327 bool needsHwVsync = false;
1328 { // Scope for the lock
1329 Mutex::Autolock _l(mHWVsyncLock);
1330 if (mPrimaryHWVsyncEnabled) {
1331 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1332 }
1333 }
1334
1335 if (needsHwVsync) {
1336 enableHardwareVsync();
1337 } else {
1338 disableHardwareVsync(false);
1339 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001340 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001341}
1342
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001343void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001344 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1345 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001346}
1347
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001348void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001349 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001350 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001351 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001352
Lloyd Piqueba04e622017-12-14 17:11:26 -08001353 // Ignore events that do not have the right sequenceId.
1354 if (sequenceId != getBE().mComposerSequenceId) {
1355 return;
1356 }
1357
Steven Thomasb02664d2017-07-26 18:48:28 -07001358 // Only lock if we're not on the main thread. This function is normally
1359 // called on a hwbinder thread, but for the primary display it's called on
1360 // the main thread with the state lock already held, so don't attempt to
1361 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001362 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001363
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001364 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001365
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001366 if (std::this_thread::get_id() == mMainThreadId) {
1367 // Process all pending hot plug events immediately if we are on the main thread.
1368 processDisplayHotplugEventsLocked();
1369 }
1370
Lloyd Piqueba04e622017-12-14 17:11:26 -08001371 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001372}
1373
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001374void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001375 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001376 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001377 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001378 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001379 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001380}
1381
Dan Stoza9e56aa02015-11-02 13:00:03 -08001382void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001383 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001384 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001385 getHwComposer().setVsyncEnabled(disp,
1386 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001387}
1388
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001389// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001390void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001391 if (mUseScheduler) {
1392 mScheduler->disableHardwareVsync(true);
1393 } else {
1394 disableHardwareVsync(true);
1395 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001396 // Clear the drawing state so that the logic inside of
1397 // handleTransactionLocked will fire. It will determine the delta between
1398 // mCurrentState and mDrawingState and re-apply all changes when we make the
1399 // transition.
1400 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001401 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001402 mDisplays.clear();
1403}
1404
Steven Thomas050b2c82017-03-06 11:45:16 -08001405void SurfaceFlinger::updateVrFlinger() {
1406 if (!mVrFlinger)
1407 return;
1408 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001409 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001410 return;
1411 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001412
David Sodman105b7dc2017-11-04 20:28:14 -07001413 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001414 ALOGE("Vr flinger is only supported for remote hardware composer"
1415 " service connections. Ignoring request to transition to vr"
1416 " flinger.");
1417 mVrFlingerRequestsDisplay = false;
1418 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001419 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001420
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001421 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001422
Steven Thomas0123ac62018-07-12 11:32:34 -07001423 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001424 LOG_ALWAYS_FATAL_IF(!display);
1425 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001426 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1427 // called below. Clear the reference now so we don't accidentally use it
1428 // later.
1429 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001430
Steven Thomasb02664d2017-07-26 18:48:28 -07001431 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001432 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001433 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001434
Steven Thomasb02664d2017-07-26 18:48:28 -07001435 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001436 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Pique90c115d2018-09-18 21:39:42 -07001437 getBE().mHwc = getFactory().createHWComposer(
1438 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -07001439 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001440
David Sodman105b7dc2017-11-04 20:28:14 -07001441 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1442 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001443
1444 if (vrFlingerRequestsDisplay) {
1445 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001446 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001447
1448 mVisibleRegionsDirty = true;
1449 invalidateHwcGeometry();
1450
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001451 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001452 display = getDefaultDisplayDeviceLocked();
1453 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001454 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001455
Steven Thomasb02664d2017-07-26 18:48:28 -07001456 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001457 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001458 const nsecs_t period = activeConfig->getVsyncPeriod();
1459 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001460
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001461 // The present fences returned from vr_hwc are not an accurate
1462 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001463 if (mUseScheduler) {
1464 mScheduler->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() || !hasSyncFramework);
1465 } else {
1466 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1467 !hasSyncFramework);
1468 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001469
Steven Thomasb02664d2017-07-26 18:48:28 -07001470 // Use phase of 0 since phase is not known.
1471 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001472 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1473 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001474
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001475 resyncToHardwareVsync(false);
1476
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001477 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001478 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001479}
1480
Mathias Agopian4fec8732012-06-29 14:12:52 -07001481void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001482 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001483 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001484 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001485 bool frameMissed = !mHadClientComposition &&
1486 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001487 (mPreviousPresentFence->getSignalTime() ==
1488 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001489 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001490 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001491 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001492 mTimeStats.incrementMissedFrames();
1493 if (mPropagateBackpressure) {
1494 signalLayerUpdate();
1495 break;
1496 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001497 }
Dan Stoza50182882016-07-08 12:02:20 -07001498
Steven Thomas050b2c82017-03-06 11:45:16 -08001499 // Now that we're going to make it to the handleMessageTransaction()
1500 // call below it's safe to call updateVrFlinger(), which will
1501 // potentially trigger a display handoff.
1502 updateVrFlinger();
1503
Dan Stoza6b9454d2014-11-07 16:00:59 -08001504 bool refreshNeeded = handleMessageTransaction();
1505 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001506 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001507 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001508 // Signal a refresh if a transaction modified the window state,
1509 // a new buffer was latched, or if HWC has requested a full
1510 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001511 signalRefresh();
1512 }
1513 break;
1514 }
1515 case MessageQueue::REFRESH: {
1516 handleMessageRefresh();
1517 break;
1518 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001519 }
1520}
1521
Dan Stoza6b9454d2014-11-07 16:00:59 -08001522bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001523 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001524 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001525 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001526 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001527 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001528 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001529}
1530
Mathias Agopian4fec8732012-06-29 14:12:52 -07001531void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001532 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001533
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001534 mRefreshPending = false;
1535
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001536 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001537 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001538 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001539 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001540 for (const auto& [token, display] : mDisplays) {
1541 beginFrame(display);
1542 prepareFrame(display);
1543 doDebugFlashRegions(display, repaintEverything);
1544 doComposition(display, repaintEverything);
1545 }
1546
Adrian Roos1e1a1282017-11-01 19:05:31 +01001547 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001548 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001549
1550 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001551 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001552
Dan Stozabfbffeb2016-07-21 14:49:33 -07001553 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001554 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001555 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001556 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001557 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001558
Alec Mouri86770e52018-09-24 22:40:58 +00001559 // Setup RenderEngine sync fences if native sync is supported.
1560 if (getBE().mRenderEngine->useNativeFenceSync()) {
1561 if (mHadClientComposition) {
1562 base::unique_fd flushFence(getRenderEngine().flush());
1563 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1564 getBE().flushFence = new Fence(std::move(flushFence));
1565 } else {
1566 // Cleanup for hygiene.
1567 getBE().flushFence = Fence::NO_FENCE;
1568 }
1569 }
1570
Jorim Jaggi90535212018-05-23 23:44:06 +02001571 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001572
David Sodman7e4ae112018-02-09 15:02:28 -08001573 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001574 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001575 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001576 compositionInfo.hwc.hwcLayer = nullptr;
1577 }
David Sodmanba340492018-08-05 21:51:33 -07001578 }
David Sodman7e4ae112018-02-09 15:02:28 -08001579
1580 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001581}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001582
David Sodmanfa9b2af2017-12-24 13:28:59 -08001583
1584bool SurfaceFlinger::handleMessageInvalidate() {
1585 ATRACE_CALL();
1586 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001587}
1588
David Sodman79bba0e2018-08-05 18:07:49 -07001589void SurfaceFlinger::calculateWorkingSet() {
1590 ATRACE_CALL();
1591 ALOGV(__FUNCTION__);
1592
David Sodman79bba0e2018-08-05 18:07:49 -07001593 // build the h/w work list
1594 if (CC_UNLIKELY(mGeometryInvalid)) {
1595 mGeometryInvalid = false;
1596 for (const auto& [token, display] : mDisplays) {
1597 const auto displayId = display->getId();
1598 if (displayId >= 0) {
1599 const Vector<sp<Layer>>& currentLayers(
1600 display->getVisibleLayersSortedByZ());
1601 for (size_t i = 0; i < currentLayers.size(); i++) {
1602 const auto& layer = currentLayers[i];
1603
1604 if (!layer->hasHwcLayer(displayId)) {
1605 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1606 layer->forceClientComposition(displayId);
1607 continue;
1608 }
1609 }
1610
1611 layer->setGeometry(display, i);
1612 if (mDebugDisableHWC || mDebugRegion) {
1613 layer->forceClientComposition(displayId);
1614 }
1615 }
1616 }
1617 }
1618 }
1619
1620 // Set the per-frame data
1621 for (const auto& [token, display] : mDisplays) {
1622 const auto displayId = display->getId();
1623 if (displayId < 0) {
1624 continue;
1625 }
1626
1627 if (mDrawingState.colorMatrixChanged) {
1628 display->setColorTransform(mDrawingState.colorMatrix);
1629 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1630 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1631 "display %d: %d", displayId, result);
1632 }
1633 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1634 if (layer->isHdrY410()) {
1635 layer->forceClientComposition(displayId);
1636 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1637 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1638 !display->hasHDR10Support()) {
1639 layer->forceClientComposition(displayId);
1640 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1641 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1642 !display->hasHLGSupport()) {
1643 layer->forceClientComposition(displayId);
1644 }
1645
Peiyong Lind3788632018-09-18 16:01:31 -07001646 // TODO(b/111562338) remove when composer 2.3 is shipped.
1647 if (layer->hasColorTransform()) {
1648 layer->forceClientComposition(displayId);
1649 }
1650
David Sodman79bba0e2018-08-05 18:07:49 -07001651 if (layer->getForceClientComposition(displayId)) {
1652 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1653 layer->setCompositionType(displayId, HWC2::Composition::Client);
1654 continue;
1655 }
1656
1657 layer->setPerFrameData(display);
1658 }
1659
Peiyong Lin13effd12018-07-24 17:01:47 -07001660 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001661 ColorMode colorMode;
1662 Dataspace dataSpace;
1663 RenderIntent renderIntent;
1664 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1665 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1666 }
1667 }
1668
1669 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001670
1671 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001672 getBE().mCompositionInfo[token].clear();
1673
David Sodmanba340492018-08-05 21:51:33 -07001674 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001675 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001676 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1677 if (!layer->setHwcLayer(displayId)) {
1678 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1679 }
David Sodman15fb96e2018-01-07 10:23:24 -08001680 layer->getBE().compositionInfo.hwc.displayId = displayId;
Dominik Laskowski05275f12018-11-01 15:03:24 -07001681 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001682 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1683 }
1684 }
David Sodman79bba0e2018-08-05 18:07:49 -07001685}
1686
David Sodmanfa9b2af2017-12-24 13:28:59 -08001687void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001688{
1689 // is debugging enabled
1690 if (CC_LIKELY(!mDebugRegion))
1691 return;
1692
David Sodmanfa9b2af2017-12-24 13:28:59 -08001693 if (display->isPoweredOn()) {
1694 // transform the dirty region into this screen's coordinate space
1695 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1696 if (!dirtyRegion.isEmpty()) {
1697 // redraw the whole screen
1698 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001699
David Sodmanfa9b2af2017-12-24 13:28:59 -08001700 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001701 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001702 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001703
David Sodmanfa9b2af2017-12-24 13:28:59 -08001704 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001705 }
1706 }
1707
David Sodmanfa9b2af2017-12-24 13:28:59 -08001708 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001709
1710 if (mDebugRegion > 1) {
1711 usleep(mDebugRegion * 1000);
1712 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001713
Dominik Laskowski05275f12018-11-01 15:03:24 -07001714 prepareFrame(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001715}
1716
Adrian Roos1e1a1282017-11-01 19:05:31 +01001717void SurfaceFlinger::doTracing(const char* where) {
1718 ATRACE_CALL();
1719 ATRACE_NAME(where);
1720 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001721 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001722 }
1723}
1724
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001725void SurfaceFlinger::logLayerStats() {
1726 ATRACE_CALL();
1727 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001728 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001729 if (display->isPrimary()) {
1730 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001731 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001732 }
1733 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001734
1735 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001736 }
1737}
1738
David Sodman2b406362017-12-15 13:33:47 -08001739void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001740{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001741 ATRACE_CALL();
1742 ALOGV("preComposition");
1743
David Sodman2b406362017-12-15 13:33:47 -08001744 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1745
Mathias Agopiancd60f992012-08-16 16:28:27 -07001746 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001747 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001748 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001749 needExtraInvalidate = true;
1750 }
Robert Carr2047fae2016-11-28 14:09:09 -08001751 });
1752
Mathias Agopiancd60f992012-08-16 16:28:27 -07001753 if (needExtraInvalidate) {
1754 signalLayerUpdate();
1755 }
1756}
1757
Ana Krulece588e312018-09-18 12:32:24 -07001758void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1759 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001760 // Update queue of past composite+present times and determine the
1761 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001762 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001763 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001764 while (!getBE().mCompositePresentTimes.empty()) {
1765 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001766 // Cached values should have been updated before calling this method,
1767 // which helps avoid duplicate syscalls.
1768 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1769 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1770 break;
1771 }
1772 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001773 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001774 }
1775
1776 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001777 while (getBE().mCompositePresentTimes.size() > 16) {
1778 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001779 }
1780
Ana Krulece588e312018-09-18 12:32:24 -07001781 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001782}
1783
Ana Krulece588e312018-09-18 12:32:24 -07001784void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1785 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001786 // Integer division and modulo round toward 0 not -inf, so we need to
1787 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001788 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1789 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1790 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001791
Brian Andersond0010582017-03-07 13:20:31 -08001792 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1793 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001794 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001795 }
1796
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001797 // Snap the latency to a value that removes scheduling jitter from the
1798 // composition and present times, which often have >1ms of jitter.
1799 // Reducing jitter is important if an app attempts to extrapolate
1800 // something (such as user input) to an accurate diasplay time.
1801 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1802 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001803 nsecs_t bias = stats.vsyncPeriod / 2;
1804 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1805 nsecs_t snappedCompositeToPresentLatency =
1806 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001807
David Sodman99974d22017-11-28 12:04:33 -08001808 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001809 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1810 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001811 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001812}
1813
David Sodman2b406362017-12-15 13:33:47 -08001814void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001815{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001816 ATRACE_CALL();
1817 ALOGV("postComposition");
1818
Brian Anderson3546a3f2016-07-14 11:51:14 -07001819 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001820 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001821 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001822 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001823 }
1824
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001825 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001826 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001827
David Sodman73beded2017-11-15 11:56:06 -08001828 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001829 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001830 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001831 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001832 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001833 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001834 } else {
1835 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1836 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001837
David Sodman73beded2017-11-15 11:56:06 -08001838 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001839 mPreviousPresentFence =
1840 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1841 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001842 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001843
Ana Krulece588e312018-09-18 12:32:24 -07001844 DisplayStatInfo stats;
1845 if (mUseScheduler) {
1846 mScheduler->getDisplayStatInfo(&stats);
1847 } else {
1848 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1849 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
1850 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001851
David Sodman2b406362017-12-15 13:33:47 -08001852 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001853 // when we started doing work for this frame, but that should be okay
1854 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07001855 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001856 CompositorTiming compositorTiming;
1857 {
David Sodman99974d22017-11-28 12:04:33 -08001858 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1859 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001860 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001861
Robert Carr2047fae2016-11-28 14:09:09 -08001862 mDrawingState.traverseInZOrder([&](Layer* layer) {
1863 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001864 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001865 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001866 recordBufferingStats(layer->getName().string(),
1867 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001868 }
Robert Carr2047fae2016-11-28 14:09:09 -08001869 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001870
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001871 if (presentFenceTime->isValid()) {
Ana Krulece588e312018-09-18 12:32:24 -07001872 if (mUseScheduler) {
1873 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001874 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001875 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
1876 enableHardwareVsync();
1877 } else {
1878 disableHardwareVsync(false);
1879 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001880 }
1881 }
1882
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001883 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001884 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07001885 if (mUseScheduler) {
1886 mScheduler->enableHardwareVsync();
1887 } else {
1888 enableHardwareVsync();
1889 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001890 }
1891 }
1892
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001893 if (mAnimCompositionPending) {
1894 mAnimCompositionPending = false;
1895
Brian Anderson4e606e32017-03-16 15:34:57 -07001896 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001897 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001898 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001899 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001900 // The HWC doesn't support present fences, so use the refresh
1901 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001902 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001903 mAnimFrameTracker.setActualPresentTime(presentTime);
1904 }
1905 mAnimFrameTracker.advanceFrame();
1906 }
Dan Stozab90cf072015-03-05 11:05:59 -08001907
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001908 mTimeStats.incrementTotalFrames();
1909 if (mHadClientComposition) {
1910 mTimeStats.incrementClientCompositionFrames();
1911 }
1912
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001913 mTimeStats.setPresentFenceGlobal(presentFenceTime);
1914
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001915 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001916 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001917 return;
1918 }
1919
1920 nsecs_t currentTime = systemTime();
1921 if (mHasPoweredOff) {
1922 mHasPoweredOff = false;
1923 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001924 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001925 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001926 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1927 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001928 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001929 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001930 }
David Sodman4a36e932017-11-07 14:29:47 -08001931 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001932 }
David Sodman4a36e932017-11-07 14:29:47 -08001933 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001934
1935 {
1936 std::lock_guard lock(mTexturePoolMutex);
1937 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1938 if (refillCount > 0) {
1939 const size_t offset = mTexturePool.size();
1940 mTexturePool.resize(mTexturePoolSize);
1941 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1942 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1943 }
1944 }
Marissa Walle2ffb422018-10-12 11:33:52 -07001945
1946 mTransactionCompletedThread.sendCallbacks();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001947}
1948
1949void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001950 ATRACE_CALL();
1951 ALOGV("rebuildLayerStacks");
1952
Mathias Agopiancd60f992012-08-16 16:28:27 -07001953 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001954 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001955 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001956 mVisibleRegionsDirty = false;
1957 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001958
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001959 for (const auto& pair : mDisplays) {
1960 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001961 Region opaqueRegion;
1962 Region dirtyRegion;
1963 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001964 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001965 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001966 const Rect bounds = display->getBounds();
1967 if (display->isPoweredOn()) {
1968 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001969
Jeff Sharkey76488112017-02-27 14:15:18 -07001970 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001971 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001972 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001973 Region drawRegion(tr.transform(
1974 layer->visibleNonTransparentRegion));
1975 drawRegion.andSelf(bounds);
1976 if (!drawRegion.isEmpty()) {
1977 layersSortedByZ.add(layer);
1978 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001979 // Clear out the HWC layer if this layer was
1980 // previously visible, but no longer is
1981 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001982 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001983 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001984 // WM changes display->layerStack upon sleep/awake.
1985 // Here we make sure we delete the HWC layers even if
1986 // WM changed their layer stack.
1987 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001988 }
1989
1990 // If a layer is not going to get a release fence because
1991 // it is invisible, but it is also going to release its
1992 // old buffer, add it to the list of layers needing
1993 // fences.
1994 if (hwcLayerDestroyed) {
1995 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1996 mLayersWithQueuedFrames.cend(), layer);
1997 if (found != mLayersWithQueuedFrames.cend()) {
1998 layersNeedingFences.add(layer);
1999 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002000 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002001 });
2002 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002003 display->setVisibleLayersSortedByZ(layersSortedByZ);
2004 display->setLayersNeedingFences(layersNeedingFences);
2005 display->undefinedRegion.set(bounds);
2006 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2007 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002008 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002009 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002010}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002011
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002012// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002013// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002014// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002015// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002016// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002017// The returned HDR data space is one of
2018// - Dataspace::UNKNOWN
2019// - Dataspace::BT2020_HLG
2020// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002021Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2022 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07002023 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002024 *outHdrDataSpace = Dataspace::UNKNOWN;
2025
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002026 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002027 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002028 case Dataspace::V0_SCRGB:
2029 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002030 case Dataspace::BT2020:
2031 case Dataspace::BT2020_ITU:
2032 case Dataspace::BT2020_LINEAR:
2033 case Dataspace::DISPLAY_BT2020:
2034 bestDataSpace = Dataspace::DISPLAY_BT2020;
2035 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002036 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002037 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002038 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002039 case Dataspace::BT2020_PQ:
2040 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002041 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002042 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002043 case Dataspace::BT2020_HLG:
2044 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002045 // When there's mixed PQ content and HLG content, we set the HDR
2046 // data space to be BT2020_PQ and convert HLG to PQ.
2047 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2048 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002049 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002050 break;
2051 default:
2052 break;
2053 }
Romain Guy54f154a2017-10-24 21:40:32 +01002054 }
2055
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002056 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002057}
2058
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002059// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002060void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2061 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002062 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2063 *outMode = ColorMode::NATIVE;
2064 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002065 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002066 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002067 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002068
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002069 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002070 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002071
Peiyong Lindfde5112018-06-05 10:58:41 -07002072 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002073 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002074 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002075 if (isHdr) {
2076 bestDataSpace = hdrDataSpace;
2077 }
2078
Chia-I Wu0d711262018-05-21 15:19:35 -07002079 RenderIntent intent;
2080 switch (mDisplayColorSetting) {
2081 case DisplayColorSetting::MANAGED:
2082 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002083 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002084 break;
2085 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002086 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002087 break;
2088 default: // vendor display color setting
2089 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2090 break;
2091 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002092
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002093 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002094}
2095
David Sodmanfa9b2af2017-12-24 13:28:59 -08002096void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002097{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002098 bool dirty = !display->getDirtyRegion(false).isEmpty();
2099 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2100 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002101
David Sodmanfa9b2af2017-12-24 13:28:59 -08002102 // If nothing has changed (!dirty), don't recompose.
2103 // If something changed, but we don't currently have any visible layers,
2104 // and didn't when we last did a composition, then skip it this time.
2105 // The second rule does two things:
2106 // - When all layers are removed from a display, we'll emit one black
2107 // frame, then nothing more until we get new layers.
2108 // - When a display is created with a private layer stack, we won't
2109 // emit any black frames until a layer is added to the layer stack.
2110 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002111
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002112 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2113 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002114 mustRecompose ? "doing" : "skipping",
2115 dirty ? "+" : "-",
2116 empty ? "+" : "-",
2117 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002118
David Sodmanfa9b2af2017-12-24 13:28:59 -08002119 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002120
David Sodmanfa9b2af2017-12-24 13:28:59 -08002121 if (mustRecompose) {
2122 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002123 }
2124}
2125
David Sodmanfa9b2af2017-12-24 13:28:59 -08002126void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002127{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002128 if (!display->isPoweredOn()) {
2129 return;
David Sodman2b406362017-12-15 13:33:47 -08002130 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002131
Dominik Laskowski05275f12018-11-01 15:03:24 -07002132 status_t result = display->prepareFrame(getHwComposer(),
2133 getBE().mCompositionInfo[display->getDisplayToken()]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08002134 ALOGE_IF(result != NO_ERROR,
2135 "prepareFrame for display %d failed:"
2136 " %d (%s)",
2137 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002138}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002139
David Sodmanfa9b2af2017-12-24 13:28:59 -08002140void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002141 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002142 ALOGV("doComposition");
2143
David Sodmanfa9b2af2017-12-24 13:28:59 -08002144 if (display->isPoweredOn()) {
2145 // transform the dirty region into this screen's coordinate space
2146 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002147
David Sodmanfa9b2af2017-12-24 13:28:59 -08002148 // repaint the framebuffer (if needed)
2149 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002150
David Sodmanfa9b2af2017-12-24 13:28:59 -08002151 display->dirtyRegion.clear();
2152 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002153 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002154 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002155}
2156
David Sodmanfa9b2af2017-12-24 13:28:59 -08002157void SurfaceFlinger::postFrame()
2158{
2159 // |mStateLock| not needed as we are on the main thread
2160 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2161 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2162 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2163 logFrameStats();
2164 }
2165 }
2166}
2167
2168void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002169{
Mathias Agopian841cde52012-03-01 15:44:37 -08002170 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002171 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002172
David Sodmanfa9b2af2017-12-24 13:28:59 -08002173 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002174
David Sodmanfa9b2af2017-12-24 13:28:59 -08002175 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002176 const auto displayId = display->getId();
2177 if (displayId >= 0) {
2178 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002179 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002180 display->onSwapBuffersCompleted();
2181 display->makeCurrent();
David Sodman15094112018-10-11 09:39:37 -07002182 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002183 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002184
Chia-I Wu7b549592017-11-15 09:14:57 -08002185 // The layer buffer from the previous frame (if any) is released
2186 // by HWC only when the release fence from this frame (if any) is
2187 // signaled. Always get the release fence from HWC first.
David Sodman15094112018-10-11 09:39:37 -07002188 auto hwcLayer = layer->getHwcLayer(displayId);
2189 if (displayId >= 0) {
2190 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002191 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002192
2193 // If the layer was client composited in the previous frame, we
2194 // need to merge with the previous client target acquire fence.
2195 // Since we do not track that, always merge with the current
2196 // client target acquire fence when it is available, even though
2197 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002198 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002199 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002200 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002201 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002202
David Sodman15094112018-10-11 09:39:37 -07002203 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002204 }
Chia-I Wu83806892017-11-16 10:50:20 -08002205
2206 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002207 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002208 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002209 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002210 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002211 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002212 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002213 }
2214 }
2215
Dominik Laskowski7e045462018-05-30 13:02:02 -07002216 if (displayId >= 0) {
2217 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002218 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002219 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002220}
2221
Mathias Agopian87baae12012-07-31 12:38:26 -07002222void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002223{
Mathias Agopian841cde52012-03-01 15:44:37 -08002224 ATRACE_CALL();
2225
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002226 // here we keep a copy of the drawing state (that is the state that's
2227 // going to be overwritten by handleTransactionLocked()) outside of
2228 // mStateLock so that the side-effects of the State assignment
2229 // don't happen with mStateLock held (which can cause deadlocks).
2230 State drawingState(mDrawingState);
2231
Mathias Agopianca4d3602011-05-19 15:38:14 -07002232 Mutex::Autolock _l(mStateLock);
2233 const nsecs_t now = systemTime();
2234 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002235
Mathias Agopianca4d3602011-05-19 15:38:14 -07002236 // Here we're guaranteed that some transaction flags are set
2237 // so we can call handleTransactionLocked() unconditionally.
2238 // We call getTransactionFlags(), which will also clear the flags,
2239 // with mStateLock held to guarantee that mCurrentState won't change
2240 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002241
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002242 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002243 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002244 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002245
Mathias Agopianca4d3602011-05-19 15:38:14 -07002246 mLastTransactionTime = systemTime() - now;
2247 mDebugInTransaction = 0;
2248 invalidateHwcGeometry();
2249 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002250}
2251
Dominik Laskowski7e045462018-05-30 13:02:02 -07002252DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002253 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002254 // Figure out whether the event is for the primary display or an
2255 // external display by matching the Hwc display id against one for a
2256 // connected display. If we did not find a match, we then check what
2257 // displays are not already connected to determine the type. If we don't
2258 // have a connected primary display, we assume the new display is meant to
2259 // be the primary display, and then if we don't have an external display,
2260 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002261 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2262 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002263 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002264 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002265 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002266 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002267 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002268 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002269 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002270 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002271 return DisplayDevice::DISPLAY_EXTERNAL;
2272 }
2273
2274 return DisplayDevice::DISPLAY_ID_INVALID;
2275}
2276
Lloyd Piqueba04e622017-12-14 17:11:26 -08002277void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2278 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002279 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002280 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002281 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002282 continue;
2283 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002284
2285 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2286 ALOGE("External displays are not supported by the vr hardware composer.");
2287 continue;
2288 }
2289
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002290 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002291 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002292 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002293 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002294 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002295
2296 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002297 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002298 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002299 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002300 DisplayDeviceState info;
2301 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002302 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2303 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002304 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002305 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002306 mInterceptor->saveDisplayCreation(info);
2307 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002308 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002309 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002310
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002311 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002312 if (idx >= 0) {
2313 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002314 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002315 mCurrentState.displays.removeItemsAt(idx);
2316 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002317 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002318 }
2319
2320 processDisplayChangesLocked();
2321 }
2322
2323 mPendingHotplugEvents.clear();
2324}
2325
Lloyd Pique99d3da52018-01-22 17:48:03 -08002326sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002327 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002328 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002329 DisplayDeviceCreationArgs creationArgs(this, displayToken, state.type, displayId);
2330 creationArgs.isSecure = state.isSecure;
2331 creationArgs.displaySurface = dispSurface;
2332 creationArgs.hasWideColorGamut = false;
2333 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002334
Peiyong Lin13effd12018-07-24 17:01:47 -07002335 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002336 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002337 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002338 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002339 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002340 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002341
Dominik Laskowski7e045462018-05-30 13:02:02 -07002342 std::vector<RenderIntent> renderIntents =
2343 getHwComposer().getRenderIntents(displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002344 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002345 }
tangrobin6753a022018-08-10 10:58:54 +08002346 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002347
tangrobin6753a022018-08-10 10:58:54 +08002348 if (displayId >= 0) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002349 getHwComposer().getHdrCapabilities(displayId, &creationArgs.hdrCapabilities);
2350 creationArgs.supportedPerFrameMetadata =
2351 getHwComposer().getSupportedPerFrameMetadata(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002352 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002353
Lloyd Pique90c115d2018-09-18 21:39:42 -07002354 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002355 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002356 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002357
2358 /*
2359 * Create our display's surface
2360 */
Peiyong Lin833074a2018-08-28 11:53:54 -07002361 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002362 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002363 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002364 renderSurface->setNativeWindow(nativeWindow.get());
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002365 creationArgs.displayWidth = renderSurface->getWidth();
2366 creationArgs.displayHeight = renderSurface->getHeight();
2367 creationArgs.renderSurface = std::move(renderSurface);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002368
2369 // Make sure that composition can never be stalled by a virtual display
2370 // consumer that isn't processing buffers fast enough. We have to do this
2371 // in two places:
2372 // * Here, in case the display is composed entirely by HWC.
2373 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2374 // window's swap interval in eglMakeCurrent, so they'll override the
2375 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002376 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002377 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2378 }
2379
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002380 creationArgs.displayInstallOrientation = state.type == DisplayDevice::DISPLAY_PRIMARY
2381 ? primaryDisplayOrientation
2382 : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002383
Lloyd Pique99d3da52018-01-22 17:48:03 -08002384 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002385 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002386
Lloyd Pique90c115d2018-09-18 21:39:42 -07002387 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002388
2389 if (maxFrameBufferAcquiredBuffers >= 3) {
2390 nativeWindowSurface->preallocateBuffers();
2391 }
2392
2393 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002394 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002395 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002396 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002397 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002398 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002399 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002400 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002401 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002402 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002403 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002404 display->setLayerStack(state.layerStack);
2405 display->setProjection(state.orientation, state.viewport, state.frame);
2406 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002407
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002408 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002409}
2410
Lloyd Pique347200f2017-12-14 17:00:15 -08002411void SurfaceFlinger::processDisplayChangesLocked() {
2412 // here we take advantage of Vector's copy-on-write semantics to
2413 // improve performance by skipping the transaction entirely when
2414 // know that the lists are identical
2415 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2416 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2417 if (!curr.isIdenticalTo(draw)) {
2418 mVisibleRegionsDirty = true;
2419 const size_t cc = curr.size();
2420 size_t dc = draw.size();
2421
2422 // find the displays that were removed
2423 // (ie: in drawing state but not in current state)
2424 // also handle displays that changed
2425 // (ie: displays that are in both lists)
2426 for (size_t i = 0; i < dc;) {
2427 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2428 if (j < 0) {
2429 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002430 // Call makeCurrent() on the primary display so we can
2431 // be sure that nothing associated with this display
2432 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002433 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2434 defaultDisplay->makeCurrent();
2435 }
2436 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2437 display->disconnect(getHwComposer());
2438 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002439 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002440 if (mUseScheduler) {
2441 mScheduler->hotplugReceived(mAppConnectionHandle,
2442 EventThread::DisplayType::Primary, false);
2443 } else {
2444 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2445 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002446 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002447 if (mUseScheduler) {
2448 mScheduler->hotplugReceived(mAppConnectionHandle,
2449 EventThread::DisplayType::External, false);
2450 } else {
2451 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2452 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002453 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002454 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002455 } else {
2456 // this display is in both lists. see if something changed.
2457 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002458 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002459 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2460 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2461 if (state_binder != draw_binder) {
2462 // changing the surface is like destroying and
2463 // recreating the DisplayDevice, so we just remove it
2464 // from the drawing state, so that it get re-added
2465 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002466 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2467 display->disconnect(getHwComposer());
2468 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002469 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002470 mDrawingState.displays.removeItemsAt(i);
2471 dc--;
2472 // at this point we must loop to the next item
2473 continue;
2474 }
2475
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002476 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002477 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002478 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002479 }
2480 if ((state.orientation != draw[i].orientation) ||
2481 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002482 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002483 }
2484 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002485 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002486 }
2487 }
2488 }
2489 ++i;
2490 }
2491
2492 // find displays that were added
2493 // (ie: in current state but not in drawing state)
2494 for (size_t i = 0; i < cc; i++) {
2495 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2496 const DisplayDeviceState& state(curr[i]);
2497
2498 sp<DisplaySurface> dispSurface;
2499 sp<IGraphicBufferProducer> producer;
2500 sp<IGraphicBufferProducer> bqProducer;
2501 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002502 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002503
Dominik Laskowski7e045462018-05-30 13:02:02 -07002504 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002505 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002506 // Virtual displays without a surface are dormant:
2507 // they have external state (layer stack, projection,
2508 // etc.) but no internal state (i.e. a DisplayDevice).
2509 if (state.surface != nullptr) {
2510 // Allow VR composer to use virtual displays.
2511 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2512 int width = 0;
2513 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2514 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2515 int height = 0;
2516 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2517 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2518 int intFormat = 0;
2519 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2520 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002521 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002522
Dominik Laskowski7e045462018-05-30 13:02:02 -07002523 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2524 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002525 }
2526
2527 // TODO: Plumb requested format back up to consumer
2528
2529 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002530 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002531 bqProducer, bqConsumer,
2532 state.displayName);
2533
2534 dispSurface = vds;
2535 producer = vds;
2536 }
2537 } else {
2538 ALOGE_IF(state.surface != nullptr,
2539 "adding a supported display, but rendering "
2540 "surface is provided (%p), ignoring it",
2541 state.surface.get());
2542
Dominik Laskowski7e045462018-05-30 13:02:02 -07002543 displayId = state.type;
2544 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002545 producer = bqProducer;
2546 }
2547
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002548 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002549 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002550 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002551 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002552 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002553 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002554 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002555 if (mUseScheduler) {
2556 mScheduler->hotplugReceived(mAppConnectionHandle,
2557 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002558 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002559 } else {
2560 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2561 true);
2562 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002563 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002564 if (mUseScheduler) {
2565 mScheduler->hotplugReceived(mAppConnectionHandle,
2566 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002567 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002568 } else {
2569 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2570 true);
2571 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002572 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002573 }
2574 }
2575 }
2576 }
2577 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002578
2579 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002580}
2581
Mathias Agopian87baae12012-07-31 12:38:26 -07002582void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002583{
Dan Stoza7dde5992015-05-22 09:51:44 -07002584 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002585 mCurrentState.traverseInZOrder([](Layer* layer) {
2586 layer->notifyAvailableFrames();
2587 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002588
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002589 /*
2590 * Traversal of the children
2591 * (perform the transaction for each of them if needed)
2592 */
2593
Mathias Agopian3559b072012-08-15 13:46:03 -07002594 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002595 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002596 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002597 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002598
2599 const uint32_t flags = layer->doTransaction(0);
2600 if (flags & Layer::eVisibleRegion)
2601 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002602 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002603 }
2604
2605 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002606 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002607 */
2608
Mathias Agopiane57f2922012-08-09 16:29:12 -07002609 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002610 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002611 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002612 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002613
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002614 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002615 // The transform hint might have changed for some layers
2616 // (either because a display has changed, or because a layer
2617 // as changed).
2618 //
2619 // Walk through all the layers in currentLayers,
2620 // and update their transform hint.
2621 //
2622 // If a layer is visible only on a single display, then that
2623 // display is used to calculate the hint, otherwise we use the
2624 // default display.
2625 //
2626 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2627 // the hint is set before we acquire a buffer from the surface texture.
2628 //
2629 // NOTE: layer transactions have taken place already, so we use their
2630 // drawing state. However, SurfaceFlinger's own transaction has not
2631 // happened yet, so we must use the current state layer list
2632 // (soon to become the drawing state list).
2633 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002634 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002635 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002636 bool first = true;
2637 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002638 // NOTE: we rely on the fact that layers are sorted by
2639 // layerStack first (so we don't have to traverse the list
2640 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002641 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002642 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002643 currentlayerStack = layerStack;
2644 // figure out if this layerstack is mirrored
2645 // (more than one display) if so, pick the default display,
2646 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002647 hintDisplay = nullptr;
2648 for (const auto& [token, display] : mDisplays) {
2649 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2650 if (hintDisplay) {
2651 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002652 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002653 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002654 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002655 }
2656 }
2657 }
2658 }
Chet Haase91d25932013-04-11 15:24:55 -07002659
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002660 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002661 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2662 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002663
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002664 // could be null when this layer is using a layerStack
2665 // that is not visible on any display. Also can occur at
2666 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002667 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002668 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002669
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002670 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002671 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002672 if (hintDisplay) {
2673 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002674 }
Robert Carr2047fae2016-11-28 14:09:09 -08002675
2676 first = false;
2677 });
Mathias Agopian84300952012-11-21 16:02:13 -08002678 }
2679
2680
Mathias Agopian3559b072012-08-15 13:46:03 -07002681 /*
2682 * Perform our own transaction if needed
2683 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002684
2685 if (mLayersAdded) {
2686 mLayersAdded = false;
2687 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002688 mVisibleRegionsDirty = true;
2689 }
2690
2691 // some layers might have been removed, so
2692 // we need to update the regions they're exposing.
2693 if (mLayersRemoved) {
2694 mLayersRemoved = false;
2695 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002696 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002697 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002698 // this layer is not visible anymore
2699 // TODO: we could traverse the tree from front to back and
2700 // compute the actual visible region
2701 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002702 Region visibleReg;
2703 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002704 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002705 }
Robert Carr2047fae2016-11-28 14:09:09 -08002706 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002707 }
2708
2709 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002710
2711 updateCursorAsync();
2712}
2713
2714void SurfaceFlinger::updateCursorAsync()
2715{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002716 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002717 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002718 continue;
2719 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002720
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002721 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2722 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002723 }
2724 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002725}
2726
2727void SurfaceFlinger::commitTransaction()
2728{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002729 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002730 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002731 for (const auto& l : mLayersPendingRemoval) {
2732 recordBufferingStats(l->getName().string(),
2733 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002734
2735 // We need to release the HWC layers when the Layer is removed
2736 // from the current state otherwise the HWC layer just continues
2737 // showing at its last configured state until we eventually
2738 // abandon the buffer queue.
2739 if (l->isRemovedFromCurrentState()) {
2740 l->destroyAllHwcLayers();
2741 l->releasePendingBuffer(systemTime());
2742 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002743 }
2744 mLayersPendingRemoval.clear();
2745 }
2746
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002747 // If this transaction is part of a window animation then the next frame
2748 // we composite should be considered an animation as well.
2749 mAnimCompositionPending = mAnimTransactionPending;
2750
Mathias Agopian4fec8732012-06-29 14:12:52 -07002751 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002752 // clear the "changed" flags in current state
2753 mCurrentState.colorMatrixChanged = false;
2754
Robert Carr1f0a16a2016-10-24 16:27:39 -07002755 mDrawingState.traverseInZOrder([](Layer* layer) {
2756 layer->commitChildList();
2757 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002758 mTransactionPending = false;
2759 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002760 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002761}
2762
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002763void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2764 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002765 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002766 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002767
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002768 Region aboveOpaqueLayers;
2769 Region aboveCoveredLayers;
2770 Region dirty;
2771
Mathias Agopian87baae12012-07-31 12:38:26 -07002772 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002773
Robert Carr2047fae2016-11-28 14:09:09 -08002774 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002775 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002776 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002777
Jesse Hall01e29052013-02-19 16:13:35 -08002778 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002779 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002780 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002781 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002782
Mathias Agopianab028732010-03-16 16:41:46 -07002783 /*
2784 * opaqueRegion: area of a surface that is fully opaque.
2785 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002786 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002787
2788 /*
2789 * visibleRegion: area of a surface that is visible on screen
2790 * and not fully transparent. This is essentially the layer's
2791 * footprint minus the opaque regions above it.
2792 * Areas covered by a translucent surface are considered visible.
2793 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002794 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002795
2796 /*
2797 * coveredRegion: area of a surface that is covered by all
2798 * visible regions above it (which includes the translucent areas).
2799 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002800 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002801
Jesse Halla8026d22012-09-25 13:25:04 -07002802 /*
2803 * transparentRegion: area of a surface that is hinted to be completely
2804 * transparent. This is only used to tell when the layer has no visible
2805 * non-transparent regions and can be removed from the layer list. It
2806 * does not affect the visibleRegion of this layer or any layers
2807 * beneath it. The hint may not be correct if apps don't respect the
2808 * SurfaceView restrictions (which, sadly, some don't).
2809 */
2810 Region transparentRegion;
2811
Mathias Agopianab028732010-03-16 16:41:46 -07002812
2813 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002814 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002815 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002816 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002817 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002818 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002819 if (!visibleRegion.isEmpty()) {
2820 // Remove the transparent area from the visible region
2821 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002822 if (tr.preserveRects()) {
2823 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002824 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002825 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002826 // transformation too complex, can't do the
2827 // transparent region optimization.
2828 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002829 }
Mathias Agopianab028732010-03-16 16:41:46 -07002830 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002831
Mathias Agopianab028732010-03-16 16:41:46 -07002832 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002833 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002834 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002835 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002836 // the opaque region is the layer's footprint
2837 opaqueRegion = visibleRegion;
2838 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002839 }
2840 }
2841
Robert Carre5f4f692018-01-12 13:12:28 -08002842 if (visibleRegion.isEmpty()) {
2843 layer->clearVisibilityRegions();
2844 return;
2845 }
2846
Mathias Agopianab028732010-03-16 16:41:46 -07002847 // Clip the covered region to the visible region
2848 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2849
2850 // Update aboveCoveredLayers for next (lower) layer
2851 aboveCoveredLayers.orSelf(visibleRegion);
2852
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002853 // subtract the opaque region covered by the layers above us
2854 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002855
2856 // compute this layer's dirty region
2857 if (layer->contentDirty) {
2858 // we need to invalidate the whole region
2859 dirty = visibleRegion;
2860 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002861 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002862 layer->contentDirty = false;
2863 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002864 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002865 * the exposed region consists of two components:
2866 * 1) what's VISIBLE now and was COVERED before
2867 * 2) what's EXPOSED now less what was EXPOSED before
2868 *
2869 * note that (1) is conservative, we start with the whole
2870 * visible region but only keep what used to be covered by
2871 * something -- which mean it may have been exposed.
2872 *
2873 * (2) handles areas that were not covered by anything but got
2874 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002875 */
Mathias Agopianab028732010-03-16 16:41:46 -07002876 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002877 const Region oldVisibleRegion = layer->visibleRegion;
2878 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002879 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2880 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002881 }
2882 dirty.subtractSelf(aboveOpaqueLayers);
2883
2884 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002885 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002886
Mathias Agopianab028732010-03-16 16:41:46 -07002887 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002888 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002889
Jesse Halla8026d22012-09-25 13:25:04 -07002890 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002891 layer->setVisibleRegion(visibleRegion);
2892 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002893 layer->setVisibleNonTransparentRegion(
2894 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002895 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002896
Mathias Agopian87baae12012-07-31 12:38:26 -07002897 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002898}
2899
Chia-I Wuab0c3192017-08-01 11:29:00 -07002900void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002901 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002902 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2903 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002904 }
2905 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002906}
2907
Dan Stoza6b9454d2014-11-07 16:00:59 -08002908bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002909{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002910 ALOGV("handlePageFlip");
2911
Brian Andersond6927fb2016-07-23 23:37:30 -07002912 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002913
Mathias Agopian4fec8732012-06-29 14:12:52 -07002914 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002915 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002916 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002917
2918 // Store the set of layers that need updates. This set must not change as
2919 // buffers are being latched, as this could result in a deadlock.
2920 // Example: Two producers share the same command stream and:
2921 // 1.) Layer 0 is latched
2922 // 2.) Layer 0 gets a new frame
2923 // 2.) Layer 1 gets a new frame
2924 // 3.) Layer 1 is latched.
2925 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2926 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002927 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002928 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002929 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002930 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2931 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002932 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002933 } else {
2934 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002935 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002936 } else {
2937 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002938 }
Robert Carr2047fae2016-11-28 14:09:09 -08002939 });
2940
Dan Stoza9e56aa02015-11-02 13:00:03 -08002941 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri86770e52018-09-24 22:40:58 +00002942 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
Dan Stozaee44edd2015-03-23 15:50:23 -07002943 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002944 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002945 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002946 newDataLatched = true;
2947 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002948 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002949
Alec Mouri86770e52018-09-24 22:40:58 +00002950 // Clear the renderengine fence here...
2951 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
2952 // clear instead of sp::clear.
2953 getBE().flushFence = Fence::NO_FENCE;
2954
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002955 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002956
2957 // If we will need to wake up at some time in the future to deal with a
2958 // queued frame that shouldn't be displayed during this vsync period, wake
2959 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002960 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002961 signalLayerUpdate();
2962 }
2963
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002964 // enter boot animation on first buffer latch
2965 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2966 ALOGI("Enter boot animation");
2967 mBootStage = BootStage::BOOTANIMATION;
2968 }
2969
Dan Stoza6b9454d2014-11-07 16:00:59 -08002970 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002971 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002972}
2973
Mathias Agopianad456f92011-01-13 17:53:01 -08002974void SurfaceFlinger::invalidateHwcGeometry()
2975{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002976 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002977}
2978
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002979void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2980 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002981 // We only need to actually compose the display if:
2982 // 1) It is being handled by hardware composer, which may need this to
2983 // keep its virtual display state machine in sync, or
2984 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002985 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002986 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002987 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002988 return;
2989 }
2990
Dan Stoza9e56aa02015-11-02 13:00:03 -08002991 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002992 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002993
2994 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002995 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002996}
2997
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002998bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002999 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003000
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003001 const Region bounds(display->bounds());
3002 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003003 const auto displayId = display->getId();
3004 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003005 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003006
Peiyong Lind3788632018-09-18 16:01:31 -07003007 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003008 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003009 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003010
Dan Stoza9e56aa02015-11-02 13:00:03 -08003011 if (hasClientComposition) {
3012 ALOGV("hasClientComposition");
3013
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003014 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003015 if (display->hasWideColorGamut()) {
3016 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003017 }
3018 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003019 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003020 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003021
Dominik Laskowski7e045462018-05-30 13:02:02 -07003022 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003023 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3024 HWC2::Capability::SkipClientColorTransform);
3025
Peiyong Lind3788632018-09-18 16:01:31 -07003026 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003027 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3028 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003029 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003030 }
3031
Chia-I Wud49d6692018-06-27 07:17:41 +08003032 // The current enhanced saturation matrix is designed to enhance Display P3,
3033 // thus we only apply this matrix when the render intent is not colorimetric
3034 // and the output color space is Display P3.
3035 needsEnhancedColorMatrix =
3036 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3037 outputDataspace == Dataspace::DISPLAY_P3);
3038 if (needsEnhancedColorMatrix) {
3039 colorMatrix *= mEnhancedSaturationMatrix;
3040 }
3041
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003042 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003043 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003044 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003045 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003046
3047 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003048 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3049 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3050 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003051 }
3052 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003053 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003054
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003055 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003056 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003057 // when using overlays, we assume a fully transparent framebuffer
3058 // NOTE: we could reduce how much we need to clear, for instance
3059 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003060 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003061 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003062 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003063 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003064 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003065 // we're left with the letterbox region
3066 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003067 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003068
3069 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003070 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003071
Mathias Agopianb9494d52012-04-18 02:28:45 -07003072 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003073 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003074 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003075 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003076 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003077 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003078
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003079 const Rect& bounds = display->getBounds();
3080 const Rect& scissor = display->getScissor();
3081 if (scissor != bounds) {
3082 // scissor doesn't match the screen's dimensions, so we
3083 // need to clear everything outside of it and enable
3084 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003085
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003086 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003087 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003088 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003089 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003090
Mathias Agopian85d751c2012-08-29 16:59:24 -07003091 /*
3092 * and then, render the layers targeted at the framebuffer
3093 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003094
Dan Stoza9e56aa02015-11-02 13:00:03 -08003095 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003096 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003097 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003098 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003099 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003100 displayTransform.transform(layer->visibleRegion)));
3101 ALOGV("Layer: %s", layer->getName().string());
3102 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003103 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003104 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003105 case HWC2::Composition::Cursor:
3106 case HWC2::Composition::Device:
3107 case HWC2::Composition::Sideband:
3108 case HWC2::Composition::SolidColor: {
David Sodmanc1498e62018-09-12 14:36:26 -07003109 const Layer::State& state(layer->getDrawingState());
3110 if (layer->getClearClientTarget(displayId) && !firstLayer &&
3111 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3112 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003113 // never clear the very first layer since we're
3114 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003115 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003116 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003117 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003118 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003119 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003120 if (layer->hasColorTransform()) {
3121 mat4 tmpMatrix;
3122 if (applyColorMatrix) {
3123 tmpMatrix = mDrawingState.colorMatrix;
3124 }
3125 tmpMatrix *= layer->getColorTransform();
3126 if (needsEnhancedColorMatrix) {
3127 tmpMatrix *= mEnhancedSaturationMatrix;
3128 }
3129 getRenderEngine().setColorTransform(tmpMatrix);
3130 } else {
3131 getRenderEngine().setColorTransform(colorMatrix);
3132 }
David Sodmanc1498e62018-09-12 14:36:26 -07003133 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003134 break;
3135 }
3136 default:
3137 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003138 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003139 } else {
3140 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003141 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003142 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003143 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003144
Peiyong Lind3788632018-09-18 16:01:31 -07003145 // Clear color transform matrix at the end of the frame.
3146 getRenderEngine().setColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003147
Mathias Agopianf45c5102012-10-24 16:29:17 -07003148 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003149 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003150 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003151}
3152
Chia-I Wu28e3a252018-09-07 12:05:02 -07003153void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003154 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003155 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003156}
3157
Dan Stoza7d89d062015-04-30 13:29:25 -07003158status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003159 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003160 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003161 const sp<Layer>& lbc,
3162 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003163{
Dan Stoza7d89d062015-04-30 13:29:25 -07003164 // add this layer to the current state list
3165 {
3166 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003167 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003168 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3169 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003170 return NO_MEMORY;
3171 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003172 if (parent == nullptr) {
3173 mCurrentState.layersSortedByZ.add(lbc);
3174 } else {
Robert Carr2e102c92018-10-23 12:11:15 -07003175 if (parent->isRemovedFromCurrentState()) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003176 ALOGE("addClientLayer called with a removed parent");
3177 return NAME_NOT_FOUND;
3178 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003179 parent->addChild(lbc);
3180 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003181
Yiwei Zhang243b3782018-05-15 17:40:04 -07003182 if (gbc != nullptr) {
3183 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3184 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3185 mMaxGraphicBufferProducerListSize,
3186 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3187 mGraphicBufferProducerList.size(),
3188 mMaxGraphicBufferProducerListSize, mNumLayers);
3189 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003190 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003191 }
3192
Mathias Agopian96f08192010-06-02 23:28:45 -07003193 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003194 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003195
Dan Stoza7d89d062015-04-30 13:29:25 -07003196 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003197}
3198
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003199status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003200 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003201 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3202}
Robert Carr7f9b8992017-03-10 11:08:39 -08003203
Robert Carr2e102c92018-10-23 12:11:15 -07003204status_t SurfaceFlinger::removeLayerLocked(const Mutex& lock, const sp<Layer>& layer,
chaviwca27f252018-02-06 16:46:39 -08003205 bool topLevelOnly) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003206 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003207 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003208 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003209 if (topLevelOnly) {
3210 return NO_ERROR;
3211 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003212 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003213 } else {
3214 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003215 }
3216
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003217 layer->onRemovedFromCurrentState();
Robert Carr2e102c92018-10-23 12:11:15 -07003218
3219 markLayerPendingRemovalLocked(lock, layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003220 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003221}
3222
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003223uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003224 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003225}
3226
Mathias Agopian3f844832013-08-07 21:24:32 -07003227uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003228 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003229}
3230
Mathias Agopian3f844832013-08-07 21:24:32 -07003231uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003232 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003233}
3234
3235uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003236 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003237 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003238 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003239 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003240 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003241 }
3242 return old;
3243}
3244
chaviwca27f252018-02-06 16:46:39 -08003245bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3246 for (const ComposerState& state : states) {
3247 // Here we need to check that the interface we're given is indeed
3248 // one of our own. A malicious client could give us a nullptr
3249 // IInterface, or one of its own or even one of our own but a
3250 // different type. All these situations would cause us to crash.
3251 if (state.client == nullptr) {
3252 return true;
3253 }
3254
3255 sp<IBinder> binder = IInterface::asBinder(state.client);
3256 if (binder == nullptr) {
3257 return true;
3258 }
3259
3260 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3261 return true;
3262 }
3263 }
3264 return false;
3265}
3266
Mathias Agopian8b33f032012-07-24 20:43:54 -07003267void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003268 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003269 const Vector<DisplayState>& displays,
3270 uint32_t flags)
3271{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003272 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003273 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003274 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003275
chaviwca27f252018-02-06 16:46:39 -08003276 if (containsAnyInvalidClientState(states)) {
3277 return;
3278 }
3279
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003280 if (flags & eAnimation) {
3281 // For window updates that are part of an animation we must wait for
3282 // previous animation "frames" to be handled.
3283 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003284 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003285 if (CC_UNLIKELY(err != NO_ERROR)) {
3286 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003287 // caller after a few seconds.
3288 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3289 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003290 mAnimTransactionPending = false;
3291 break;
3292 }
3293 }
3294 }
3295
chaviwca27f252018-02-06 16:46:39 -08003296 for (const DisplayState& display : displays) {
3297 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003298 }
3299
Marissa Walle2ffb422018-10-12 11:33:52 -07003300 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003301 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003302 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003303 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003304 // If the state doesn't require a traversal and there are callbacks, send them now
3305 if (!(clientStateFlags & eTraversalNeeded)) {
3306 mTransactionCompletedThread.sendCallbacks();
3307 }
3308 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003309
3310 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3311 // as destroyed should only occur after setting all other states. This is to allow for a
3312 // child re-parent to happen before marking its original parent as destroyed (which would
3313 // then mark the child as destroyed).
3314 for (const ComposerState& state : states) {
3315 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003316 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003317
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003318 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3319 // anyway. This can be used as a flush mechanism for previous async transactions.
3320 // Empty animation transaction can be used to simulate back-pressure, so also force a
3321 // transaction for empty animation transactions.
3322 if (transactionFlags == 0 &&
3323 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003324 transactionFlags = eTransactionNeeded;
3325 }
3326
Mathias Agopian386aa982011-11-07 21:58:03 -08003327 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003328 if (mInterceptor->isEnabled()) {
3329 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003330 }
Irvel468051e2016-06-13 16:44:44 -07003331
Mathias Agopian386aa982011-11-07 21:58:03 -08003332 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003333 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3334 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003335 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003336
3337 // if this is a synchronous transaction, wait for it to take effect
3338 // before returning.
3339 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003340 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003341 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003342 if (flags & eAnimation) {
3343 mAnimTransactionPending = true;
3344 }
3345 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003346 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3347 if (CC_UNLIKELY(err != NO_ERROR)) {
3348 // just in case something goes wrong in SF, return to the
3349 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003350 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3351 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003352 break;
3353 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003354 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003355 }
3356}
3357
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003358uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3359 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3360 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003361
Mathias Agopiane57f2922012-08-09 16:29:12 -07003362 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003363 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3364
3365 const uint32_t what = s.what;
3366 if (what & DisplayState::eSurfaceChanged) {
3367 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3368 state.surface = s.surface;
3369 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003370 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003371 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003372 if (what & DisplayState::eLayerStackChanged) {
3373 if (state.layerStack != s.layerStack) {
3374 state.layerStack = s.layerStack;
3375 flags |= eDisplayTransactionNeeded;
3376 }
3377 }
3378 if (what & DisplayState::eDisplayProjectionChanged) {
3379 if (state.orientation != s.orientation) {
3380 state.orientation = s.orientation;
3381 flags |= eDisplayTransactionNeeded;
3382 }
3383 if (state.frame != s.frame) {
3384 state.frame = s.frame;
3385 flags |= eDisplayTransactionNeeded;
3386 }
3387 if (state.viewport != s.viewport) {
3388 state.viewport = s.viewport;
3389 flags |= eDisplayTransactionNeeded;
3390 }
3391 }
3392 if (what & DisplayState::eDisplaySizeChanged) {
3393 if (state.width != s.width) {
3394 state.width = s.width;
3395 flags |= eDisplayTransactionNeeded;
3396 }
3397 if (state.height != s.height) {
3398 state.height = s.height;
3399 flags |= eDisplayTransactionNeeded;
3400 }
3401 }
3402
Mathias Agopiane57f2922012-08-09 16:29:12 -07003403 return flags;
3404}
3405
Robert Carrd4ae7f32018-06-07 16:10:57 -07003406bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3407 IPCThreadState* ipc = IPCThreadState::self();
3408 const int pid = ipc->getCallingPid();
3409 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003410 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003411 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003412 return false;
3413 }
3414 return true;
3415}
3416
chaviwca27f252018-02-06 16:46:39 -08003417uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3418 const layer_state_t& s = composerState.state;
3419 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3420
Mathias Agopian13127d82013-03-05 17:47:11 -08003421 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003422 if (layer == nullptr) {
3423 return 0;
3424 }
3425
chaviw8b3871a2017-11-01 17:41:01 -07003426 uint32_t flags = 0;
3427
3428 const uint32_t what = s.what;
3429 bool geometryAppliesWithResize =
3430 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003431
3432 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3433 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003434 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003435 layer->pushPendingState();
3436 }
3437
chaviw8b3871a2017-11-01 17:41:01 -07003438 if (what & layer_state_t::ePositionChanged) {
3439 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3440 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003441 }
chaviw8b3871a2017-11-01 17:41:01 -07003442 }
3443 if (what & layer_state_t::eLayerChanged) {
3444 // NOTE: index needs to be calculated before we update the state
3445 const auto& p = layer->getParent();
3446 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003447 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003448 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003449 mCurrentState.layersSortedByZ.removeAt(idx);
3450 mCurrentState.layersSortedByZ.add(layer);
3451 // we need traversal (state changed)
3452 // AND transaction (list changed)
3453 flags |= eTransactionNeeded|eTraversalNeeded;
3454 }
chaviw8b3871a2017-11-01 17:41:01 -07003455 } else {
3456 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003457 flags |= eTransactionNeeded|eTraversalNeeded;
3458 }
3459 }
chaviw8b3871a2017-11-01 17:41:01 -07003460 }
3461 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003462 // NOTE: index needs to be calculated before we update the state
3463 const auto& p = layer->getParent();
3464 if (p == nullptr) {
3465 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3466 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3467 mCurrentState.layersSortedByZ.removeAt(idx);
3468 mCurrentState.layersSortedByZ.add(layer);
3469 // we need traversal (state changed)
3470 // AND transaction (list changed)
3471 flags |= eTransactionNeeded|eTraversalNeeded;
3472 }
3473 } else {
3474 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3475 flags |= eTransactionNeeded|eTraversalNeeded;
3476 }
chaviw8b3871a2017-11-01 17:41:01 -07003477 }
3478 }
3479 if (what & layer_state_t::eSizeChanged) {
3480 if (layer->setSize(s.w, s.h)) {
3481 flags |= eTraversalNeeded;
3482 }
3483 }
3484 if (what & layer_state_t::eAlphaChanged) {
3485 if (layer->setAlpha(s.alpha))
3486 flags |= eTraversalNeeded;
3487 }
3488 if (what & layer_state_t::eColorChanged) {
3489 if (layer->setColor(s.color))
3490 flags |= eTraversalNeeded;
3491 }
Peiyong Lind3788632018-09-18 16:01:31 -07003492 if (what & layer_state_t::eColorTransformChanged) {
3493 if (layer->setColorTransform(s.colorTransform)) {
3494 flags |= eTraversalNeeded;
3495 }
3496 }
chaviw8b3871a2017-11-01 17:41:01 -07003497 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003498 // TODO: b/109894387
3499 //
3500 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3501 // rotation. To see the problem observe that if we have a square parent, and a child
3502 // of the same size, then we rotate the child 45 degrees around it's center, the child
3503 // must now be cropped to a non rectangular 8 sided region.
3504 //
3505 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3506 // private API, and the WindowManager only uses rotation in one case, which is on a top
3507 // level layer in which cropping is not an issue.
3508 //
3509 // However given that abuse of rotation matrices could lead to surfaces extending outside
3510 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3511 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3512 // transformations.
3513 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003514 flags |= eTraversalNeeded;
3515 }
3516 if (what & layer_state_t::eTransparentRegionChanged) {
3517 if (layer->setTransparentRegionHint(s.transparentRegion))
3518 flags |= eTraversalNeeded;
3519 }
3520 if (what & layer_state_t::eFlagsChanged) {
3521 if (layer->setFlags(s.flags, s.mask))
3522 flags |= eTraversalNeeded;
3523 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003524 if (what & layer_state_t::eCropChanged_legacy) {
3525 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003526 flags |= eTraversalNeeded;
3527 }
chaviw8b3871a2017-11-01 17:41:01 -07003528 if (what & layer_state_t::eLayerStackChanged) {
3529 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3530 // We only allow setting layer stacks for top level layers,
3531 // everything else inherits layer stack from its parent.
3532 if (layer->hasParent()) {
3533 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3534 layer->getName().string());
3535 } else if (idx < 0) {
3536 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3537 "that also does not appear in the top level layer list. Something"
3538 " has gone wrong.", layer->getName().string());
3539 } else if (layer->setLayerStack(s.layerStack)) {
3540 mCurrentState.layersSortedByZ.removeAt(idx);
3541 mCurrentState.layersSortedByZ.add(layer);
3542 // we need traversal (state changed)
3543 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003544 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003545 }
3546 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003547 if (what & layer_state_t::eDeferTransaction_legacy) {
3548 if (s.barrierHandle_legacy != nullptr) {
3549 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3550 } else if (s.barrierGbp_legacy != nullptr) {
3551 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003552 if (authenticateSurfaceTextureLocked(gbp)) {
3553 const auto& otherLayer =
3554 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003555 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003556 } else {
3557 ALOGE("Attempt to defer transaction to to an"
3558 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003559 }
3560 }
chaviw8b3871a2017-11-01 17:41:01 -07003561 // We don't trigger a traversal here because if no other state is
3562 // changed, we don't want this to cause any more work
3563 }
3564 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003565 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003566 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003567 if (!hadParent) {
3568 mCurrentState.layersSortedByZ.remove(layer);
3569 }
chaviw8b3871a2017-11-01 17:41:01 -07003570 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003571 }
chaviw8b3871a2017-11-01 17:41:01 -07003572 }
3573 if (what & layer_state_t::eReparentChildren) {
3574 if (layer->reparentChildren(s.reparentHandle)) {
3575 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003576 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003577 }
chaviw8b3871a2017-11-01 17:41:01 -07003578 if (what & layer_state_t::eDetachChildren) {
3579 layer->detachChildren();
3580 }
3581 if (what & layer_state_t::eOverrideScalingModeChanged) {
3582 layer->setOverrideScalingMode(s.overrideScalingMode);
3583 // We don't trigger a traversal here because if no other state is
3584 // changed, we don't want this to cause any more work
3585 }
Marissa Wall61c58622018-07-18 10:12:20 -07003586 if (what & layer_state_t::eTransformChanged) {
3587 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3588 }
3589 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3590 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3591 flags |= eTraversalNeeded;
3592 }
3593 if (what & layer_state_t::eCropChanged) {
3594 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3595 }
3596 if (what & layer_state_t::eBufferChanged) {
3597 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3598 }
3599 if (what & layer_state_t::eAcquireFenceChanged) {
3600 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3601 }
3602 if (what & layer_state_t::eDataspaceChanged) {
3603 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3604 }
3605 if (what & layer_state_t::eHdrMetadataChanged) {
3606 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3607 }
3608 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3609 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3610 }
3611 if (what & layer_state_t::eApiChanged) {
3612 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3613 }
3614 if (what & layer_state_t::eSidebandStreamChanged) {
3615 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3616 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003617
3618 std::vector<sp<CallbackHandle>> callbackHandles;
3619 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3620 mTransactionCompletedThread.run();
3621 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3622 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3623 }
3624 }
3625 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3626 // Do not put anything that updates layer state or modifies flags after
3627 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003628 return flags;
3629}
3630
chaviwca27f252018-02-06 16:46:39 -08003631void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3632 const layer_state_t& state = composerState.state;
3633 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3634
3635 sp<Layer> layer(client->getLayerUser(state.surface));
3636 if (layer == nullptr) {
3637 return;
3638 }
3639
chaviwca27f252018-02-06 16:46:39 -08003640 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 =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003756 getFactory().createBufferQueueLayer(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 =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003772 getFactory().createBufferStateLayer(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 Pique90c115d2018-09-18 21:39:42 -07003783 *outLayer = getFactory().createColorLayer(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 Pique90c115d2018-09-18 21:39:42 -07003792 *outLayer =
3793 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003794 *handle = (*outLayer)->getHandle();
3795 return NO_ERROR;
3796}
3797
3798
Mathias Agopianac9fa422013-02-11 16:40:36 -08003799status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003800{
Robert Carr9524cb32017-02-13 11:32:32 -08003801 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003802 status_t err = NO_ERROR;
3803 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003804 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003805 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003806 err = removeLayer(l);
3807 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3808 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003809 }
3810 return err;
3811}
3812
Robert Carr2e102c92018-10-23 12:11:15 -07003813void SurfaceFlinger::markLayerPendingRemovalLocked(const Mutex&, const sp<Layer>& layer) {
3814 mLayersPendingRemoval.add(layer);
3815 mLayersRemoved = true;
3816 setTransactionFlags(eTransactionNeeded);
3817}
3818
3819void SurfaceFlinger::onHandleDestroyed(const sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003820{
Robert Carr2e102c92018-10-23 12:11:15 -07003821 Mutex::Autolock lock(mStateLock);
3822 markLayerPendingRemovalLocked(mStateLock, layer);
Rob Carr4bba3702018-10-08 21:53:30 +00003823}
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
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003975 if (display->isPrimary()) {
3976 mTimeStats.setPowerMode(mode);
3977 }
3978
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003979 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003980}
3981
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003982void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003983 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003984 const auto display = getDisplayDevice(displayToken);
3985 if (!display) {
3986 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3987 displayToken.get());
3988 } else if (display->isVirtual()) {
3989 ALOGW("Attempt to set power mode %d for virtual display", mode);
3990 } else {
3991 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003992 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003993 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003994}
3995
3996// ---------------------------------------------------------------------------
3997
Lloyd Pique755e3192018-01-31 16:46:15 -08003998status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3999 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004000 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004001
Mathias Agopianbd115332013-04-18 16:41:04 -07004002 IPCThreadState* ipc = IPCThreadState::self();
4003 const int pid = ipc->getCallingPid();
4004 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004005
Mathias Agopianbd115332013-04-18 16:41:04 -07004006 if ((uid != AID_SHELL) &&
4007 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004008 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004009 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004010 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004011 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004012 // (this would indicate SF is stuck, but we want to be able to
4013 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004014 status_t err = mStateLock.timedLock(s2ns(1));
4015 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004016 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004017 result.appendFormat(
4018 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4019 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004020 }
4021
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004022 bool dumpAll = true;
4023 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004024 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004025
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004026 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004027 if ((index < numArgs) &&
4028 (args[index] == String16("--list"))) {
4029 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004030 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004031 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004032 }
4033
4034 if ((index < numArgs) &&
4035 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004036 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004037 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004038 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004039 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004040
4041 if ((index < numArgs) &&
4042 (args[index] == String16("--latency-clear"))) {
4043 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004044 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004045 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004046 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004047
4048 if ((index < numArgs) &&
4049 (args[index] == String16("--dispsync"))) {
4050 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004051 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004052 dumpAll = false;
4053 }
Dan Stozab90cf072015-03-05 11:05:59 -08004054
4055 if ((index < numArgs) &&
4056 (args[index] == String16("--static-screen"))) {
4057 index++;
4058 dumpStaticScreenStats(result);
4059 dumpAll = false;
4060 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004061
4062 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004063 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004064 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004065 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004066 dumpAll = false;
4067 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004068
4069 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4070 index++;
4071 dumpWideColorInfo(result);
4072 dumpAll = false;
4073 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004074
4075 if ((index < numArgs) &&
4076 (args[index] == String16("--enable-layer-stats"))) {
4077 index++;
4078 mLayerStats.enable();
4079 dumpAll = false;
4080 }
4081
4082 if ((index < numArgs) &&
4083 (args[index] == String16("--disable-layer-stats"))) {
4084 index++;
4085 mLayerStats.disable();
4086 dumpAll = false;
4087 }
4088
4089 if ((index < numArgs) &&
4090 (args[index] == String16("--clear-layer-stats"))) {
4091 index++;
4092 mLayerStats.clear();
4093 dumpAll = false;
4094 }
4095
4096 if ((index < numArgs) &&
4097 (args[index] == String16("--dump-layer-stats"))) {
4098 index++;
4099 mLayerStats.dump(result);
4100 dumpAll = false;
4101 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004102
4103 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004104 (args[index] == String16("--frame-composition"))) {
4105 index++;
4106 dumpFrameCompositionInfo(result);
4107 dumpAll = false;
4108 }
4109
4110 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004111 (args[index] == String16("--display-identification"))) {
4112 index++;
4113 dumpDisplayIdentificationData(result);
4114 dumpAll = false;
4115 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004116
4117 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4118 index++;
4119 mTimeStats.parseArgs(asProto, args, index, result);
4120 dumpAll = false;
4121 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004122 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004123
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004124 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004125 if (asProto) {
4126 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4127 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4128 } else {
4129 dumpAllLocked(args, index, result);
4130 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004131 }
4132
Mathias Agopian9795c422009-08-26 16:36:26 -07004133 if (locked) {
4134 mStateLock.unlock();
4135 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004136 }
4137 write(fd, result.string(), result.size());
4138 return NO_ERROR;
4139}
4140
Dan Stozac7014012014-02-14 15:03:43 -08004141void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4142 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004143{
Robert Carr2047fae2016-11-28 14:09:09 -08004144 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004145 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004146 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004147}
4148
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004149void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004150 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004151{
4152 String8 name;
4153 if (index < args.size()) {
4154 name = String8(args[index]);
4155 index++;
4156 }
4157
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004158 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4159 getHwComposer().isConnected(displayId)) {
4160 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4161 const nsecs_t period = activeConfig->getVsyncPeriod();
4162 result.appendFormat("%" PRId64 "\n", period);
4163 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004164
4165 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004166 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004167 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004168 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004169 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004170 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004171 }
Robert Carr2047fae2016-11-28 14:09:09 -08004172 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004173 }
4174}
4175
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004176void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004177 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004178{
4179 String8 name;
4180 if (index < args.size()) {
4181 name = String8(args[index]);
4182 index++;
4183 }
4184
Robert Carr2047fae2016-11-28 14:09:09 -08004185 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004186 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004187 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004188 }
Robert Carr2047fae2016-11-28 14:09:09 -08004189 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004190
Svetoslavd85084b2014-03-20 10:28:31 -07004191 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004192}
4193
Jamie Gennis6547ff42013-07-16 20:12:42 -07004194// This should only be called from the main thread. Otherwise it would need
4195// the lock and should use mCurrentState rather than mDrawingState.
4196void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004197 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004198 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004199 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004200
4201 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4202}
4203
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004204void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004205{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004206 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004207
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004208 if (isLayerTripleBufferingDisabled())
4209 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004210
4211 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004212 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004213 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004214 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004215 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4216 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004217 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004218}
4219
Dan Stozab90cf072015-03-05 11:05:59 -08004220void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4221{
4222 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004223 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4224 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004225 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004226 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004227 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4228 b + 1, bucketTimeSec, percent);
4229 }
David Sodman4a36e932017-11-07 14:29:47 -08004230 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004231 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004232 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004233 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004234 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004235}
4236
Dan Stozae77c7662016-05-13 11:37:28 -07004237void SurfaceFlinger::recordBufferingStats(const char* layerName,
4238 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004239 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4240 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004241 for (const auto& segment : history) {
4242 if (!segment.usedThirdBuffer) {
4243 stats.twoBufferTime += segment.totalTime;
4244 }
4245 if (segment.occupancyAverage < 1.0f) {
4246 stats.doubleBufferedTime += segment.totalTime;
4247 } else if (segment.occupancyAverage < 2.0f) {
4248 stats.tripleBufferedTime += segment.totalTime;
4249 }
4250 ++stats.numSegments;
4251 stats.totalTime += segment.totalTime;
4252 }
4253}
4254
Brian Andersond6927fb2016-07-23 23:37:30 -07004255void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4256 result.appendFormat("Layer frame timestamps:\n");
4257
4258 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4259 const size_t count = currentLayers.size();
4260 for (size_t i=0 ; i<count ; i++) {
4261 currentLayers[i]->dumpFrameEvents(result);
4262 }
4263}
4264
Dan Stozae77c7662016-05-13 11:37:28 -07004265void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4266 result.append("Buffering stats:\n");
4267 result.append(" [Layer name] <Active time> <Two buffer> "
4268 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004269 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004270 typedef std::tuple<std::string, float, float, float> BufferTuple;
4271 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004272 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004273 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004274 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004275 if (stats.numSegments == 0) {
4276 continue;
4277 }
4278 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4279 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4280 stats.totalTime;
4281 float doubleBufferRatio = static_cast<float>(
4282 stats.doubleBufferedTime) / stats.totalTime;
4283 float tripleBufferRatio = static_cast<float>(
4284 stats.tripleBufferedTime) / stats.totalTime;
4285 sorted.insert({activeTime, {name, twoBufferRatio,
4286 doubleBufferRatio, tripleBufferRatio}});
4287 }
4288 for (const auto& sortedPair : sorted) {
4289 float activeTime = sortedPair.first;
4290 const BufferTuple& values = sortedPair.second;
4291 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4292 std::get<0>(values).c_str(), activeTime,
4293 std::get<1>(values), std::get<2>(values),
4294 std::get<3>(values));
4295 }
4296 result.append("\n");
4297}
4298
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004299void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004300 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004301 const int32_t displayId = display->getId();
4302 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4303 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004304 continue;
4305 }
4306
Dominik Laskowski7e045462018-05-30 13:02:02 -07004307 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004308 uint8_t port;
4309 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004310 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004311 result.append("no identification data\n");
4312 continue;
4313 }
4314
4315 if (!isEdid(data)) {
4316 result.append("unknown identification data: ");
4317 for (uint8_t byte : data) {
4318 result.appendFormat("%x ", byte);
4319 }
4320 result.append("\n");
4321 continue;
4322 }
4323
4324 const auto edid = parseEdid(data);
4325 if (!edid) {
4326 result.append("invalid EDID: ");
4327 for (uint8_t byte : data) {
4328 result.appendFormat("%x ", byte);
4329 }
4330 result.append("\n");
4331 continue;
4332 }
4333
4334 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4335 result.append(edid->displayName.data(), edid->displayName.length());
4336 result.append("\"\n");
4337 }
4338 result.append("\n");
4339}
4340
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004341void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004342 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4343 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004344 result.appendFormat("DisplayColorSetting: %s\n",
4345 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004346
4347 // TODO: print out if wide-color mode is active or not
4348
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004349 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004350 const int32_t displayId = display->getId();
4351 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004352 continue;
4353 }
4354
Dominik Laskowski7e045462018-05-30 13:02:02 -07004355 result.appendFormat("Display %d color modes:\n", displayId);
4356 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004357 for (auto&& mode : modes) {
4358 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4359 }
4360
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004361 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004362 result.appendFormat(" Current color mode: %s (%d)\n",
4363 decodeColorMode(currentMode).c_str(), currentMode);
4364 }
4365 result.append("\n");
4366}
4367
David Sodman7e4ae112018-02-09 15:02:28 -08004368void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4369 std::string stringResult;
4370
4371 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004372 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4373 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004374 continue;
4375 }
4376
Dominik Laskowski05275f12018-11-01 15:03:24 -07004377 const auto& compositionInfoList = it->second;
4378 stringResult += base::StringPrintf("%s\n", display->getDebugName().c_str());
David Sodman7e4ae112018-02-09 15:02:28 -08004379 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:
Ady Abraham37965d42018-11-01 13:43:32 -07004735 case GET_COLOR_MANAGEMENT:
Peiyong Lin0256f722018-08-31 15:45:10 -07004736 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004737 return OK;
4738 }
4739 case CAPTURE_LAYERS:
4740 case CAPTURE_SCREEN: {
4741 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004742 IPCThreadState* ipc = IPCThreadState::self();
4743 const int pid = ipc->getCallingPid();
4744 const int uid = ipc->getCallingUid();
4745 if ((uid != AID_GRAPHICS) &&
4746 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4747 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4748 return PERMISSION_DENIED;
4749 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004750 return OK;
4751 }
4752 // The following codes are deprecated and should never be allowed to access SF.
4753 case CONNECT_DISPLAY_UNUSED:
4754 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4755 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4756 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004757 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004758 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004759
4760 // These codes are used for the IBinder protocol to either interrogate the recipient
4761 // side of the transaction for its canonical interface descriptor or to dump its state.
4762 // We let them pass by default.
4763 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4764 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4765 code == IBinder::SYSPROPS_TRANSACTION) {
4766 return OK;
4767 }
Peiyong Lin3b44a032018-10-24 18:18:12 -07004768 // Numbers from 1000 to 1030 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004769 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin3b44a032018-10-24 18:18:12 -07004770 if (code >= 1000 && code <= 1030) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004771 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4772 return OK;
4773 }
4774 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4775 return PERMISSION_DENIED;
4776#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004777}
4778
Ana Krulec13be8ad2018-08-21 02:43:56 +00004779status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4780 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004781 status_t credentialCheck = CheckTransactCodeCredentials(code);
4782 if (credentialCheck != OK) {
4783 return credentialCheck;
4784 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004785
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004786 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4787 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004788 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004789 IPCThreadState* ipc = IPCThreadState::self();
4790 const int uid = ipc->getCallingUid();
4791 if (CC_UNLIKELY(uid != AID_SYSTEM
4792 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004793 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004794 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004795 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004796 return PERMISSION_DENIED;
4797 }
4798 int n;
4799 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004800 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004801 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004802 return NO_ERROR;
4803 case 1002: // SHOW_UPDATES
4804 n = data.readInt32();
4805 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004806 invalidateHwcGeometry();
4807 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004808 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004809 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004810 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004811 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004812 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004813 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004814 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004815 setTransactionFlags(
4816 eTransactionNeeded|
4817 eDisplayTransactionNeeded|
4818 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004819 return NO_ERROR;
4820 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004821 case 1006:{ // send empty update
4822 signalRefresh();
4823 return NO_ERROR;
4824 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004825 case 1008: // toggle use of hw composer
4826 n = data.readInt32();
4827 mDebugDisableHWC = n ? 1 : 0;
4828 invalidateHwcGeometry();
4829 repaintEverything();
4830 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004831 case 1009: // toggle use of transform hint
4832 n = data.readInt32();
4833 mDebugDisableTransformHint = n ? 1 : 0;
4834 invalidateHwcGeometry();
4835 repaintEverything();
4836 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004837 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004838 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004839 reply->writeInt32(0);
4840 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004841 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004842 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004843 return NO_ERROR;
4844 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004845 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004846 if (!display) {
4847 return NAME_NOT_FOUND;
4848 }
4849
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004850 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004851 return NO_ERROR;
4852 }
4853 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004854 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004855 // daltonize
4856 n = data.readInt32();
4857 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004858 case 1:
4859 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4860 break;
4861 case 2:
4862 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4863 break;
4864 case 3:
4865 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4866 break;
4867 default:
4868 mDaltonizer.setType(ColorBlindnessType::None);
4869 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004870 }
4871 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004872 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004873 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004874 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004875 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004876
4877 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004878 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004879 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004880 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004881 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004882 // apply a color matrix
4883 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004884 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004885 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004886 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004887 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004888 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004889 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004890 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004891 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004892 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004893 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004894
4895 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4896 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004897 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004898 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4899 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4900 }
4901
Chia-I Wu28f320b2018-05-03 11:02:56 -07004902 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004903 return NO_ERROR;
4904 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004905 // This is an experimental interface
4906 // Needs to be shifted to proper binder interface when we productize
4907 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004908 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07004909 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07004910 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004911 return NO_ERROR;
4912 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004913 case 1017: {
4914 n = data.readInt32();
4915 mForceFullDamage = static_cast<bool>(n);
4916 return NO_ERROR;
4917 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004918 case 1018: { // Modify Choreographer's phase offset
4919 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004920 if (mUseScheduler) {
4921 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
4922 } else {
4923 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4924 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004925 return NO_ERROR;
4926 }
4927 case 1019: { // Modify SurfaceFlinger's phase offset
4928 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004929 if (mUseScheduler) {
4930 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
4931 } else {
4932 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4933 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004934 return NO_ERROR;
4935 }
Irvel468051e2016-06-13 16:44:44 -07004936 case 1020: { // Layer updates interceptor
4937 n = data.readInt32();
4938 if (n) {
4939 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004940 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004941 }
4942 else{
4943 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004944 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004945 }
4946 return NO_ERROR;
4947 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004948 case 1021: { // Disable HWC virtual displays
4949 n = data.readInt32();
4950 mUseHwcVirtualDisplays = !n;
4951 return NO_ERROR;
4952 }
Romain Guy0147a172017-06-01 13:53:56 -07004953 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004954 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004955 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004956
Chia-I Wu28f320b2018-05-03 11:02:56 -07004957 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004958 return NO_ERROR;
4959 }
Romain Guy54f154a2017-10-24 21:40:32 +01004960 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004961 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004962 invalidateHwcGeometry();
4963 repaintEverything();
4964 return NO_ERROR;
4965 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004966 // Deprecate, use 1030 to check whether the device is color managed.
4967 case 1024: {
4968 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004969 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004970 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004971 n = data.readInt32();
4972 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004973 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004974 mTracing.enable();
4975 doTracing("tracing.enable");
4976 reply->writeInt32(NO_ERROR);
4977 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004978 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004979 status_t err = mTracing.disable();
4980 reply->writeInt32(err);
4981 }
4982 return NO_ERROR;
4983 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004984 case 1026: { // Get layer tracing status
4985 reply->writeBool(mTracing.isEnabled());
4986 return NO_ERROR;
4987 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004988 // Is a DisplayColorSetting supported?
4989 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004990 const auto display = getDefaultDisplayDevice();
4991 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004992 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004993 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004994
4995 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4996 switch (setting) {
4997 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07004998 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004999 break;
5000 case DisplayColorSetting::UNMANAGED:
5001 reply->writeBool(true);
5002 break;
5003 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005004 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005005 break;
5006 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005007 reply->writeBool(
5008 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005009 break;
5010 }
5011 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005012 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005013 // Is VrFlinger active?
5014 case 1028: {
5015 Mutex::Autolock _l(mStateLock);
5016 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5017 return NO_ERROR;
5018 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005019 // Is device color managed?
5020 case 1030: {
5021 reply->writeBool(useColorManagement);
5022 return NO_ERROR;
5023 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005024 }
5025 }
5026 return err;
5027}
5028
Steven Thomas6d8110b2017-08-31 18:24:21 -07005029void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005030 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005031 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005032}
5033
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005034// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5035class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005036public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005037 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5038 ~WindowDisconnector() {
5039 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005040 }
5041
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005042private:
5043 ANativeWindow* mWindow;
5044 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005045};
5046
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005047status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005048 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5049 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005050 uint32_t reqWidth, uint32_t reqHeight,
5051 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005052 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005053 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005054
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005055 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005056
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005057 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5058
Chia-I Wu20261cb2018-08-23 12:55:44 -07005059 sp<DisplayDevice> display;
5060 {
5061 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005062
Chia-I Wu20261cb2018-08-23 12:55:44 -07005063 display = getDisplayDeviceLocked(displayToken);
5064 if (!display) return BAD_VALUE;
5065
Chia-I Wucb023152018-08-28 12:57:23 -07005066 // set the requested width/height to the logical display viewport size
5067 // by default
5068 if (reqWidth == 0 || reqHeight == 0) {
5069 reqWidth = uint32_t(display->getViewport().width());
5070 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005071 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005072 }
5073
Peiyong Lin0e003c92018-09-17 11:09:51 -07005074 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5075 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005076
5077 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005078 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005079 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5080 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005081}
5082
5083status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005084 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5085 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005086 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005087 ATRACE_CALL();
5088
5089 class LayerRenderArea : public RenderArea {
5090 public:
Robert Carr578038f2018-03-09 12:25:24 -08005091 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005092 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5093 bool childrenOnly)
5094 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005095 mLayer(layer),
5096 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005097 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005098 mFlinger(flinger),
5099 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005100 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005101 Rect getBounds() const override {
5102 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005103 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005104 }
Marissa Wall61c58622018-07-18 10:12:20 -07005105 int getHeight() const override {
5106 return mLayer->getActiveHeight(mLayer->getDrawingState());
5107 }
5108 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005109 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005110 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005111 Rect getSourceCrop() const override {
5112 if (mCrop.isEmpty()) {
5113 return getBounds();
5114 } else {
5115 return mCrop;
5116 }
5117 }
Robert Carr578038f2018-03-09 12:25:24 -08005118 class ReparentForDrawing {
5119 public:
5120 const sp<Layer>& oldParent;
5121 const sp<Layer>& newParent;
5122
5123 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5124 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005125 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005126 }
Robert Carr15eae092018-03-23 13:43:53 -07005127 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005128 };
5129
5130 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005131 const Rect sourceCrop = getSourceCrop();
5132 // no need to check rotation because there is none
5133 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5134 sourceCrop.height() != getReqHeight();
5135
Robert Carr578038f2018-03-09 12:25:24 -08005136 if (!mChildrenOnly) {
5137 mTransform = mLayer->getTransform().inverse();
5138 drawLayers();
5139 } else {
5140 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005141 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005142 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5143 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005144
5145 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5146 drawLayers();
5147 }
5148 }
chaviwa76b2712017-09-20 12:02:26 -07005149
chaviwa76b2712017-09-20 12:02:26 -07005150 private:
chaviw7206d492017-11-10 16:16:12 -08005151 const sp<Layer> mLayer;
5152 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005153
5154 // In the "childrenOnly" case we reparent the children to a screenshot
5155 // layer which has no properties set and which does not draw.
5156 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005157 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005158 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005159
5160 SurfaceFlinger* mFlinger;
5161 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005162 };
5163
5164 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5165 auto parent = layerHandle->owner.promote();
5166
Robert Carr2e102c92018-10-23 12:11:15 -07005167 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005168 ALOGE("captureLayers called with a removed parent");
5169 return NAME_NOT_FOUND;
5170 }
5171
Robert Carr578038f2018-03-09 12:25:24 -08005172 const int uid = IPCThreadState::self()->getCallingUid();
5173 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5174 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5175 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5176 return PERMISSION_DENIED;
5177 }
5178
chaviw7206d492017-11-10 16:16:12 -08005179 Rect crop(sourceCrop);
5180 if (sourceCrop.width() <= 0) {
5181 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005182 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005183 }
5184
5185 if (sourceCrop.height() <= 0) {
5186 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005187 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005188 }
5189
5190 int32_t reqWidth = crop.width() * frameScale;
5191 int32_t reqHeight = crop.height() * frameScale;
5192
Chia-I Wu20261cb2018-08-23 12:55:44 -07005193 // really small crop or frameScale
5194 if (reqWidth <= 0) {
5195 reqWidth = 1;
5196 }
5197 if (reqHeight <= 0) {
5198 reqHeight = 1;
5199 }
5200
Peiyong Lin0e003c92018-09-17 11:09:51 -07005201 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005202
Robert Carr578038f2018-03-09 12:25:24 -08005203 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005204 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5205 if (!layer->isVisible()) {
5206 return;
Robert Carr578038f2018-03-09 12:25:24 -08005207 } else if (childrenOnly && layer == parent.get()) {
5208 return;
chaviwa76b2712017-09-20 12:02:26 -07005209 }
5210 visitor(layer);
5211 });
5212 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005213 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005214}
5215
5216status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5217 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005218 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005219 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005220 bool useIdentityTransform) {
5221 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005222
Peiyong Lin0e003c92018-09-17 11:09:51 -07005223 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005224 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5225 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005226 *outBuffer =
5227 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5228 static_cast<android_pixel_format>(reqPixelFormat), 1,
5229 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005230
5231 // This mutex protects syncFd and captureResult for communication of the return values from the
5232 // main thread back to this Binder thread
5233 std::mutex captureMutex;
5234 std::condition_variable captureCondition;
5235 std::unique_lock<std::mutex> captureLock(captureMutex);
5236 int syncFd = -1;
5237 std::optional<status_t> captureResult;
5238
Robert Carr03480e22018-01-04 16:02:06 -08005239 const int uid = IPCThreadState::self()->getCallingUid();
5240 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5241
Dominik Laskowski8c001672018-05-30 16:52:06 -07005242 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005243 // If there is a refresh pending, bug out early and tell the binder thread to try again
5244 // after the refresh.
5245 if (mRefreshPending) {
5246 ATRACE_NAME("Skipping screenshot for now");
5247 std::unique_lock<std::mutex> captureLock(captureMutex);
5248 captureResult = std::make_optional<status_t>(EAGAIN);
5249 captureCondition.notify_one();
5250 return;
5251 }
5252
5253 status_t result = NO_ERROR;
5254 int fd = -1;
5255 {
5256 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005257 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005258 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5259 useIdentityTransform, forSystem, &fd);
5260 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005261 }
5262
5263 {
5264 std::unique_lock<std::mutex> captureLock(captureMutex);
5265 syncFd = fd;
5266 captureResult = std::make_optional<status_t>(result);
5267 captureCondition.notify_one();
5268 }
5269 });
5270
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005271 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005272 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005273 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005274 while (*captureResult == EAGAIN) {
5275 captureResult.reset();
5276 result = postMessageAsync(message);
5277 if (result != NO_ERROR) {
5278 return result;
5279 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005280 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005281 }
5282 result = *captureResult;
5283 }
5284
5285 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005286 sync_wait(syncFd, -1);
5287 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005288 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005289
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005290 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005291}
5292
chaviwa76b2712017-09-20 12:02:26 -07005293void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005294 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005295 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005296 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005297
Lloyd Pique144e1162017-12-20 16:44:52 -08005298 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005299
chaviwa76b2712017-09-20 12:02:26 -07005300 const auto reqWidth = renderArea.getReqWidth();
5301 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005302 const auto sourceCrop = renderArea.getSourceCrop();
5303 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005304
Peiyong Lin0e003c92018-09-17 11:09:51 -07005305 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005306 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005307
Mathias Agopian180f10d2013-04-10 22:55:41 -07005308 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005309 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005310
5311 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005312 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005313 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005314
chaviw50da5042018-04-09 13:49:37 -07005315 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005316 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005317 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005318
chaviwa76b2712017-09-20 12:02:26 -07005319 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005320 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005321 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005322 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005323 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005324}
5325
chaviwa76b2712017-09-20 12:02:26 -07005326status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5327 TraverseLayersFunction traverseLayers,
5328 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005329 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005330 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005331 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005332 ATRACE_CALL();
5333
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005334 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005335
5336 traverseLayers([&](Layer* layer) {
5337 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5338 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005339
Robert Carr03480e22018-01-04 16:02:06 -08005340 // We allow the system server to take screenshots of secure layers for
5341 // use in situations like the Screen-rotation animation and place
5342 // the impetus on WindowManager to not persist them.
5343 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005344 ALOGW("FB is protected: PERMISSION_DENIED");
5345 return PERMISSION_DENIED;
5346 }
5347
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005348 // this binds the given EGLImage as a framebuffer for the
5349 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005350 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005351 if (bufferBond.getStatus() != NO_ERROR) {
5352 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005353 return INVALID_OPERATION;
5354 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005355
Dan Stozaabcda352017-06-01 14:37:39 -07005356 // this will in fact render into our dequeued buffer
5357 // via an FBO, which means we didn't have to create
5358 // an EGLSurface and therefore we're not
5359 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005360 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005361
Alec Mouri492bc572018-09-11 21:40:04 +00005362 base::unique_fd syncFd = getRenderEngine().flush();
5363 if (syncFd < 0) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005364 getRenderEngine().finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005365 }
Alec Mouri492bc572018-09-11 21:40:04 +00005366 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005367
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005368 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005369}
5370
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005371// ---------------------------------------------------------------------------
5372
Dan Stoza412903f2017-04-27 13:42:17 -07005373void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5374 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005375}
5376
Dan Stoza412903f2017-04-27 13:42:17 -07005377void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5378 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005379}
5380
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005381void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005382 const LayerVector::Visitor& visitor) {
5383 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005384 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005385 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005386 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005387 continue;
5388 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005389 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005390 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005391 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005392 return;
5393 }
chaviwa76b2712017-09-20 12:02:26 -07005394 if (!layer->isVisible()) {
5395 return;
5396 }
5397 visitor(layer);
5398 });
5399 }
5400}
5401
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005402}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005403
Lloyd Pique074e8122018-07-26 12:57:23 -07005404
Mathias Agopian3f844832013-08-07 21:24:32 -07005405#if defined(__gl_h_)
5406#error "don't include gl/gl.h in this file"
5407#endif
5408
5409#if defined(__gl2_h_)
5410#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005411#endif