blob: 4c3be4da0bfddcf0834303cc4a27a0ac066f51ea [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 Abraham2a6ab2a2018-10-26 14:25:30 -0700521bool SurfaceFlinger::isColorManagementUsed() const {
522 return useColorManagement;
523}
524
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800525void SurfaceFlinger::bootFinished()
526{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700527 if (mStartPropertySetThread->join() != NO_ERROR) {
528 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800529 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800530 const nsecs_t now = systemTime();
531 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000532 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700533
534 // wait patiently for the window manager death
535 const String16 name("window");
536 sp<IBinder> window(defaultServiceManager()->getService(name));
537 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700538 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700539 }
540
Steven Thomas050b2c82017-03-06 11:45:16 -0800541 if (mVrFlinger) {
542 mVrFlinger->OnBootFinished();
543 }
544
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700545 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700546 // formerly we would just kill the process, but we now ask it to exit so it
547 // can choose where to stop the animation.
548 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700549
550 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
551 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
552 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700553
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800554 postMessageAsync(new LambdaMessage([this] {
555 readPersistentProperties();
556 mBootStage = BootStage::FINISHED;
557 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800558}
559
Dan Stoza436ccf32018-06-21 12:10:12 -0700560uint32_t SurfaceFlinger::getNewTexture() {
561 {
562 std::lock_guard lock(mTexturePoolMutex);
563 if (!mTexturePool.empty()) {
564 uint32_t name = mTexturePool.back();
565 mTexturePool.pop_back();
566 ATRACE_INT("TexturePoolSize", mTexturePool.size());
567 return name;
568 }
569
570 // The pool was too small, so increase it for the future
571 ++mTexturePoolSize;
572 }
573
574 // The pool was empty, so we need to get a new texture name directly using a
575 // blocking call to the main thread
576 uint32_t name = 0;
577 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
578 return name;
579}
580
Mathias Agopian3f844832013-08-07 21:24:32 -0700581void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700582 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700583}
584
Wei Wangf9b05ee2017-07-19 20:59:39 -0700585// Do not call property_set on main thread which will be blocked by init
586// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700587void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700588 ALOGI( "SurfaceFlinger's main thread ready to run. "
589 "Initializing graphics H/W...");
590
Thierry Strudel2924d012017-08-14 15:19:37 -0700591 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900592
Steven Thomasb02664d2017-07-26 18:48:28 -0700593 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800594
Steven Thomasb02664d2017-07-26 18:48:28 -0700595 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700596 if (mUseScheduler) {
Lloyd Pique90c115d2018-09-18 21:39:42 -0700597 mScheduler = getFactory().createScheduler(
Ana Krulece588e312018-09-18 12:32:24 -0700598 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Ana Krulec98b5b242018-08-10 15:03:23 -0700599 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700600 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700601 [this] { resyncWithRateLimit(); },
602 impl::EventThread::InterceptVSyncsCallback());
603 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700604 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700605 [this] { resyncWithRateLimit(); },
606 [this](nsecs_t timestamp) {
607 mInterceptor->saveVSyncEvent(timestamp);
608 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800609
Ana Krulec98b5b242018-08-10 15:03:23 -0700610 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700611 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
612 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700613 } else {
614 mEventThreadSource =
615 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
616 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
617 mEventThread =
618 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
619 [this] { resyncWithRateLimit(); },
620 impl::EventThread::InterceptVSyncsCallback(),
621 "appEventThread");
622 mSfEventThreadSource =
623 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
624 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
625
626 mSFEventThread =
627 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
628 [this] { resyncWithRateLimit(); },
629 [this](nsecs_t timestamp) {
630 mInterceptor->saveVSyncEvent(timestamp);
631 },
632 "sfEventThread");
633 mEventQueue->setEventThread(mSFEventThread.get());
634 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
635 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800636
Steven Thomasb02664d2017-07-26 18:48:28 -0700637 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700638 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700639 renderEngineFeature |= (useColorManagement ?
640 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700641 renderEngineFeature |= (useContextPriority ?
642 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700643
644 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
645 getBE().mRenderEngine =
Peiyong Linc6780972018-10-28 15:24:08 -0700646 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
647 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800648 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700649
650 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
651 "Starting with vr flinger active is not currently supported.");
Lloyd Pique90c115d2018-09-18 21:39:42 -0700652 getBE().mHwc = getFactory().createHWComposer(getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -0700653 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800654 // Process any initial hotplug and resulting display changes.
655 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700656 const auto display = getDefaultDisplayDeviceLocked();
657 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
658 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
659 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800660
Lloyd Piquefcd86612017-12-14 17:15:36 -0800661 // make the default display GLContext current so that we can create textures
662 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700663 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800664
Steven Thomas050b2c82017-03-06 11:45:16 -0800665 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700666 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700667 // This callback is called from the vr flinger dispatch thread. We
668 // need to call signalTransaction(), which requires holding
669 // mStateLock when we're not on the main thread. Acquiring
670 // mStateLock from the vr flinger dispatch thread might trigger a
671 // deadlock in surface flinger (see b/66916578), so post a message
672 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700673 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700674 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
675 mVrFlingerRequestsDisplay = requestDisplay;
676 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700677 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800678 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700679 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
680 getHwComposer()
681 .getHwcDisplayId(display->getId())
682 .value_or(0),
683 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800684 if (!mVrFlinger) {
685 ALOGE("Failed to start vrflinger");
686 }
687 }
688
Lloyd Pique90c115d2018-09-18 21:39:42 -0700689 mEventControlThread = getFactory().createEventControlThread(
Lloyd Pique379adc12018-01-22 17:31:47 -0800690 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700691
Mathias Agopian92a979a2012-08-02 18:32:23 -0700692 // initialize our drawing state
693 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700694
Andy McFadden13a082e2012-08-24 10:16:42 -0700695 // set initial conditions (e.g. unblank default device)
696 initializeDisplays();
697
David Sodmanbc815282017-11-05 18:57:52 -0800698 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700699
Wei Wangf9b05ee2017-07-19 20:59:39 -0700700 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700701
702 const bool presentFenceReliable =
703 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
704 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700705
706 if (mStartPropertySetThread->Start() != NO_ERROR) {
707 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800708 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800709
Chia-I Wud49d6692018-06-27 07:17:41 +0800710 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
711 // is used to saturate legacy sRGB content. However, to make sure the same color under
712 // Display P3 will be saturated to the same color, we intentionally break the API spec
713 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
714 // such saturation matrix on Display P3 is understood fully, the API should always return
715 // identify matrix.
716 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
717 Dataspace::SRGB_LINEAR);
718
719 // we will apply this on Display P3.
720 if (mEnhancedSaturationMatrix != mat4()) {
721 ColorSpace srgb(ColorSpace::sRGB());
722 ColorSpace displayP3(ColorSpace::DisplayP3());
723 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
724 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
725 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
726 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800727
Dan Stoza9e56aa02015-11-02 13:00:03 -0800728 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700729}
730
Romain Guy11d63f42017-07-20 12:47:14 -0700731void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700732 Mutex::Autolock _l(mStateLock);
733
Romain Guy11d63f42017-07-20 12:47:14 -0700734 char value[PROPERTY_VALUE_MAX];
735
736 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800737 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700738 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800739 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100740
741 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700742 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700743}
744
Mathias Agopiana67e4182012-06-19 17:26:12 -0700745void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800746 // Start boot animation service by setting a property mailbox
747 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700748 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800749 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700750 if (mStartPropertySetThread->join() != NO_ERROR) {
751 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800752 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700753}
754
Mathias Agopian875d8e12013-06-07 15:35:48 -0700755size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800756 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700757}
758
Mathias Agopian875d8e12013-06-07 15:35:48 -0700759size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800760 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700761}
762
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800763// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800764
Jamie Gennis582270d2011-08-17 18:19:00 -0700765bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800766 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800767 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800768 return authenticateSurfaceTextureLocked(bufferProducer);
769}
770
771bool SurfaceFlinger::authenticateSurfaceTextureLocked(
772 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800773 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800774 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800775}
776
Brian Anderson6b376712017-04-04 10:51:39 -0700777status_t SurfaceFlinger::getSupportedFrameTimestamps(
778 std::vector<FrameEvent>* outSupported) const {
779 *outSupported = {
780 FrameEvent::REQUESTED_PRESENT,
781 FrameEvent::ACQUIRE,
782 FrameEvent::LATCH,
783 FrameEvent::FIRST_REFRESH_START,
784 FrameEvent::LAST_REFRESH_START,
785 FrameEvent::GPU_COMPOSITION_DONE,
786 FrameEvent::DEQUEUE_READY,
787 FrameEvent::RELEASE,
788 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700789 ConditionalLock _l(mStateLock,
790 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700791 if (!getHwComposer().hasCapability(
792 HWC2::Capability::PresentFenceIsNotReliable)) {
793 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
794 }
795 return NO_ERROR;
796}
797
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700798status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
799 Vector<DisplayInfo>* configs) {
800 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700801 return BAD_VALUE;
802 }
803
Jesse Hall692c7232012-11-08 15:41:56 -0800804 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700805 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
806 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700807 type = i;
808 break;
809 }
810 }
811
812 if (type < 0) {
813 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700814 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700815
Mathias Agopian8b736f12012-08-13 17:54:26 -0700816 // TODO: Not sure if display density should handled by SF any longer
817 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700818 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700819 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700820 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800821 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700822 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700823 }
824 return density;
825 }
826 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700827 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700828 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700829 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700830 return getDensityFromProperty("ro.sf.lcd_density"); }
831 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700832
Dan Stoza7f7da322014-05-02 15:26:25 -0700833 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700834
Steven Thomas6d8110b2017-08-31 18:24:21 -0700835 ConditionalLock _l(mStateLock,
836 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800837 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700838 DisplayInfo info = DisplayInfo();
839
Dan Stoza9e56aa02015-11-02 13:00:03 -0800840 float xdpi = hwConfig->getDpiX();
841 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700842
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700843 info.w = hwConfig->getWidth();
844 info.h = hwConfig->getHeight();
845 // Default display viewport to display width and height
846 info.viewportW = info.w;
847 info.viewportH = info.h;
848
Dan Stoza7f7da322014-05-02 15:26:25 -0700849 if (type == DisplayDevice::DISPLAY_PRIMARY) {
850 // The density of the device is provided by a build property
851 float density = Density::getBuildDensity() / 160.0f;
852 if (density == 0) {
853 // the build doesn't provide a density -- this is wrong!
854 // use xdpi instead
855 ALOGE("ro.sf.lcd_density must be defined as a build property");
856 density = xdpi / 160.0f;
857 }
858 if (Density::getEmuDensity()) {
859 // if "qemu.sf.lcd_density" is specified, it overrides everything
860 xdpi = ydpi = density = Density::getEmuDensity();
861 density /= 160.0f;
862 }
863 info.density = density;
864
865 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700866 const auto display = getDefaultDisplayDeviceLocked();
867 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700868
869 // This is for screenrecord
870 const Rect viewport = display->getViewport();
871 if (viewport.isValid()) {
872 info.viewportW = uint32_t(viewport.getWidth());
873 info.viewportH = uint32_t(viewport.getHeight());
874 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700875 } else {
876 // TODO: where should this value come from?
877 static const int TV_DENSITY = 213;
878 info.density = TV_DENSITY / 160.0f;
879 info.orientation = 0;
880 }
881
Dan Stoza7f7da322014-05-02 15:26:25 -0700882 info.xdpi = xdpi;
883 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800884 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900885 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800886
Andy McFadden91b2ca82014-06-13 14:04:23 -0700887 // This is how far in advance a buffer must be queued for
888 // presentation at a given time. If you want a buffer to appear
889 // on the screen at time N, you must submit the buffer before
890 // (N - presentationDeadline).
891 //
892 // Normally it's one full refresh period (to give SF a chance to
893 // latch the buffer), but this can be reduced by configuring a
894 // DispSync offset. Any additional delays introduced by the hardware
895 // composer or panel must be accounted for here.
896 //
897 // We add an additional 1ms to allow for processing time and
898 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800899 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800900 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700901
902 // All non-virtual displays are currently considered secure.
903 info.secure = true;
904
Iris Chang7501ed62018-04-30 14:45:42 +0800905 if (type == DisplayDevice::DISPLAY_PRIMARY &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700906 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800907 std::swap(info.w, info.h);
908 }
909
Michael Wright28f24d02016-07-12 13:30:53 -0700910 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700911 }
912
Dan Stoza7f7da322014-05-02 15:26:25 -0700913 return NO_ERROR;
914}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700915
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700916status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
917 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700918 return BAD_VALUE;
919 }
920
Ana Krulece588e312018-09-18 12:32:24 -0700921 // FIXME for now we always return stats for the primary display.
922 if (mUseScheduler) {
923 mScheduler->getDisplayStatInfo(stats);
924 } else {
925 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
926 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
927 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700928 return NO_ERROR;
929}
930
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700931int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
932 const auto display = getDisplayDevice(displayToken);
933 if (!display) {
934 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800935 return BAD_VALUE;
936 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700937
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700938 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700939}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700940
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700941void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
942 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700943 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700944 return;
945 }
946
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700947 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700948 ALOGW("Trying to set config for virtual display");
949 return;
950 }
951
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700952 display->setActiveConfig(mode);
953 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700954}
955
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700956status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700957 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700958 Vector<DisplayInfo> configs;
959 getDisplayConfigs(displayToken, &configs);
960 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
961 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
962 configs.size());
963 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700964 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700965 const auto display = getDisplayDevice(displayToken);
966 if (!display) {
967 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
968 displayToken.get());
969 } else if (display->isVirtual()) {
970 ALOGW("Attempt to set active config %d for virtual display", mode);
971 } else {
972 setActiveConfigInternal(display, mode);
973 }
974 }));
975
Mathias Agopian888c8222012-08-04 21:10:38 -0700976 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700977}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700978status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
979 Vector<ColorMode>* outColorModes) {
980 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700981 return BAD_VALUE;
982 }
983
Michael Wright28f24d02016-07-12 13:30:53 -0700984 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700985 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
986 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700987 type = i;
988 break;
989 }
990 }
991
992 if (type < 0) {
993 return type;
994 }
995
Peiyong Lina52f0292018-03-14 17:26:31 -0700996 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700997 {
998 ConditionalLock _l(mStateLock,
999 std::this_thread::get_id() != mMainThreadId);
1000 modes = getHwComposer().getColorModes(type);
1001 }
Michael Wright28f24d02016-07-12 13:30:53 -07001002 outColorModes->clear();
1003 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1004
1005 return NO_ERROR;
1006}
1007
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001008ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1009 if (const auto display = getDisplayDevice(displayToken)) {
1010 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001011 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001012 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001013}
1014
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001015void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1016 Dataspace dataSpace, RenderIntent renderIntent) {
1017 ColorMode currentMode = display->getActiveColorMode();
1018 Dataspace currentDataSpace = display->getCompositionDataSpace();
1019 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001020
Peiyong Lin38e9a562018-04-10 16:24:20 -07001021 if (mode == currentMode && dataSpace == currentDataSpace &&
1022 renderIntent == currentRenderIntent) {
1023 return;
1024 }
1025
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001026 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001027 ALOGW("Trying to set config for virtual display");
1028 return;
1029 }
1030
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001031 display->setActiveColorMode(mode);
1032 display->setCompositionDataSpace(dataSpace);
1033 display->setActiveRenderIntent(renderIntent);
1034 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001035
1036 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001037 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1038 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001039}
1040
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001041status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001042 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001043 Vector<ColorMode> modes;
1044 getDisplayColorModes(displayToken, &modes);
1045 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1046 if (mode < ColorMode::NATIVE || !exists) {
1047 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1048 decodeColorMode(mode).c_str(), mode, displayToken.get());
1049 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001050 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001051 const auto display = getDisplayDevice(displayToken);
1052 if (!display) {
1053 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1054 decodeColorMode(mode).c_str(), mode, displayToken.get());
1055 } else if (display->isVirtual()) {
1056 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1057 decodeColorMode(mode).c_str(), mode);
1058 } else {
1059 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1060 RenderIntent::COLORIMETRIC);
1061 }
1062 }));
1063
Michael Wright28f24d02016-07-12 13:30:53 -07001064 return NO_ERROR;
1065}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001066
Svetoslavd85084b2014-03-20 10:28:31 -07001067status_t SurfaceFlinger::clearAnimationFrameStats() {
1068 Mutex::Autolock _l(mStateLock);
1069 mAnimFrameTracker.clearStats();
1070 return NO_ERROR;
1071}
1072
1073status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1074 Mutex::Autolock _l(mStateLock);
1075 mAnimFrameTracker.getStats(outStats);
1076 return NO_ERROR;
1077}
1078
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001079status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1080 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001081 Mutex::Autolock _l(mStateLock);
1082
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001083 const auto display = getDisplayDeviceLocked(displayToken);
1084 if (!display) {
1085 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001086 return BAD_VALUE;
1087 }
1088
Peiyong Linfb069302018-04-25 14:34:31 -07001089 // At this point the DisplayDeivce should already be set up,
1090 // meaning the luminance information is already queried from
1091 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001092 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001093 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1094 capabilities.getDesiredMaxLuminance(),
1095 capabilities.getDesiredMaxAverageLuminance(),
1096 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001097
1098 return NO_ERROR;
1099}
1100
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001101status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001102 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001103 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001104
Chia-I Wu90f669f2017-10-05 14:24:41 -07001105 if (mInjectVSyncs == enable) {
1106 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001107 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001108
Ana Krulec98b5b242018-08-10 15:03:23 -07001109 // TODO(akrulec): Part of the Injector should be refactored, so that it
1110 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001111 if (enable) {
1112 ALOGV("VSync Injections enabled");
1113 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001114 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001115 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001116 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001117 impl::EventThread::InterceptVSyncsCallback(),
1118 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001119 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001120 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001121 } else {
1122 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001123 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001124 }
1125
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001126 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001127 }));
1128
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001129 return NO_ERROR;
1130}
1131
1132status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001133 Mutex::Autolock _l(mStateLock);
1134
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001135 if (!mInjectVSyncs) {
1136 ALOGE("VSync Injections not enabled");
1137 return BAD_VALUE;
1138 }
1139 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1140 ALOGV("Injecting VSync inside SurfaceFlinger");
1141 mVSyncInjector->onInjectSyncEvent(when);
1142 }
1143 return NO_ERROR;
1144}
1145
Lloyd Pique755e3192018-01-31 16:46:15 -08001146status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1147 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001148 // Try to acquire a lock for 1s, fail gracefully
1149 const status_t err = mStateLock.timedLock(s2ns(1));
1150 const bool locked = (err == NO_ERROR);
1151 if (!locked) {
1152 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1153 return TIMED_OUT;
1154 }
1155
1156 outLayers->clear();
1157 mCurrentState.traverseInZOrder([&](Layer* layer) {
1158 outLayers->push_back(layer->getLayerDebugInfo());
1159 });
1160
1161 mStateLock.unlock();
1162 return NO_ERROR;
1163}
1164
Peiyong Linc6780972018-10-28 15:24:08 -07001165status_t SurfaceFlinger::getCompositionPreference(
1166 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1167 Dataspace* outWideColorGamutDataspace,
1168 ui::PixelFormat* outWideColorGamutPixelFormat) const {
1169 *outDataspace = defaultCompositionDataspace;
1170 *outPixelFormat = defaultCompositionPixelFormat;
1171 *outWideColorGamutDataspace = wideColorGamutCompositionDataspace;
1172 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001173 return NO_ERROR;
1174}
1175
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001176// ----------------------------------------------------------------------------
1177
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001178sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1179 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001180 if (mUseScheduler) {
1181 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1182 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1183 } else {
1184 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1185 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001186 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001187 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1188 return mSFEventThread->createEventConnection();
1189 } else {
1190 return mEventThread->createEventConnection();
1191 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001192 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001193}
1194
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001195// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001196
1197void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001198 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001199}
1200
1201void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001202 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001203}
1204
1205void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001206 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001207}
1208
1209void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001210 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001211 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001212}
1213
1214status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001215 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001216 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001217}
1218
1219status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001220 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001221 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001222 if (res == NO_ERROR) {
1223 msg->wait();
1224 }
1225 return res;
1226}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001227
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001228void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001229 do {
1230 waitForEvent();
1231 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001232}
1233
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001234void SurfaceFlinger::enableHardwareVsync() {
1235 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001236 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001237 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001238 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001239 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001240 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001241}
1242
Jesse Hall948fe0c2013-10-14 12:56:09 -07001243void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001244 Mutex::Autolock _l(mHWVsyncLock);
1245
Jesse Hall948fe0c2013-10-14 12:56:09 -07001246 if (makeAvailable) {
1247 mHWVsyncAvailable = true;
1248 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001249 // Hardware vsync is not currently available, so abort the resync
1250 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001251 return;
1252 }
1253
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001254 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1255 if (!getHwComposer().isConnected(displayId)) {
1256 return;
1257 }
1258
1259 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001260 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001261
Ana Krulece588e312018-09-18 12:32:24 -07001262 if (mUseScheduler) {
1263 mScheduler->setVsyncPeriod(period);
1264 } else {
1265 mPrimaryDispSync->reset();
1266 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001267
Ana Krulece588e312018-09-18 12:32:24 -07001268 if (!mPrimaryHWVsyncEnabled) {
1269 mPrimaryDispSync->beginResync();
1270 mEventControlThread->setVsyncEnabled(true);
1271 mPrimaryHWVsyncEnabled = true;
1272 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001273 }
1274}
1275
Jesse Hall948fe0c2013-10-14 12:56:09 -07001276void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001277 Mutex::Autolock _l(mHWVsyncLock);
1278 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001279 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001280 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001281 mPrimaryHWVsyncEnabled = false;
1282 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001283 if (makeUnavailable) {
1284 mHWVsyncAvailable = false;
1285 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001286}
1287
Tim Murray4a4e4a22016-04-19 16:29:23 +00001288void SurfaceFlinger::resyncWithRateLimit() {
1289 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001290
1291 // No explicit locking is needed here since EventThread holds a lock while calling this method
1292 static nsecs_t sLastResyncAttempted = 0;
1293 const nsecs_t now = systemTime();
1294 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001295 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001296 }
Dan Stoza57164302017-05-08 14:03:54 -07001297 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001298}
1299
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001300void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1301 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001302 ATRACE_NAME("SF onVsync");
1303
Steven Thomas3cfac282017-02-06 12:29:30 -08001304 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001305 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001306 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001307 return;
1308 }
1309
1310 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001311 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001312 return;
1313 }
1314
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001315 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1316 // For now, we don't do anything with external display vsyncs.
1317 return;
1318 }
1319
Ana Krulece588e312018-09-18 12:32:24 -07001320 if (mUseScheduler) {
1321 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001322 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001323 bool needsHwVsync = false;
1324 { // Scope for the lock
1325 Mutex::Autolock _l(mHWVsyncLock);
1326 if (mPrimaryHWVsyncEnabled) {
1327 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1328 }
1329 }
1330
1331 if (needsHwVsync) {
1332 enableHardwareVsync();
1333 } else {
1334 disableHardwareVsync(false);
1335 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001336 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001337}
1338
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001339void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001340 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1341 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001342}
1343
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001344void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001345 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001346 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001347 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001348
Lloyd Piqueba04e622017-12-14 17:11:26 -08001349 // Ignore events that do not have the right sequenceId.
1350 if (sequenceId != getBE().mComposerSequenceId) {
1351 return;
1352 }
1353
Steven Thomasb02664d2017-07-26 18:48:28 -07001354 // Only lock if we're not on the main thread. This function is normally
1355 // called on a hwbinder thread, but for the primary display it's called on
1356 // the main thread with the state lock already held, so don't attempt to
1357 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001358 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001359
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001360 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001361
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001362 if (std::this_thread::get_id() == mMainThreadId) {
1363 // Process all pending hot plug events immediately if we are on the main thread.
1364 processDisplayHotplugEventsLocked();
1365 }
1366
Lloyd Piqueba04e622017-12-14 17:11:26 -08001367 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001368}
1369
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001370void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001371 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001372 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001373 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001374 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001375 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001376}
1377
Dan Stoza9e56aa02015-11-02 13:00:03 -08001378void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001379 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001380 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001381 getHwComposer().setVsyncEnabled(disp,
1382 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001383}
1384
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001385// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001386void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001387 if (mUseScheduler) {
1388 mScheduler->disableHardwareVsync(true);
1389 } else {
1390 disableHardwareVsync(true);
1391 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001392 // Clear the drawing state so that the logic inside of
1393 // handleTransactionLocked will fire. It will determine the delta between
1394 // mCurrentState and mDrawingState and re-apply all changes when we make the
1395 // transition.
1396 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001397 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001398 mDisplays.clear();
1399}
1400
Steven Thomas050b2c82017-03-06 11:45:16 -08001401void SurfaceFlinger::updateVrFlinger() {
1402 if (!mVrFlinger)
1403 return;
1404 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001405 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001406 return;
1407 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001408
David Sodman105b7dc2017-11-04 20:28:14 -07001409 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001410 ALOGE("Vr flinger is only supported for remote hardware composer"
1411 " service connections. Ignoring request to transition to vr"
1412 " flinger.");
1413 mVrFlingerRequestsDisplay = false;
1414 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001415 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001416
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001417 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001418
Steven Thomas0123ac62018-07-12 11:32:34 -07001419 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001420 LOG_ALWAYS_FATAL_IF(!display);
1421 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001422 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1423 // called below. Clear the reference now so we don't accidentally use it
1424 // later.
1425 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001426
Steven Thomasb02664d2017-07-26 18:48:28 -07001427 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001428 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001429 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001430
Steven Thomasb02664d2017-07-26 18:48:28 -07001431 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001432 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Pique90c115d2018-09-18 21:39:42 -07001433 getBE().mHwc = getFactory().createHWComposer(
1434 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -07001435 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001436
David Sodman105b7dc2017-11-04 20:28:14 -07001437 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1438 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001439
1440 if (vrFlingerRequestsDisplay) {
1441 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001442 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001443
1444 mVisibleRegionsDirty = true;
1445 invalidateHwcGeometry();
1446
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001447 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001448 display = getDefaultDisplayDeviceLocked();
1449 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001450 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001451
Steven Thomasb02664d2017-07-26 18:48:28 -07001452 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001453 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001454 const nsecs_t period = activeConfig->getVsyncPeriod();
1455 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001456
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001457 // The present fences returned from vr_hwc are not an accurate
1458 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001459 if (mUseScheduler) {
1460 mScheduler->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() || !hasSyncFramework);
1461 } else {
1462 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1463 !hasSyncFramework);
1464 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001465
Steven Thomasb02664d2017-07-26 18:48:28 -07001466 // Use phase of 0 since phase is not known.
1467 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001468 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1469 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001470
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001471 resyncToHardwareVsync(false);
1472
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001473 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001474 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001475}
1476
Mathias Agopian4fec8732012-06-29 14:12:52 -07001477void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001478 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001479 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001480 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001481 bool frameMissed = !mHadClientComposition &&
1482 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001483 (mPreviousPresentFence->getSignalTime() ==
1484 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001485 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001486 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001487 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001488 mTimeStats.incrementMissedFrames();
1489 if (mPropagateBackpressure) {
1490 signalLayerUpdate();
1491 break;
1492 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001493 }
Dan Stoza50182882016-07-08 12:02:20 -07001494
Steven Thomas050b2c82017-03-06 11:45:16 -08001495 // Now that we're going to make it to the handleMessageTransaction()
1496 // call below it's safe to call updateVrFlinger(), which will
1497 // potentially trigger a display handoff.
1498 updateVrFlinger();
1499
Dan Stoza6b9454d2014-11-07 16:00:59 -08001500 bool refreshNeeded = handleMessageTransaction();
1501 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001502 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001503 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001504 // Signal a refresh if a transaction modified the window state,
1505 // a new buffer was latched, or if HWC has requested a full
1506 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001507 signalRefresh();
1508 }
1509 break;
1510 }
1511 case MessageQueue::REFRESH: {
1512 handleMessageRefresh();
1513 break;
1514 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001515 }
1516}
1517
Dan Stoza6b9454d2014-11-07 16:00:59 -08001518bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001519 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001520 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001521 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001522 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001523 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001524 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001525}
1526
Mathias Agopian4fec8732012-06-29 14:12:52 -07001527void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001528 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001529
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001530 mRefreshPending = false;
1531
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001532 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001533 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001534 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001535 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001536 for (const auto& [token, display] : mDisplays) {
1537 beginFrame(display);
1538 prepareFrame(display);
1539 doDebugFlashRegions(display, repaintEverything);
1540 doComposition(display, repaintEverything);
1541 }
1542
Adrian Roos1e1a1282017-11-01 19:05:31 +01001543 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001544 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001545
1546 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001547 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001548
Dan Stozabfbffeb2016-07-21 14:49:33 -07001549 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001550 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001551 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001552 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001553 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001554
Alec Mouri86770e52018-09-24 22:40:58 +00001555 // Setup RenderEngine sync fences if native sync is supported.
1556 if (getBE().mRenderEngine->useNativeFenceSync()) {
1557 if (mHadClientComposition) {
1558 base::unique_fd flushFence(getRenderEngine().flush());
1559 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1560 getBE().flushFence = new Fence(std::move(flushFence));
1561 } else {
1562 // Cleanup for hygiene.
1563 getBE().flushFence = Fence::NO_FENCE;
1564 }
1565 }
1566
Jorim Jaggi90535212018-05-23 23:44:06 +02001567 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001568
David Sodman7e4ae112018-02-09 15:02:28 -08001569 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001570 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001571 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001572 compositionInfo.hwc.hwcLayer = nullptr;
1573 }
David Sodmanba340492018-08-05 21:51:33 -07001574 }
David Sodman7e4ae112018-02-09 15:02:28 -08001575
1576 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001577}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001578
David Sodmanfa9b2af2017-12-24 13:28:59 -08001579
1580bool SurfaceFlinger::handleMessageInvalidate() {
1581 ATRACE_CALL();
1582 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001583}
1584
David Sodman79bba0e2018-08-05 18:07:49 -07001585void SurfaceFlinger::calculateWorkingSet() {
1586 ATRACE_CALL();
1587 ALOGV(__FUNCTION__);
1588
David Sodman79bba0e2018-08-05 18:07:49 -07001589 // build the h/w work list
1590 if (CC_UNLIKELY(mGeometryInvalid)) {
1591 mGeometryInvalid = false;
1592 for (const auto& [token, display] : mDisplays) {
1593 const auto displayId = display->getId();
1594 if (displayId >= 0) {
1595 const Vector<sp<Layer>>& currentLayers(
1596 display->getVisibleLayersSortedByZ());
1597 for (size_t i = 0; i < currentLayers.size(); i++) {
1598 const auto& layer = currentLayers[i];
1599
1600 if (!layer->hasHwcLayer(displayId)) {
1601 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1602 layer->forceClientComposition(displayId);
1603 continue;
1604 }
1605 }
1606
1607 layer->setGeometry(display, i);
1608 if (mDebugDisableHWC || mDebugRegion) {
1609 layer->forceClientComposition(displayId);
1610 }
1611 }
1612 }
1613 }
1614 }
1615
1616 // Set the per-frame data
1617 for (const auto& [token, display] : mDisplays) {
1618 const auto displayId = display->getId();
1619 if (displayId < 0) {
1620 continue;
1621 }
1622
1623 if (mDrawingState.colorMatrixChanged) {
1624 display->setColorTransform(mDrawingState.colorMatrix);
1625 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1626 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1627 "display %d: %d", displayId, result);
1628 }
1629 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1630 if (layer->isHdrY410()) {
1631 layer->forceClientComposition(displayId);
1632 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1633 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1634 !display->hasHDR10Support()) {
1635 layer->forceClientComposition(displayId);
1636 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1637 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1638 !display->hasHLGSupport()) {
1639 layer->forceClientComposition(displayId);
1640 }
1641
Peiyong Lind3788632018-09-18 16:01:31 -07001642 // TODO(b/111562338) remove when composer 2.3 is shipped.
1643 if (layer->hasColorTransform()) {
1644 layer->forceClientComposition(displayId);
1645 }
1646
David Sodman79bba0e2018-08-05 18:07:49 -07001647 if (layer->getForceClientComposition(displayId)) {
1648 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1649 layer->setCompositionType(displayId, HWC2::Composition::Client);
1650 continue;
1651 }
1652
1653 layer->setPerFrameData(display);
1654 }
1655
Peiyong Lin13effd12018-07-24 17:01:47 -07001656 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001657 ColorMode colorMode;
1658 Dataspace dataSpace;
1659 RenderIntent renderIntent;
1660 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1661 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1662 }
1663 }
1664
1665 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001666
1667 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001668 getBE().mCompositionInfo[token].clear();
1669
David Sodmanba340492018-08-05 21:51:33 -07001670 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001671 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001672 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1673 if (!layer->setHwcLayer(displayId)) {
1674 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1675 }
David Sodman15fb96e2018-01-07 10:23:24 -08001676 layer->getBE().compositionInfo.hwc.displayId = displayId;
Dominik Laskowski05275f12018-11-01 15:03:24 -07001677 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001678 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1679 }
1680 }
David Sodman79bba0e2018-08-05 18:07:49 -07001681}
1682
David Sodmanfa9b2af2017-12-24 13:28:59 -08001683void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001684{
1685 // is debugging enabled
1686 if (CC_LIKELY(!mDebugRegion))
1687 return;
1688
David Sodmanfa9b2af2017-12-24 13:28:59 -08001689 if (display->isPoweredOn()) {
1690 // transform the dirty region into this screen's coordinate space
1691 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1692 if (!dirtyRegion.isEmpty()) {
1693 // redraw the whole screen
1694 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001695
David Sodmanfa9b2af2017-12-24 13:28:59 -08001696 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001697 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001698 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001699
David Sodmanfa9b2af2017-12-24 13:28:59 -08001700 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001701 }
1702 }
1703
David Sodmanfa9b2af2017-12-24 13:28:59 -08001704 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001705
1706 if (mDebugRegion > 1) {
1707 usleep(mDebugRegion * 1000);
1708 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001709
Dominik Laskowski05275f12018-11-01 15:03:24 -07001710 prepareFrame(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001711}
1712
Adrian Roos1e1a1282017-11-01 19:05:31 +01001713void SurfaceFlinger::doTracing(const char* where) {
1714 ATRACE_CALL();
1715 ATRACE_NAME(where);
1716 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001717 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001718 }
1719}
1720
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001721void SurfaceFlinger::logLayerStats() {
1722 ATRACE_CALL();
1723 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001724 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001725 if (display->isPrimary()) {
1726 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001727 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001728 }
1729 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001730
1731 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001732 }
1733}
1734
David Sodman2b406362017-12-15 13:33:47 -08001735void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001736{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001737 ATRACE_CALL();
1738 ALOGV("preComposition");
1739
David Sodman2b406362017-12-15 13:33:47 -08001740 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1741
Mathias Agopiancd60f992012-08-16 16:28:27 -07001742 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001743 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001744 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001745 needExtraInvalidate = true;
1746 }
Robert Carr2047fae2016-11-28 14:09:09 -08001747 });
1748
Mathias Agopiancd60f992012-08-16 16:28:27 -07001749 if (needExtraInvalidate) {
1750 signalLayerUpdate();
1751 }
1752}
1753
Ana Krulece588e312018-09-18 12:32:24 -07001754void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1755 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001756 // Update queue of past composite+present times and determine the
1757 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001758 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001759 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001760 while (!getBE().mCompositePresentTimes.empty()) {
1761 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001762 // Cached values should have been updated before calling this method,
1763 // which helps avoid duplicate syscalls.
1764 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1765 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1766 break;
1767 }
1768 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001769 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001770 }
1771
1772 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001773 while (getBE().mCompositePresentTimes.size() > 16) {
1774 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001775 }
1776
Ana Krulece588e312018-09-18 12:32:24 -07001777 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001778}
1779
Ana Krulece588e312018-09-18 12:32:24 -07001780void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1781 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001782 // Integer division and modulo round toward 0 not -inf, so we need to
1783 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001784 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1785 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1786 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001787
Brian Andersond0010582017-03-07 13:20:31 -08001788 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1789 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001790 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001791 }
1792
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001793 // Snap the latency to a value that removes scheduling jitter from the
1794 // composition and present times, which often have >1ms of jitter.
1795 // Reducing jitter is important if an app attempts to extrapolate
1796 // something (such as user input) to an accurate diasplay time.
1797 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1798 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001799 nsecs_t bias = stats.vsyncPeriod / 2;
1800 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1801 nsecs_t snappedCompositeToPresentLatency =
1802 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001803
David Sodman99974d22017-11-28 12:04:33 -08001804 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001805 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1806 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001807 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001808}
1809
David Sodman2b406362017-12-15 13:33:47 -08001810void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001811{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001812 ATRACE_CALL();
1813 ALOGV("postComposition");
1814
Brian Anderson3546a3f2016-07-14 11:51:14 -07001815 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001816 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001817 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001818 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001819 }
1820
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001821 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001822 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001823
David Sodman73beded2017-11-15 11:56:06 -08001824 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001825 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001826 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001827 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001828 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001829 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001830 } else {
1831 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1832 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001833
David Sodman73beded2017-11-15 11:56:06 -08001834 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001835 mPreviousPresentFence =
1836 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1837 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001838 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001839
Ana Krulece588e312018-09-18 12:32:24 -07001840 DisplayStatInfo stats;
1841 if (mUseScheduler) {
1842 mScheduler->getDisplayStatInfo(&stats);
1843 } else {
1844 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1845 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
1846 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001847
David Sodman2b406362017-12-15 13:33:47 -08001848 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001849 // when we started doing work for this frame, but that should be okay
1850 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07001851 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001852 CompositorTiming compositorTiming;
1853 {
David Sodman99974d22017-11-28 12:04:33 -08001854 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1855 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001856 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001857
Robert Carr2047fae2016-11-28 14:09:09 -08001858 mDrawingState.traverseInZOrder([&](Layer* layer) {
1859 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001860 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001861 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001862 recordBufferingStats(layer->getName().string(),
1863 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001864 }
Robert Carr2047fae2016-11-28 14:09:09 -08001865 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001866
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001867 if (presentFenceTime->isValid()) {
Ana Krulece588e312018-09-18 12:32:24 -07001868 if (mUseScheduler) {
1869 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001870 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001871 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
1872 enableHardwareVsync();
1873 } else {
1874 disableHardwareVsync(false);
1875 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001876 }
1877 }
1878
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001879 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001880 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07001881 if (mUseScheduler) {
1882 mScheduler->enableHardwareVsync();
1883 } else {
1884 enableHardwareVsync();
1885 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001886 }
1887 }
1888
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001889 if (mAnimCompositionPending) {
1890 mAnimCompositionPending = false;
1891
Brian Anderson4e606e32017-03-16 15:34:57 -07001892 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001893 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001894 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001895 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001896 // The HWC doesn't support present fences, so use the refresh
1897 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001898 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001899 mAnimFrameTracker.setActualPresentTime(presentTime);
1900 }
1901 mAnimFrameTracker.advanceFrame();
1902 }
Dan Stozab90cf072015-03-05 11:05:59 -08001903
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001904 mTimeStats.incrementTotalFrames();
1905 if (mHadClientComposition) {
1906 mTimeStats.incrementClientCompositionFrames();
1907 }
1908
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001909 mTimeStats.setPresentFenceGlobal(presentFenceTime);
1910
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001911 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001912 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001913 return;
1914 }
1915
1916 nsecs_t currentTime = systemTime();
1917 if (mHasPoweredOff) {
1918 mHasPoweredOff = false;
1919 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001920 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001921 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001922 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1923 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001924 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001925 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001926 }
David Sodman4a36e932017-11-07 14:29:47 -08001927 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001928 }
David Sodman4a36e932017-11-07 14:29:47 -08001929 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001930
1931 {
1932 std::lock_guard lock(mTexturePoolMutex);
1933 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1934 if (refillCount > 0) {
1935 const size_t offset = mTexturePool.size();
1936 mTexturePool.resize(mTexturePoolSize);
1937 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1938 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1939 }
1940 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001941}
1942
1943void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001944 ATRACE_CALL();
1945 ALOGV("rebuildLayerStacks");
1946
Mathias Agopiancd60f992012-08-16 16:28:27 -07001947 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001948 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001949 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001950 mVisibleRegionsDirty = false;
1951 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001952
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001953 for (const auto& pair : mDisplays) {
1954 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001955 Region opaqueRegion;
1956 Region dirtyRegion;
1957 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001958 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001959 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001960 const Rect bounds = display->getBounds();
1961 if (display->isPoweredOn()) {
1962 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001963
Jeff Sharkey76488112017-02-27 14:15:18 -07001964 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001965 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001966 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001967 Region drawRegion(tr.transform(
1968 layer->visibleNonTransparentRegion));
1969 drawRegion.andSelf(bounds);
1970 if (!drawRegion.isEmpty()) {
1971 layersSortedByZ.add(layer);
1972 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001973 // Clear out the HWC layer if this layer was
1974 // previously visible, but no longer is
1975 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001976 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001977 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001978 // WM changes display->layerStack upon sleep/awake.
1979 // Here we make sure we delete the HWC layers even if
1980 // WM changed their layer stack.
1981 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001982 }
1983
1984 // If a layer is not going to get a release fence because
1985 // it is invisible, but it is also going to release its
1986 // old buffer, add it to the list of layers needing
1987 // fences.
1988 if (hwcLayerDestroyed) {
1989 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1990 mLayersWithQueuedFrames.cend(), layer);
1991 if (found != mLayersWithQueuedFrames.cend()) {
1992 layersNeedingFences.add(layer);
1993 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001994 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001995 });
1996 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001997 display->setVisibleLayersSortedByZ(layersSortedByZ);
1998 display->setLayersNeedingFences(layersNeedingFences);
1999 display->undefinedRegion.set(bounds);
2000 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2001 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002002 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002003 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002004}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002005
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002006// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002007// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002008// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002009// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002010// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002011// The returned HDR data space is one of
2012// - Dataspace::UNKNOWN
2013// - Dataspace::BT2020_HLG
2014// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002015Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2016 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07002017 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002018 *outHdrDataSpace = Dataspace::UNKNOWN;
2019
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002020 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002021 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002022 case Dataspace::V0_SCRGB:
2023 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002024 case Dataspace::BT2020:
2025 case Dataspace::BT2020_ITU:
2026 case Dataspace::BT2020_LINEAR:
2027 case Dataspace::DISPLAY_BT2020:
2028 bestDataSpace = Dataspace::DISPLAY_BT2020;
2029 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002030 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002031 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002032 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002033 case Dataspace::BT2020_PQ:
2034 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002035 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002036 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002037 case Dataspace::BT2020_HLG:
2038 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002039 // When there's mixed PQ content and HLG content, we set the HDR
2040 // data space to be BT2020_PQ and convert HLG to PQ.
2041 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2042 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002043 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002044 break;
2045 default:
2046 break;
2047 }
Romain Guy54f154a2017-10-24 21:40:32 +01002048 }
2049
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002050 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002051}
2052
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002053// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002054void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2055 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002056 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2057 *outMode = ColorMode::NATIVE;
2058 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002059 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002060 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002061 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002062
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002063 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002064 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002065
Peiyong Lindfde5112018-06-05 10:58:41 -07002066 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002067 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002068 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002069 if (isHdr) {
2070 bestDataSpace = hdrDataSpace;
2071 }
2072
Chia-I Wu0d711262018-05-21 15:19:35 -07002073 RenderIntent intent;
2074 switch (mDisplayColorSetting) {
2075 case DisplayColorSetting::MANAGED:
2076 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002077 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002078 break;
2079 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002080 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002081 break;
2082 default: // vendor display color setting
2083 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2084 break;
2085 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002086
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002087 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002088}
2089
David Sodmanfa9b2af2017-12-24 13:28:59 -08002090void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002091{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002092 bool dirty = !display->getDirtyRegion(false).isEmpty();
2093 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2094 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002095
David Sodmanfa9b2af2017-12-24 13:28:59 -08002096 // If nothing has changed (!dirty), don't recompose.
2097 // If something changed, but we don't currently have any visible layers,
2098 // and didn't when we last did a composition, then skip it this time.
2099 // The second rule does two things:
2100 // - When all layers are removed from a display, we'll emit one black
2101 // frame, then nothing more until we get new layers.
2102 // - When a display is created with a private layer stack, we won't
2103 // emit any black frames until a layer is added to the layer stack.
2104 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002105
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002106 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2107 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002108 mustRecompose ? "doing" : "skipping",
2109 dirty ? "+" : "-",
2110 empty ? "+" : "-",
2111 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002112
David Sodmanfa9b2af2017-12-24 13:28:59 -08002113 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002114
David Sodmanfa9b2af2017-12-24 13:28:59 -08002115 if (mustRecompose) {
2116 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002117 }
2118}
2119
David Sodmanfa9b2af2017-12-24 13:28:59 -08002120void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002121{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002122 if (!display->isPoweredOn()) {
2123 return;
David Sodman2b406362017-12-15 13:33:47 -08002124 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002125
Dominik Laskowski05275f12018-11-01 15:03:24 -07002126 status_t result = display->prepareFrame(getHwComposer(),
2127 getBE().mCompositionInfo[display->getDisplayToken()]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08002128 ALOGE_IF(result != NO_ERROR,
2129 "prepareFrame for display %d failed:"
2130 " %d (%s)",
2131 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002132}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002133
David Sodmanfa9b2af2017-12-24 13:28:59 -08002134void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002135 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002136 ALOGV("doComposition");
2137
David Sodmanfa9b2af2017-12-24 13:28:59 -08002138 if (display->isPoweredOn()) {
2139 // transform the dirty region into this screen's coordinate space
2140 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002141
David Sodmanfa9b2af2017-12-24 13:28:59 -08002142 // repaint the framebuffer (if needed)
2143 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002144
David Sodmanfa9b2af2017-12-24 13:28:59 -08002145 display->dirtyRegion.clear();
2146 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002147 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002148 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002149}
2150
David Sodmanfa9b2af2017-12-24 13:28:59 -08002151void SurfaceFlinger::postFrame()
2152{
2153 // |mStateLock| not needed as we are on the main thread
2154 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2155 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2156 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2157 logFrameStats();
2158 }
2159 }
2160}
2161
2162void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002163{
Mathias Agopian841cde52012-03-01 15:44:37 -08002164 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002165 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002166
David Sodmanfa9b2af2017-12-24 13:28:59 -08002167 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002168
David Sodmanfa9b2af2017-12-24 13:28:59 -08002169 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002170 const auto displayId = display->getId();
2171 if (displayId >= 0) {
2172 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002173 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002174 display->onSwapBuffersCompleted();
2175 display->makeCurrent();
David Sodman15094112018-10-11 09:39:37 -07002176 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002177 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002178
Chia-I Wu7b549592017-11-15 09:14:57 -08002179 // The layer buffer from the previous frame (if any) is released
2180 // by HWC only when the release fence from this frame (if any) is
2181 // signaled. Always get the release fence from HWC first.
David Sodman15094112018-10-11 09:39:37 -07002182 auto hwcLayer = layer->getHwcLayer(displayId);
2183 if (displayId >= 0) {
2184 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002185 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002186
2187 // If the layer was client composited in the previous frame, we
2188 // need to merge with the previous client target acquire fence.
2189 // Since we do not track that, always merge with the current
2190 // client target acquire fence when it is available, even though
2191 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002192 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002193 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002194 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002195 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002196
David Sodman15094112018-10-11 09:39:37 -07002197 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002198 }
Chia-I Wu83806892017-11-16 10:50:20 -08002199
2200 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002201 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002202 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002203 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002204 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002205 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002206 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002207 }
2208 }
2209
Dominik Laskowski7e045462018-05-30 13:02:02 -07002210 if (displayId >= 0) {
2211 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002212 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002213 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002214}
2215
Mathias Agopian87baae12012-07-31 12:38:26 -07002216void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002217{
Mathias Agopian841cde52012-03-01 15:44:37 -08002218 ATRACE_CALL();
2219
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002220 // here we keep a copy of the drawing state (that is the state that's
2221 // going to be overwritten by handleTransactionLocked()) outside of
2222 // mStateLock so that the side-effects of the State assignment
2223 // don't happen with mStateLock held (which can cause deadlocks).
2224 State drawingState(mDrawingState);
2225
Mathias Agopianca4d3602011-05-19 15:38:14 -07002226 Mutex::Autolock _l(mStateLock);
2227 const nsecs_t now = systemTime();
2228 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002229
Mathias Agopianca4d3602011-05-19 15:38:14 -07002230 // Here we're guaranteed that some transaction flags are set
2231 // so we can call handleTransactionLocked() unconditionally.
2232 // We call getTransactionFlags(), which will also clear the flags,
2233 // with mStateLock held to guarantee that mCurrentState won't change
2234 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002235
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002236 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002237 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002238 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002239
Mathias Agopianca4d3602011-05-19 15:38:14 -07002240 mLastTransactionTime = systemTime() - now;
2241 mDebugInTransaction = 0;
2242 invalidateHwcGeometry();
2243 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002244}
2245
Dominik Laskowski7e045462018-05-30 13:02:02 -07002246DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002247 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002248 // Figure out whether the event is for the primary display or an
2249 // external display by matching the Hwc display id against one for a
2250 // connected display. If we did not find a match, we then check what
2251 // displays are not already connected to determine the type. If we don't
2252 // have a connected primary display, we assume the new display is meant to
2253 // be the primary display, and then if we don't have an external display,
2254 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002255 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2256 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002257 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002258 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002259 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002260 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002261 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002262 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002263 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002264 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002265 return DisplayDevice::DISPLAY_EXTERNAL;
2266 }
2267
2268 return DisplayDevice::DISPLAY_ID_INVALID;
2269}
2270
Lloyd Piqueba04e622017-12-14 17:11:26 -08002271void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2272 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002273 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002274 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002275 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002276 continue;
2277 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002278
2279 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2280 ALOGE("External displays are not supported by the vr hardware composer.");
2281 continue;
2282 }
2283
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002284 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002285 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002286 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002287 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002288 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002289
2290 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002291 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002292 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002293 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002294 DisplayDeviceState info;
2295 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002296 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2297 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002298 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002299 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002300 mInterceptor->saveDisplayCreation(info);
2301 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002302 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002303 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002304
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002305 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002306 if (idx >= 0) {
2307 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002308 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002309 mCurrentState.displays.removeItemsAt(idx);
2310 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002311 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002312 }
2313
2314 processDisplayChangesLocked();
2315 }
2316
2317 mPendingHotplugEvents.clear();
2318}
2319
Lloyd Pique99d3da52018-01-22 17:48:03 -08002320sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002321 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002322 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002323 DisplayDeviceCreationArgs creationArgs(this, displayToken, state.type, displayId);
2324 creationArgs.isSecure = state.isSecure;
2325 creationArgs.displaySurface = dispSurface;
2326 creationArgs.hasWideColorGamut = false;
2327 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002328
Peiyong Lin13effd12018-07-24 17:01:47 -07002329 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002330 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002331 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002332 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002333 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002334 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002335
Dominik Laskowski7e045462018-05-30 13:02:02 -07002336 std::vector<RenderIntent> renderIntents =
2337 getHwComposer().getRenderIntents(displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002338 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002339 }
tangrobin6753a022018-08-10 10:58:54 +08002340 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002341
tangrobin6753a022018-08-10 10:58:54 +08002342 if (displayId >= 0) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002343 getHwComposer().getHdrCapabilities(displayId, &creationArgs.hdrCapabilities);
2344 creationArgs.supportedPerFrameMetadata =
2345 getHwComposer().getSupportedPerFrameMetadata(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002346 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002347
Lloyd Pique90c115d2018-09-18 21:39:42 -07002348 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002349 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002350 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002351
2352 /*
2353 * Create our display's surface
2354 */
Peiyong Lin833074a2018-08-28 11:53:54 -07002355 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002356 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002357 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002358 renderSurface->setNativeWindow(nativeWindow.get());
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002359 creationArgs.displayWidth = renderSurface->getWidth();
2360 creationArgs.displayHeight = renderSurface->getHeight();
2361 creationArgs.renderSurface = std::move(renderSurface);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002362
2363 // Make sure that composition can never be stalled by a virtual display
2364 // consumer that isn't processing buffers fast enough. We have to do this
2365 // in two places:
2366 // * Here, in case the display is composed entirely by HWC.
2367 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2368 // window's swap interval in eglMakeCurrent, so they'll override the
2369 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002370 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002371 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2372 }
2373
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002374 creationArgs.displayInstallOrientation = state.type == DisplayDevice::DISPLAY_PRIMARY
2375 ? primaryDisplayOrientation
2376 : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002377
Lloyd Pique99d3da52018-01-22 17:48:03 -08002378 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002379 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002380
Lloyd Pique90c115d2018-09-18 21:39:42 -07002381 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002382
2383 if (maxFrameBufferAcquiredBuffers >= 3) {
2384 nativeWindowSurface->preallocateBuffers();
2385 }
2386
2387 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002388 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002389 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002390 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002391 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002392 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002393 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002394 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002395 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002396 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002397 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002398 display->setLayerStack(state.layerStack);
2399 display->setProjection(state.orientation, state.viewport, state.frame);
2400 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002401
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002402 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002403}
2404
Lloyd Pique347200f2017-12-14 17:00:15 -08002405void SurfaceFlinger::processDisplayChangesLocked() {
2406 // here we take advantage of Vector's copy-on-write semantics to
2407 // improve performance by skipping the transaction entirely when
2408 // know that the lists are identical
2409 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2410 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2411 if (!curr.isIdenticalTo(draw)) {
2412 mVisibleRegionsDirty = true;
2413 const size_t cc = curr.size();
2414 size_t dc = draw.size();
2415
2416 // find the displays that were removed
2417 // (ie: in drawing state but not in current state)
2418 // also handle displays that changed
2419 // (ie: displays that are in both lists)
2420 for (size_t i = 0; i < dc;) {
2421 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2422 if (j < 0) {
2423 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002424 // Call makeCurrent() on the primary display so we can
2425 // be sure that nothing associated with this display
2426 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002427 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2428 defaultDisplay->makeCurrent();
2429 }
2430 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2431 display->disconnect(getHwComposer());
2432 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002433 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002434 if (mUseScheduler) {
2435 mScheduler->hotplugReceived(mAppConnectionHandle,
2436 EventThread::DisplayType::Primary, false);
2437 } else {
2438 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2439 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002440 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002441 if (mUseScheduler) {
2442 mScheduler->hotplugReceived(mAppConnectionHandle,
2443 EventThread::DisplayType::External, false);
2444 } else {
2445 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2446 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002447 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002448 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002449 } else {
2450 // this display is in both lists. see if something changed.
2451 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002452 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002453 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2454 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2455 if (state_binder != draw_binder) {
2456 // changing the surface is like destroying and
2457 // recreating the DisplayDevice, so we just remove it
2458 // from the drawing state, so that it get re-added
2459 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002460 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2461 display->disconnect(getHwComposer());
2462 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002463 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002464 mDrawingState.displays.removeItemsAt(i);
2465 dc--;
2466 // at this point we must loop to the next item
2467 continue;
2468 }
2469
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002470 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002471 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002472 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002473 }
2474 if ((state.orientation != draw[i].orientation) ||
2475 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002476 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002477 }
2478 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002479 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002480 }
2481 }
2482 }
2483 ++i;
2484 }
2485
2486 // find displays that were added
2487 // (ie: in current state but not in drawing state)
2488 for (size_t i = 0; i < cc; i++) {
2489 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2490 const DisplayDeviceState& state(curr[i]);
2491
2492 sp<DisplaySurface> dispSurface;
2493 sp<IGraphicBufferProducer> producer;
2494 sp<IGraphicBufferProducer> bqProducer;
2495 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002496 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002497
Dominik Laskowski7e045462018-05-30 13:02:02 -07002498 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002499 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002500 // Virtual displays without a surface are dormant:
2501 // they have external state (layer stack, projection,
2502 // etc.) but no internal state (i.e. a DisplayDevice).
2503 if (state.surface != nullptr) {
2504 // Allow VR composer to use virtual displays.
2505 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2506 int width = 0;
2507 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2508 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2509 int height = 0;
2510 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2511 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2512 int intFormat = 0;
2513 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2514 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002515 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002516
Dominik Laskowski7e045462018-05-30 13:02:02 -07002517 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2518 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002519 }
2520
2521 // TODO: Plumb requested format back up to consumer
2522
2523 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002524 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002525 bqProducer, bqConsumer,
2526 state.displayName);
2527
2528 dispSurface = vds;
2529 producer = vds;
2530 }
2531 } else {
2532 ALOGE_IF(state.surface != nullptr,
2533 "adding a supported display, but rendering "
2534 "surface is provided (%p), ignoring it",
2535 state.surface.get());
2536
Dominik Laskowski7e045462018-05-30 13:02:02 -07002537 displayId = state.type;
2538 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002539 producer = bqProducer;
2540 }
2541
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002542 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002543 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002544 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002545 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002546 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002547 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002548 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002549 if (mUseScheduler) {
2550 mScheduler->hotplugReceived(mAppConnectionHandle,
2551 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002552 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002553 } else {
2554 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2555 true);
2556 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002557 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002558 if (mUseScheduler) {
2559 mScheduler->hotplugReceived(mAppConnectionHandle,
2560 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002561 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002562 } else {
2563 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2564 true);
2565 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002566 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002567 }
2568 }
2569 }
2570 }
2571 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002572
2573 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002574}
2575
Mathias Agopian87baae12012-07-31 12:38:26 -07002576void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002577{
Dan Stoza7dde5992015-05-22 09:51:44 -07002578 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002579 mCurrentState.traverseInZOrder([](Layer* layer) {
2580 layer->notifyAvailableFrames();
2581 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002582
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002583 /*
2584 * Traversal of the children
2585 * (perform the transaction for each of them if needed)
2586 */
2587
Mathias Agopian3559b072012-08-15 13:46:03 -07002588 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002589 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002590 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002591 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002592
2593 const uint32_t flags = layer->doTransaction(0);
2594 if (flags & Layer::eVisibleRegion)
2595 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002596 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002597 }
2598
2599 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002600 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002601 */
2602
Mathias Agopiane57f2922012-08-09 16:29:12 -07002603 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002604 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002605 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002606 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002607
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002608 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002609 // The transform hint might have changed for some layers
2610 // (either because a display has changed, or because a layer
2611 // as changed).
2612 //
2613 // Walk through all the layers in currentLayers,
2614 // and update their transform hint.
2615 //
2616 // If a layer is visible only on a single display, then that
2617 // display is used to calculate the hint, otherwise we use the
2618 // default display.
2619 //
2620 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2621 // the hint is set before we acquire a buffer from the surface texture.
2622 //
2623 // NOTE: layer transactions have taken place already, so we use their
2624 // drawing state. However, SurfaceFlinger's own transaction has not
2625 // happened yet, so we must use the current state layer list
2626 // (soon to become the drawing state list).
2627 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002628 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002629 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002630 bool first = true;
2631 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002632 // NOTE: we rely on the fact that layers are sorted by
2633 // layerStack first (so we don't have to traverse the list
2634 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002635 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002636 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002637 currentlayerStack = layerStack;
2638 // figure out if this layerstack is mirrored
2639 // (more than one display) if so, pick the default display,
2640 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002641 hintDisplay = nullptr;
2642 for (const auto& [token, display] : mDisplays) {
2643 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2644 if (hintDisplay) {
2645 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002646 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002647 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002648 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002649 }
2650 }
2651 }
2652 }
Chet Haase91d25932013-04-11 15:24:55 -07002653
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002654 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002655 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2656 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002657
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002658 // could be null when this layer is using a layerStack
2659 // that is not visible on any display. Also can occur at
2660 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002661 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002662 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002663
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002664 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002665 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002666 if (hintDisplay) {
2667 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002668 }
Robert Carr2047fae2016-11-28 14:09:09 -08002669
2670 first = false;
2671 });
Mathias Agopian84300952012-11-21 16:02:13 -08002672 }
2673
2674
Mathias Agopian3559b072012-08-15 13:46:03 -07002675 /*
2676 * Perform our own transaction if needed
2677 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002678
2679 if (mLayersAdded) {
2680 mLayersAdded = false;
2681 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002682 mVisibleRegionsDirty = true;
2683 }
2684
2685 // some layers might have been removed, so
2686 // we need to update the regions they're exposing.
2687 if (mLayersRemoved) {
2688 mLayersRemoved = false;
2689 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002690 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002691 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002692 // this layer is not visible anymore
2693 // TODO: we could traverse the tree from front to back and
2694 // compute the actual visible region
2695 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002696 Region visibleReg;
2697 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002698 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002699 }
Robert Carr2047fae2016-11-28 14:09:09 -08002700 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002701 }
2702
2703 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002704
2705 updateCursorAsync();
2706}
2707
2708void SurfaceFlinger::updateCursorAsync()
2709{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002710 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002711 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002712 continue;
2713 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002714
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002715 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2716 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002717 }
2718 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002719}
2720
2721void SurfaceFlinger::commitTransaction()
2722{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002723 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002724 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002725 for (const auto& l : mLayersPendingRemoval) {
2726 recordBufferingStats(l->getName().string(),
2727 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002728
2729 // We need to release the HWC layers when the Layer is removed
2730 // from the current state otherwise the HWC layer just continues
2731 // showing at its last configured state until we eventually
2732 // abandon the buffer queue.
2733 if (l->isRemovedFromCurrentState()) {
2734 l->destroyAllHwcLayers();
2735 l->releasePendingBuffer(systemTime());
2736 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002737 }
2738 mLayersPendingRemoval.clear();
2739 }
2740
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002741 // If this transaction is part of a window animation then the next frame
2742 // we composite should be considered an animation as well.
2743 mAnimCompositionPending = mAnimTransactionPending;
2744
Mathias Agopian4fec8732012-06-29 14:12:52 -07002745 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002746 // clear the "changed" flags in current state
2747 mCurrentState.colorMatrixChanged = false;
2748
Robert Carr1f0a16a2016-10-24 16:27:39 -07002749 mDrawingState.traverseInZOrder([](Layer* layer) {
2750 layer->commitChildList();
2751 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002752 mTransactionPending = false;
2753 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002754 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002755}
2756
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002757void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2758 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002759 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002760 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002761
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002762 Region aboveOpaqueLayers;
2763 Region aboveCoveredLayers;
2764 Region dirty;
2765
Mathias Agopian87baae12012-07-31 12:38:26 -07002766 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002767
Robert Carr2047fae2016-11-28 14:09:09 -08002768 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002769 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002770 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002771
Jesse Hall01e29052013-02-19 16:13:35 -08002772 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002773 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002774 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002775 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002776
Mathias Agopianab028732010-03-16 16:41:46 -07002777 /*
2778 * opaqueRegion: area of a surface that is fully opaque.
2779 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002780 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002781
2782 /*
2783 * visibleRegion: area of a surface that is visible on screen
2784 * and not fully transparent. This is essentially the layer's
2785 * footprint minus the opaque regions above it.
2786 * Areas covered by a translucent surface are considered visible.
2787 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002788 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002789
2790 /*
2791 * coveredRegion: area of a surface that is covered by all
2792 * visible regions above it (which includes the translucent areas).
2793 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002794 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002795
Jesse Halla8026d22012-09-25 13:25:04 -07002796 /*
2797 * transparentRegion: area of a surface that is hinted to be completely
2798 * transparent. This is only used to tell when the layer has no visible
2799 * non-transparent regions and can be removed from the layer list. It
2800 * does not affect the visibleRegion of this layer or any layers
2801 * beneath it. The hint may not be correct if apps don't respect the
2802 * SurfaceView restrictions (which, sadly, some don't).
2803 */
2804 Region transparentRegion;
2805
Mathias Agopianab028732010-03-16 16:41:46 -07002806
2807 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002808 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002809 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002810 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002811 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002812 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002813 if (!visibleRegion.isEmpty()) {
2814 // Remove the transparent area from the visible region
2815 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002816 if (tr.preserveRects()) {
2817 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002818 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002819 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002820 // transformation too complex, can't do the
2821 // transparent region optimization.
2822 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002823 }
Mathias Agopianab028732010-03-16 16:41:46 -07002824 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002825
Mathias Agopianab028732010-03-16 16:41:46 -07002826 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002827 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002828 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002829 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002830 // the opaque region is the layer's footprint
2831 opaqueRegion = visibleRegion;
2832 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002833 }
2834 }
2835
Robert Carre5f4f692018-01-12 13:12:28 -08002836 if (visibleRegion.isEmpty()) {
2837 layer->clearVisibilityRegions();
2838 return;
2839 }
2840
Mathias Agopianab028732010-03-16 16:41:46 -07002841 // Clip the covered region to the visible region
2842 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2843
2844 // Update aboveCoveredLayers for next (lower) layer
2845 aboveCoveredLayers.orSelf(visibleRegion);
2846
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002847 // subtract the opaque region covered by the layers above us
2848 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002849
2850 // compute this layer's dirty region
2851 if (layer->contentDirty) {
2852 // we need to invalidate the whole region
2853 dirty = visibleRegion;
2854 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002855 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002856 layer->contentDirty = false;
2857 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002858 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002859 * the exposed region consists of two components:
2860 * 1) what's VISIBLE now and was COVERED before
2861 * 2) what's EXPOSED now less what was EXPOSED before
2862 *
2863 * note that (1) is conservative, we start with the whole
2864 * visible region but only keep what used to be covered by
2865 * something -- which mean it may have been exposed.
2866 *
2867 * (2) handles areas that were not covered by anything but got
2868 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002869 */
Mathias Agopianab028732010-03-16 16:41:46 -07002870 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002871 const Region oldVisibleRegion = layer->visibleRegion;
2872 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002873 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2874 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002875 }
2876 dirty.subtractSelf(aboveOpaqueLayers);
2877
2878 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002879 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002880
Mathias Agopianab028732010-03-16 16:41:46 -07002881 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002882 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002883
Jesse Halla8026d22012-09-25 13:25:04 -07002884 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002885 layer->setVisibleRegion(visibleRegion);
2886 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002887 layer->setVisibleNonTransparentRegion(
2888 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002889 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002890
Mathias Agopian87baae12012-07-31 12:38:26 -07002891 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002892}
2893
Chia-I Wuab0c3192017-08-01 11:29:00 -07002894void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002895 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002896 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2897 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002898 }
2899 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002900}
2901
Dan Stoza6b9454d2014-11-07 16:00:59 -08002902bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002903{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002904 ALOGV("handlePageFlip");
2905
Brian Andersond6927fb2016-07-23 23:37:30 -07002906 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002907
Mathias Agopian4fec8732012-06-29 14:12:52 -07002908 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002909 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002910 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002911
2912 // Store the set of layers that need updates. This set must not change as
2913 // buffers are being latched, as this could result in a deadlock.
2914 // Example: Two producers share the same command stream and:
2915 // 1.) Layer 0 is latched
2916 // 2.) Layer 0 gets a new frame
2917 // 2.) Layer 1 gets a new frame
2918 // 3.) Layer 1 is latched.
2919 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2920 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002921 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002922 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002923 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002924 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2925 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002926 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002927 } else {
2928 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002929 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002930 } else {
2931 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002932 }
Robert Carr2047fae2016-11-28 14:09:09 -08002933 });
2934
Dan Stoza9e56aa02015-11-02 13:00:03 -08002935 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri86770e52018-09-24 22:40:58 +00002936 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
Dan Stozaee44edd2015-03-23 15:50:23 -07002937 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002938 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002939 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002940 newDataLatched = true;
2941 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002942 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002943
Alec Mouri86770e52018-09-24 22:40:58 +00002944 // Clear the renderengine fence here...
2945 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
2946 // clear instead of sp::clear.
2947 getBE().flushFence = Fence::NO_FENCE;
2948
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002949 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002950
2951 // If we will need to wake up at some time in the future to deal with a
2952 // queued frame that shouldn't be displayed during this vsync period, wake
2953 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002954 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002955 signalLayerUpdate();
2956 }
2957
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002958 // enter boot animation on first buffer latch
2959 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2960 ALOGI("Enter boot animation");
2961 mBootStage = BootStage::BOOTANIMATION;
2962 }
2963
Dan Stoza6b9454d2014-11-07 16:00:59 -08002964 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002965 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002966}
2967
Mathias Agopianad456f92011-01-13 17:53:01 -08002968void SurfaceFlinger::invalidateHwcGeometry()
2969{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002970 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002971}
2972
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002973void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2974 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002975 // We only need to actually compose the display if:
2976 // 1) It is being handled by hardware composer, which may need this to
2977 // keep its virtual display state machine in sync, or
2978 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002979 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002980 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002981 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002982 return;
2983 }
2984
Dan Stoza9e56aa02015-11-02 13:00:03 -08002985 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002986 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002987
2988 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002989 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002990}
2991
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002992bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002993 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002994
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002995 const Region bounds(display->bounds());
2996 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002997 const auto displayId = display->getId();
2998 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002999 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003000
Peiyong Lind3788632018-09-18 16:01:31 -07003001 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003002 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003003 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003004
Dan Stoza9e56aa02015-11-02 13:00:03 -08003005 if (hasClientComposition) {
3006 ALOGV("hasClientComposition");
3007
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003008 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003009 if (display->hasWideColorGamut()) {
3010 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003011 }
3012 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003013 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003014 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003015
Dominik Laskowski7e045462018-05-30 13:02:02 -07003016 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003017 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3018 HWC2::Capability::SkipClientColorTransform);
3019
Peiyong Lind3788632018-09-18 16:01:31 -07003020 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003021 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3022 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003023 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003024 }
3025
Chia-I Wud49d6692018-06-27 07:17:41 +08003026 // The current enhanced saturation matrix is designed to enhance Display P3,
3027 // thus we only apply this matrix when the render intent is not colorimetric
3028 // and the output color space is Display P3.
3029 needsEnhancedColorMatrix =
3030 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3031 outputDataspace == Dataspace::DISPLAY_P3);
3032 if (needsEnhancedColorMatrix) {
3033 colorMatrix *= mEnhancedSaturationMatrix;
3034 }
3035
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003036 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003037 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003038 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003039 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003040
3041 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003042 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3043 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3044 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003045 }
3046 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003047 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003048
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003049 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003050 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003051 // when using overlays, we assume a fully transparent framebuffer
3052 // NOTE: we could reduce how much we need to clear, for instance
3053 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003054 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003055 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003056 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003057 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003058 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003059 // we're left with the letterbox region
3060 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003061 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003062
3063 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003064 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003065
Mathias Agopianb9494d52012-04-18 02:28:45 -07003066 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003067 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003068 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003069 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003070 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003071 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003072
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003073 const Rect& bounds = display->getBounds();
3074 const Rect& scissor = display->getScissor();
3075 if (scissor != bounds) {
3076 // scissor doesn't match the screen's dimensions, so we
3077 // need to clear everything outside of it and enable
3078 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003079
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003080 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003081 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003082 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003083 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003084
Mathias Agopian85d751c2012-08-29 16:59:24 -07003085 /*
3086 * and then, render the layers targeted at the framebuffer
3087 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003088
Dan Stoza9e56aa02015-11-02 13:00:03 -08003089 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003090 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003091 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003092 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003093 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003094 displayTransform.transform(layer->visibleRegion)));
3095 ALOGV("Layer: %s", layer->getName().string());
3096 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003097 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003098 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003099 case HWC2::Composition::Cursor:
3100 case HWC2::Composition::Device:
3101 case HWC2::Composition::Sideband:
3102 case HWC2::Composition::SolidColor: {
David Sodmanc1498e62018-09-12 14:36:26 -07003103 const Layer::State& state(layer->getDrawingState());
3104 if (layer->getClearClientTarget(displayId) && !firstLayer &&
3105 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3106 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003107 // never clear the very first layer since we're
3108 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003109 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003110 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003111 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003112 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003113 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003114 if (layer->hasColorTransform()) {
3115 mat4 tmpMatrix;
3116 if (applyColorMatrix) {
3117 tmpMatrix = mDrawingState.colorMatrix;
3118 }
3119 tmpMatrix *= layer->getColorTransform();
3120 if (needsEnhancedColorMatrix) {
3121 tmpMatrix *= mEnhancedSaturationMatrix;
3122 }
3123 getRenderEngine().setColorTransform(tmpMatrix);
3124 } else {
3125 getRenderEngine().setColorTransform(colorMatrix);
3126 }
David Sodmanc1498e62018-09-12 14:36:26 -07003127 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003128 break;
3129 }
3130 default:
3131 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003132 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003133 } else {
3134 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003135 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003136 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003137 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003138
Peiyong Lind3788632018-09-18 16:01:31 -07003139 // Clear color transform matrix at the end of the frame.
3140 getRenderEngine().setColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003141
Mathias Agopianf45c5102012-10-24 16:29:17 -07003142 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003143 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003144 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003145}
3146
Chia-I Wu28e3a252018-09-07 12:05:02 -07003147void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003148 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003149 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003150}
3151
Dan Stoza7d89d062015-04-30 13:29:25 -07003152status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003153 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003154 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003155 const sp<Layer>& lbc,
3156 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003157{
Dan Stoza7d89d062015-04-30 13:29:25 -07003158 // add this layer to the current state list
3159 {
3160 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003161 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003162 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3163 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003164 return NO_MEMORY;
3165 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003166 if (parent == nullptr) {
3167 mCurrentState.layersSortedByZ.add(lbc);
3168 } else {
Robert Carr2e102c92018-10-23 12:11:15 -07003169 if (parent->isRemovedFromCurrentState()) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003170 ALOGE("addClientLayer called with a removed parent");
3171 return NAME_NOT_FOUND;
3172 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003173 parent->addChild(lbc);
3174 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003175
Yiwei Zhang243b3782018-05-15 17:40:04 -07003176 if (gbc != nullptr) {
3177 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3178 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3179 mMaxGraphicBufferProducerListSize,
3180 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3181 mGraphicBufferProducerList.size(),
3182 mMaxGraphicBufferProducerListSize, mNumLayers);
3183 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003184 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003185 }
3186
Mathias Agopian96f08192010-06-02 23:28:45 -07003187 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003188 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003189
Dan Stoza7d89d062015-04-30 13:29:25 -07003190 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003191}
3192
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003193status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003194 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003195 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3196}
Robert Carr7f9b8992017-03-10 11:08:39 -08003197
Robert Carr2e102c92018-10-23 12:11:15 -07003198status_t SurfaceFlinger::removeLayerLocked(const Mutex& lock, const sp<Layer>& layer,
chaviwca27f252018-02-06 16:46:39 -08003199 bool topLevelOnly) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003200 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003201 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003202 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003203 if (topLevelOnly) {
3204 return NO_ERROR;
3205 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003206 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003207 } else {
3208 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003209 }
3210
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003211 layer->onRemovedFromCurrentState();
Robert Carr2e102c92018-10-23 12:11:15 -07003212
3213 markLayerPendingRemovalLocked(lock, layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003214 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003215}
3216
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003217uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003218 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003219}
3220
Mathias Agopian3f844832013-08-07 21:24:32 -07003221uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003222 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003223}
3224
Mathias Agopian3f844832013-08-07 21:24:32 -07003225uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003226 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003227}
3228
3229uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003230 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003231 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003232 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003233 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003234 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003235 }
3236 return old;
3237}
3238
chaviwca27f252018-02-06 16:46:39 -08003239bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3240 for (const ComposerState& state : states) {
3241 // Here we need to check that the interface we're given is indeed
3242 // one of our own. A malicious client could give us a nullptr
3243 // IInterface, or one of its own or even one of our own but a
3244 // different type. All these situations would cause us to crash.
3245 if (state.client == nullptr) {
3246 return true;
3247 }
3248
3249 sp<IBinder> binder = IInterface::asBinder(state.client);
3250 if (binder == nullptr) {
3251 return true;
3252 }
3253
3254 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3255 return true;
3256 }
3257 }
3258 return false;
3259}
3260
Mathias Agopian8b33f032012-07-24 20:43:54 -07003261void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003262 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003263 const Vector<DisplayState>& displays,
3264 uint32_t flags)
3265{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003266 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003267 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003268 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003269
chaviwca27f252018-02-06 16:46:39 -08003270 if (containsAnyInvalidClientState(states)) {
3271 return;
3272 }
3273
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003274 if (flags & eAnimation) {
3275 // For window updates that are part of an animation we must wait for
3276 // previous animation "frames" to be handled.
3277 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003278 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003279 if (CC_UNLIKELY(err != NO_ERROR)) {
3280 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003281 // caller after a few seconds.
3282 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3283 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003284 mAnimTransactionPending = false;
3285 break;
3286 }
3287 }
3288 }
3289
chaviwca27f252018-02-06 16:46:39 -08003290 for (const DisplayState& display : displays) {
3291 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003292 }
3293
chaviwca27f252018-02-06 16:46:39 -08003294 for (const ComposerState& state : states) {
3295 transactionFlags |= setClientStateLocked(state);
3296 }
3297
3298 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3299 // as destroyed should only occur after setting all other states. This is to allow for a
3300 // child re-parent to happen before marking its original parent as destroyed (which would
3301 // then mark the child as destroyed).
3302 for (const ComposerState& state : states) {
3303 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003304 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003305
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003306 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3307 // anyway. This can be used as a flush mechanism for previous async transactions.
3308 // Empty animation transaction can be used to simulate back-pressure, so also force a
3309 // transaction for empty animation transactions.
3310 if (transactionFlags == 0 &&
3311 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003312 transactionFlags = eTransactionNeeded;
3313 }
3314
Mathias Agopian386aa982011-11-07 21:58:03 -08003315 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003316 if (mInterceptor->isEnabled()) {
3317 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003318 }
Irvel468051e2016-06-13 16:44:44 -07003319
Mathias Agopian386aa982011-11-07 21:58:03 -08003320 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003321 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3322 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003323 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003324
3325 // if this is a synchronous transaction, wait for it to take effect
3326 // before returning.
3327 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003328 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003329 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003330 if (flags & eAnimation) {
3331 mAnimTransactionPending = true;
3332 }
3333 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003334 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3335 if (CC_UNLIKELY(err != NO_ERROR)) {
3336 // just in case something goes wrong in SF, return to the
3337 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003338 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3339 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003340 break;
3341 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003342 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003343 }
3344}
3345
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003346uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3347 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3348 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003349
Mathias Agopiane57f2922012-08-09 16:29:12 -07003350 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003351 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3352
3353 const uint32_t what = s.what;
3354 if (what & DisplayState::eSurfaceChanged) {
3355 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3356 state.surface = s.surface;
3357 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003358 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003359 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003360 if (what & DisplayState::eLayerStackChanged) {
3361 if (state.layerStack != s.layerStack) {
3362 state.layerStack = s.layerStack;
3363 flags |= eDisplayTransactionNeeded;
3364 }
3365 }
3366 if (what & DisplayState::eDisplayProjectionChanged) {
3367 if (state.orientation != s.orientation) {
3368 state.orientation = s.orientation;
3369 flags |= eDisplayTransactionNeeded;
3370 }
3371 if (state.frame != s.frame) {
3372 state.frame = s.frame;
3373 flags |= eDisplayTransactionNeeded;
3374 }
3375 if (state.viewport != s.viewport) {
3376 state.viewport = s.viewport;
3377 flags |= eDisplayTransactionNeeded;
3378 }
3379 }
3380 if (what & DisplayState::eDisplaySizeChanged) {
3381 if (state.width != s.width) {
3382 state.width = s.width;
3383 flags |= eDisplayTransactionNeeded;
3384 }
3385 if (state.height != s.height) {
3386 state.height = s.height;
3387 flags |= eDisplayTransactionNeeded;
3388 }
3389 }
3390
Mathias Agopiane57f2922012-08-09 16:29:12 -07003391 return flags;
3392}
3393
Robert Carrd4ae7f32018-06-07 16:10:57 -07003394bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3395 IPCThreadState* ipc = IPCThreadState::self();
3396 const int pid = ipc->getCallingPid();
3397 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003398 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003399 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003400 return false;
3401 }
3402 return true;
3403}
3404
chaviwca27f252018-02-06 16:46:39 -08003405uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3406 const layer_state_t& s = composerState.state;
3407 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3408
Mathias Agopian13127d82013-03-05 17:47:11 -08003409 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003410 if (layer == nullptr) {
3411 return 0;
3412 }
3413
chaviw8b3871a2017-11-01 17:41:01 -07003414 uint32_t flags = 0;
3415
3416 const uint32_t what = s.what;
3417 bool geometryAppliesWithResize =
3418 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003419
3420 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3421 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003422 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003423 layer->pushPendingState();
3424 }
3425
chaviw8b3871a2017-11-01 17:41:01 -07003426 if (what & layer_state_t::ePositionChanged) {
3427 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3428 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003429 }
chaviw8b3871a2017-11-01 17:41:01 -07003430 }
3431 if (what & layer_state_t::eLayerChanged) {
3432 // NOTE: index needs to be calculated before we update the state
3433 const auto& p = layer->getParent();
3434 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003435 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003436 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003437 mCurrentState.layersSortedByZ.removeAt(idx);
3438 mCurrentState.layersSortedByZ.add(layer);
3439 // we need traversal (state changed)
3440 // AND transaction (list changed)
3441 flags |= eTransactionNeeded|eTraversalNeeded;
3442 }
chaviw8b3871a2017-11-01 17:41:01 -07003443 } else {
3444 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003445 flags |= eTransactionNeeded|eTraversalNeeded;
3446 }
3447 }
chaviw8b3871a2017-11-01 17:41:01 -07003448 }
3449 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003450 // NOTE: index needs to be calculated before we update the state
3451 const auto& p = layer->getParent();
3452 if (p == nullptr) {
3453 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3454 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3455 mCurrentState.layersSortedByZ.removeAt(idx);
3456 mCurrentState.layersSortedByZ.add(layer);
3457 // we need traversal (state changed)
3458 // AND transaction (list changed)
3459 flags |= eTransactionNeeded|eTraversalNeeded;
3460 }
3461 } else {
3462 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3463 flags |= eTransactionNeeded|eTraversalNeeded;
3464 }
chaviw8b3871a2017-11-01 17:41:01 -07003465 }
3466 }
3467 if (what & layer_state_t::eSizeChanged) {
3468 if (layer->setSize(s.w, s.h)) {
3469 flags |= eTraversalNeeded;
3470 }
3471 }
3472 if (what & layer_state_t::eAlphaChanged) {
3473 if (layer->setAlpha(s.alpha))
3474 flags |= eTraversalNeeded;
3475 }
3476 if (what & layer_state_t::eColorChanged) {
3477 if (layer->setColor(s.color))
3478 flags |= eTraversalNeeded;
3479 }
Peiyong Lind3788632018-09-18 16:01:31 -07003480 if (what & layer_state_t::eColorTransformChanged) {
3481 if (layer->setColorTransform(s.colorTransform)) {
3482 flags |= eTraversalNeeded;
3483 }
3484 }
chaviw8b3871a2017-11-01 17:41:01 -07003485 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003486 // TODO: b/109894387
3487 //
3488 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3489 // rotation. To see the problem observe that if we have a square parent, and a child
3490 // of the same size, then we rotate the child 45 degrees around it's center, the child
3491 // must now be cropped to a non rectangular 8 sided region.
3492 //
3493 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3494 // private API, and the WindowManager only uses rotation in one case, which is on a top
3495 // level layer in which cropping is not an issue.
3496 //
3497 // However given that abuse of rotation matrices could lead to surfaces extending outside
3498 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3499 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3500 // transformations.
3501 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003502 flags |= eTraversalNeeded;
3503 }
3504 if (what & layer_state_t::eTransparentRegionChanged) {
3505 if (layer->setTransparentRegionHint(s.transparentRegion))
3506 flags |= eTraversalNeeded;
3507 }
3508 if (what & layer_state_t::eFlagsChanged) {
3509 if (layer->setFlags(s.flags, s.mask))
3510 flags |= eTraversalNeeded;
3511 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003512 if (what & layer_state_t::eCropChanged_legacy) {
3513 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003514 flags |= eTraversalNeeded;
3515 }
chaviw8b3871a2017-11-01 17:41:01 -07003516 if (what & layer_state_t::eLayerStackChanged) {
3517 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3518 // We only allow setting layer stacks for top level layers,
3519 // everything else inherits layer stack from its parent.
3520 if (layer->hasParent()) {
3521 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3522 layer->getName().string());
3523 } else if (idx < 0) {
3524 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3525 "that also does not appear in the top level layer list. Something"
3526 " has gone wrong.", layer->getName().string());
3527 } else if (layer->setLayerStack(s.layerStack)) {
3528 mCurrentState.layersSortedByZ.removeAt(idx);
3529 mCurrentState.layersSortedByZ.add(layer);
3530 // we need traversal (state changed)
3531 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003532 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003533 }
3534 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003535 if (what & layer_state_t::eDeferTransaction_legacy) {
3536 if (s.barrierHandle_legacy != nullptr) {
3537 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3538 } else if (s.barrierGbp_legacy != nullptr) {
3539 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003540 if (authenticateSurfaceTextureLocked(gbp)) {
3541 const auto& otherLayer =
3542 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003543 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003544 } else {
3545 ALOGE("Attempt to defer transaction to to an"
3546 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003547 }
3548 }
chaviw8b3871a2017-11-01 17:41:01 -07003549 // We don't trigger a traversal here because if no other state is
3550 // changed, we don't want this to cause any more work
3551 }
3552 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003553 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003554 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003555 if (!hadParent) {
3556 mCurrentState.layersSortedByZ.remove(layer);
3557 }
chaviw8b3871a2017-11-01 17:41:01 -07003558 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003559 }
chaviw8b3871a2017-11-01 17:41:01 -07003560 }
3561 if (what & layer_state_t::eReparentChildren) {
3562 if (layer->reparentChildren(s.reparentHandle)) {
3563 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003564 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003565 }
chaviw8b3871a2017-11-01 17:41:01 -07003566 if (what & layer_state_t::eDetachChildren) {
3567 layer->detachChildren();
3568 }
3569 if (what & layer_state_t::eOverrideScalingModeChanged) {
3570 layer->setOverrideScalingMode(s.overrideScalingMode);
3571 // We don't trigger a traversal here because if no other state is
3572 // changed, we don't want this to cause any more work
3573 }
Marissa Wall61c58622018-07-18 10:12:20 -07003574 if (what & layer_state_t::eTransformChanged) {
3575 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3576 }
3577 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3578 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3579 flags |= eTraversalNeeded;
3580 }
3581 if (what & layer_state_t::eCropChanged) {
3582 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3583 }
3584 if (what & layer_state_t::eBufferChanged) {
3585 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3586 }
3587 if (what & layer_state_t::eAcquireFenceChanged) {
3588 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3589 }
3590 if (what & layer_state_t::eDataspaceChanged) {
3591 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3592 }
3593 if (what & layer_state_t::eHdrMetadataChanged) {
3594 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3595 }
3596 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3597 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3598 }
3599 if (what & layer_state_t::eApiChanged) {
3600 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3601 }
3602 if (what & layer_state_t::eSidebandStreamChanged) {
3603 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3604 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003605 return flags;
3606}
3607
chaviwca27f252018-02-06 16:46:39 -08003608void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3609 const layer_state_t& state = composerState.state;
3610 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3611
3612 sp<Layer> layer(client->getLayerUser(state.surface));
3613 if (layer == nullptr) {
3614 return;
3615 }
3616
chaviwca27f252018-02-06 16:46:39 -08003617 if (state.what & layer_state_t::eDestroySurface) {
3618 removeLayerLocked(mStateLock, layer);
3619 }
3620}
3621
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003622status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003623 const String8& name,
3624 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003625 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003626 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003627 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003628{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003629 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003630 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003631 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003632 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003633 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003634
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003635 status_t result = NO_ERROR;
3636
3637 sp<Layer> layer;
3638
Cody Northropbc755282017-03-31 12:00:08 -06003639 String8 uniqueName = getUniqueLayerName(name);
3640
Mathias Agopian3165cc22012-08-08 19:42:09 -07003641 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003642 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003643 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3644 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003645
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003646 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003647 case ISurfaceComposerClient::eFXSurfaceBufferState:
3648 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3649 break;
chaviw13fdc492017-06-27 12:40:18 -07003650 case ISurfaceComposerClient::eFXSurfaceColor:
3651 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003652 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003653 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003654 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003655 case ISurfaceComposerClient::eFXSurfaceContainer:
3656 result = createContainerLayer(client,
3657 uniqueName, w, h, flags,
3658 handle, &layer);
3659 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003660 default:
3661 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003662 break;
3663 }
3664
Dan Stoza7d89d062015-04-30 13:29:25 -07003665 if (result != NO_ERROR) {
3666 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003667 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003668
Chia-I Wuab0c3192017-08-01 11:29:00 -07003669 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3670 // TODO b/64227542
3671 if (windowType == 441731) {
3672 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3673 layer->setPrimaryDisplayOnly();
3674 }
3675
Albert Chaulk479c60c2017-01-27 14:21:34 -05003676 layer->setInfo(windowType, ownerUid);
3677
Robert Carr1f0a16a2016-10-24 16:27:39 -07003678 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003679 if (result != NO_ERROR) {
3680 return result;
3681 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003682 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003683
3684 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003685 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003686}
3687
Cody Northropbc755282017-03-31 12:00:08 -06003688String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3689{
3690 bool matchFound = true;
3691 uint32_t dupeCounter = 0;
3692
3693 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3694 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3695
Dan Stoza436ccf32018-06-21 12:10:12 -07003696 // Grab the state lock since we're accessing mCurrentState
3697 Mutex::Autolock lock(mStateLock);
3698
Cody Northropbc755282017-03-31 12:00:08 -06003699 // Loop over layers until we're sure there is no matching name
3700 while (matchFound) {
3701 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003702 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003703 if (layer->getName() == uniqueName) {
3704 matchFound = true;
3705 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3706 }
3707 });
3708 }
3709
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003710 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3711 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003712
3713 return uniqueName;
3714}
3715
Marissa Wallfd668622018-05-10 10:21:13 -07003716status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3717 uint32_t w, uint32_t h, uint32_t flags,
3718 PixelFormat& format, sp<IBinder>* handle,
3719 sp<IGraphicBufferProducer>* gbp,
3720 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003721 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003722 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003723 case PIXEL_FORMAT_TRANSPARENT:
3724 case PIXEL_FORMAT_TRANSLUCENT:
3725 format = PIXEL_FORMAT_RGBA_8888;
3726 break;
3727 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003728 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003729 break;
3730 }
3731
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003732 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003733 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003734 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003735 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003736 *handle = layer->getHandle();
3737 *gbp = layer->getProducer();
3738 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003739 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003740
Marissa Wallfd668622018-05-10 10:21:13 -07003741 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003742 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003743}
3744
Marissa Wall61c58622018-07-18 10:12:20 -07003745status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3746 uint32_t w, uint32_t h, uint32_t flags,
3747 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003748 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003749 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003750 *handle = layer->getHandle();
3751 *outLayer = layer;
3752
3753 return NO_ERROR;
3754}
3755
chaviw13fdc492017-06-27 12:40:18 -07003756status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003757 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003758 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003759{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003760 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003761 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003762 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003763}
3764
Robert Carr6b3f6c52018-08-13 13:05:17 -07003765status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3766 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3767 sp<IBinder>* handle, sp<Layer>* outLayer)
3768{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003769 *outLayer =
3770 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003771 *handle = (*outLayer)->getHandle();
3772 return NO_ERROR;
3773}
3774
3775
Mathias Agopianac9fa422013-02-11 16:40:36 -08003776status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003777{
Robert Carr9524cb32017-02-13 11:32:32 -08003778 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003779 status_t err = NO_ERROR;
3780 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003781 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003782 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003783 err = removeLayer(l);
3784 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3785 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003786 }
3787 return err;
3788}
3789
Robert Carr2e102c92018-10-23 12:11:15 -07003790void SurfaceFlinger::markLayerPendingRemovalLocked(const Mutex&, const sp<Layer>& layer) {
3791 mLayersPendingRemoval.add(layer);
3792 mLayersRemoved = true;
3793 setTransactionFlags(eTransactionNeeded);
3794}
3795
3796void SurfaceFlinger::onHandleDestroyed(const sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003797{
Robert Carr2e102c92018-10-23 12:11:15 -07003798 Mutex::Autolock lock(mStateLock);
3799 markLayerPendingRemovalLocked(mStateLock, layer);
Rob Carr4bba3702018-10-08 21:53:30 +00003800}
3801
Mathias Agopianb60314a2012-04-10 22:09:54 -07003802// ---------------------------------------------------------------------------
3803
Andy McFadden13a082e2012-08-24 10:16:42 -07003804void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003805 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3806 if (!displayToken) return;
3807
Jesse Hall01e29052013-02-19 16:13:35 -08003808 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003809 Vector<ComposerState> state;
3810 Vector<DisplayState> displays;
3811 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003812 d.what = DisplayState::eDisplayProjectionChanged |
3813 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003814 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003815 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003816 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003817 d.frame.makeInvalid();
3818 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003819 d.width = 0;
3820 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003821 displays.add(d);
3822 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003823
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003824 const auto display = getDisplayDevice(displayToken);
3825 if (!display) return;
3826
3827 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3828
3829 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003830 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003831 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003832
Brian Andersond0010582017-03-07 13:20:31 -08003833 // Use phase of 0 since phase is not known.
3834 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07003835 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
3836 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003837}
3838
3839void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003840 // Async since we may be called from the main thread.
3841 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003842}
3843
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003844void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3845 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003846 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003847 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003848
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003849 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003850 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003851 return;
3852 }
3853
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003854 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003855 ALOGW("Trying to set power mode for virtual display");
3856 return;
3857 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003858
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003859 display->setPowerMode(mode);
3860
Lloyd Pique4dccc412018-01-22 17:21:36 -08003861 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003862 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003863 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003864 if (idx < 0) {
3865 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3866 return;
3867 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003868 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003869 }
3870
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003871 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003872 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003873 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003874 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003875 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003876 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003877 if (mUseScheduler) {
3878 mScheduler->onScreenAcquired(mAppConnectionHandle);
3879 } else {
3880 mEventThread->onScreenAcquired();
3881 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07003882 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003883 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003884
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003885 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003886 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003887 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003888
3889 struct sched_param param = {0};
3890 param.sched_priority = 1;
3891 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3892 ALOGW("Couldn't set SCHED_FIFO on display on");
3893 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003894 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003895 // Turn off the display
3896 struct sched_param param = {0};
3897 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3898 ALOGW("Couldn't set SCHED_OTHER on display off");
3899 }
3900
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003901 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07003902 if (mUseScheduler) {
3903 mScheduler->disableHardwareVsync(true);
3904 } else {
3905 disableHardwareVsync(true); // also cancels any in-progress resync
3906 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07003907 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003908 if (mUseScheduler) {
3909 mScheduler->onScreenReleased(mAppConnectionHandle);
3910 } else {
3911 mEventThread->onScreenReleased();
3912 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07003913 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003914
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003915 getHwComposer().setPowerMode(type, mode);
3916 mVisibleRegionsDirty = true;
3917 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003918 } else if (mode == HWC_POWER_MODE_DOZE ||
3919 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003920 // Update display while dozing
3921 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003922 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003923 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003924 if (mUseScheduler) {
3925 mScheduler->onScreenAcquired(mAppConnectionHandle);
3926 } else {
3927 mEventThread->onScreenAcquired();
3928 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003929 resyncToHardwareVsync(true);
3930 }
3931 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3932 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003933 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07003934 if (mUseScheduler) {
3935 mScheduler->disableHardwareVsync(true);
3936 } else {
3937 disableHardwareVsync(true); // also cancels any in-progress resync
3938 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003939 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003940 if (mUseScheduler) {
3941 mScheduler->onScreenReleased(mAppConnectionHandle);
3942 } else {
3943 mEventThread->onScreenReleased();
3944 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003945 }
3946 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003947 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003948 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003949 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003950 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003951
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003952 if (display->isPrimary()) {
3953 mTimeStats.setPowerMode(mode);
3954 }
3955
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003956 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003957}
3958
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003959void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003960 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003961 const auto display = getDisplayDevice(displayToken);
3962 if (!display) {
3963 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3964 displayToken.get());
3965 } else if (display->isVirtual()) {
3966 ALOGW("Attempt to set power mode %d for virtual display", mode);
3967 } else {
3968 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003969 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003970 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003971}
3972
3973// ---------------------------------------------------------------------------
3974
Lloyd Pique755e3192018-01-31 16:46:15 -08003975status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3976 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003977 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003978
Mathias Agopianbd115332013-04-18 16:41:04 -07003979 IPCThreadState* ipc = IPCThreadState::self();
3980 const int pid = ipc->getCallingPid();
3981 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003982
Mathias Agopianbd115332013-04-18 16:41:04 -07003983 if ((uid != AID_SHELL) &&
3984 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003985 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003986 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003987 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003988 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003989 // (this would indicate SF is stuck, but we want to be able to
3990 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003991 status_t err = mStateLock.timedLock(s2ns(1));
3992 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003993 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003994 result.appendFormat(
3995 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3996 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003997 }
3998
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003999 bool dumpAll = true;
4000 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004001 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004002
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004003 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004004 if ((index < numArgs) &&
4005 (args[index] == String16("--list"))) {
4006 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004007 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004008 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004009 }
4010
4011 if ((index < numArgs) &&
4012 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004013 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004014 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004015 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004016 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004017
4018 if ((index < numArgs) &&
4019 (args[index] == String16("--latency-clear"))) {
4020 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004021 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004022 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004023 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004024
4025 if ((index < numArgs) &&
4026 (args[index] == String16("--dispsync"))) {
4027 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004028 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004029 dumpAll = false;
4030 }
Dan Stozab90cf072015-03-05 11:05:59 -08004031
4032 if ((index < numArgs) &&
4033 (args[index] == String16("--static-screen"))) {
4034 index++;
4035 dumpStaticScreenStats(result);
4036 dumpAll = false;
4037 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004038
4039 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004040 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004041 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004042 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004043 dumpAll = false;
4044 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004045
4046 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4047 index++;
4048 dumpWideColorInfo(result);
4049 dumpAll = false;
4050 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004051
4052 if ((index < numArgs) &&
4053 (args[index] == String16("--enable-layer-stats"))) {
4054 index++;
4055 mLayerStats.enable();
4056 dumpAll = false;
4057 }
4058
4059 if ((index < numArgs) &&
4060 (args[index] == String16("--disable-layer-stats"))) {
4061 index++;
4062 mLayerStats.disable();
4063 dumpAll = false;
4064 }
4065
4066 if ((index < numArgs) &&
4067 (args[index] == String16("--clear-layer-stats"))) {
4068 index++;
4069 mLayerStats.clear();
4070 dumpAll = false;
4071 }
4072
4073 if ((index < numArgs) &&
4074 (args[index] == String16("--dump-layer-stats"))) {
4075 index++;
4076 mLayerStats.dump(result);
4077 dumpAll = false;
4078 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004079
4080 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004081 (args[index] == String16("--frame-composition"))) {
4082 index++;
4083 dumpFrameCompositionInfo(result);
4084 dumpAll = false;
4085 }
4086
4087 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004088 (args[index] == String16("--display-identification"))) {
4089 index++;
4090 dumpDisplayIdentificationData(result);
4091 dumpAll = false;
4092 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004093
4094 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4095 index++;
4096 mTimeStats.parseArgs(asProto, args, index, result);
4097 dumpAll = false;
4098 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004099 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004100
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004101 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004102 if (asProto) {
4103 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4104 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4105 } else {
4106 dumpAllLocked(args, index, result);
4107 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004108 }
4109
Mathias Agopian9795c422009-08-26 16:36:26 -07004110 if (locked) {
4111 mStateLock.unlock();
4112 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004113 }
4114 write(fd, result.string(), result.size());
4115 return NO_ERROR;
4116}
4117
Dan Stozac7014012014-02-14 15:03:43 -08004118void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4119 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004120{
Robert Carr2047fae2016-11-28 14:09:09 -08004121 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004122 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004123 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004124}
4125
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004126void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004127 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004128{
4129 String8 name;
4130 if (index < args.size()) {
4131 name = String8(args[index]);
4132 index++;
4133 }
4134
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004135 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4136 getHwComposer().isConnected(displayId)) {
4137 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4138 const nsecs_t period = activeConfig->getVsyncPeriod();
4139 result.appendFormat("%" PRId64 "\n", period);
4140 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004141
4142 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004143 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004144 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004145 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004146 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004147 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004148 }
Robert Carr2047fae2016-11-28 14:09:09 -08004149 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004150 }
4151}
4152
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004153void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004154 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004155{
4156 String8 name;
4157 if (index < args.size()) {
4158 name = String8(args[index]);
4159 index++;
4160 }
4161
Robert Carr2047fae2016-11-28 14:09:09 -08004162 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004163 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004164 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004165 }
Robert Carr2047fae2016-11-28 14:09:09 -08004166 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004167
Svetoslavd85084b2014-03-20 10:28:31 -07004168 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004169}
4170
Jamie Gennis6547ff42013-07-16 20:12:42 -07004171// This should only be called from the main thread. Otherwise it would need
4172// the lock and should use mCurrentState rather than mDrawingState.
4173void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004174 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004175 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004176 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004177
4178 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4179}
4180
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004181void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004182{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004183 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004184
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004185 if (isLayerTripleBufferingDisabled())
4186 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004187
4188 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004189 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004190 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004191 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004192 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4193 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004194 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004195}
4196
Dan Stozab90cf072015-03-05 11:05:59 -08004197void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4198{
4199 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004200 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4201 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004202 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004203 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004204 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4205 b + 1, bucketTimeSec, percent);
4206 }
David Sodman4a36e932017-11-07 14:29:47 -08004207 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004208 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004209 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004210 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004211 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004212}
4213
Dan Stozae77c7662016-05-13 11:37:28 -07004214void SurfaceFlinger::recordBufferingStats(const char* layerName,
4215 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004216 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4217 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004218 for (const auto& segment : history) {
4219 if (!segment.usedThirdBuffer) {
4220 stats.twoBufferTime += segment.totalTime;
4221 }
4222 if (segment.occupancyAverage < 1.0f) {
4223 stats.doubleBufferedTime += segment.totalTime;
4224 } else if (segment.occupancyAverage < 2.0f) {
4225 stats.tripleBufferedTime += segment.totalTime;
4226 }
4227 ++stats.numSegments;
4228 stats.totalTime += segment.totalTime;
4229 }
4230}
4231
Brian Andersond6927fb2016-07-23 23:37:30 -07004232void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4233 result.appendFormat("Layer frame timestamps:\n");
4234
4235 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4236 const size_t count = currentLayers.size();
4237 for (size_t i=0 ; i<count ; i++) {
4238 currentLayers[i]->dumpFrameEvents(result);
4239 }
4240}
4241
Dan Stozae77c7662016-05-13 11:37:28 -07004242void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4243 result.append("Buffering stats:\n");
4244 result.append(" [Layer name] <Active time> <Two buffer> "
4245 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004246 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004247 typedef std::tuple<std::string, float, float, float> BufferTuple;
4248 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004249 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004250 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004251 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004252 if (stats.numSegments == 0) {
4253 continue;
4254 }
4255 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4256 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4257 stats.totalTime;
4258 float doubleBufferRatio = static_cast<float>(
4259 stats.doubleBufferedTime) / stats.totalTime;
4260 float tripleBufferRatio = static_cast<float>(
4261 stats.tripleBufferedTime) / stats.totalTime;
4262 sorted.insert({activeTime, {name, twoBufferRatio,
4263 doubleBufferRatio, tripleBufferRatio}});
4264 }
4265 for (const auto& sortedPair : sorted) {
4266 float activeTime = sortedPair.first;
4267 const BufferTuple& values = sortedPair.second;
4268 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4269 std::get<0>(values).c_str(), activeTime,
4270 std::get<1>(values), std::get<2>(values),
4271 std::get<3>(values));
4272 }
4273 result.append("\n");
4274}
4275
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004276void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004277 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004278 const int32_t displayId = display->getId();
4279 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4280 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004281 continue;
4282 }
4283
Dominik Laskowski7e045462018-05-30 13:02:02 -07004284 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004285 uint8_t port;
4286 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004287 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004288 result.append("no identification data\n");
4289 continue;
4290 }
4291
4292 if (!isEdid(data)) {
4293 result.append("unknown identification data: ");
4294 for (uint8_t byte : data) {
4295 result.appendFormat("%x ", byte);
4296 }
4297 result.append("\n");
4298 continue;
4299 }
4300
4301 const auto edid = parseEdid(data);
4302 if (!edid) {
4303 result.append("invalid EDID: ");
4304 for (uint8_t byte : data) {
4305 result.appendFormat("%x ", byte);
4306 }
4307 result.append("\n");
4308 continue;
4309 }
4310
4311 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4312 result.append(edid->displayName.data(), edid->displayName.length());
4313 result.append("\"\n");
4314 }
4315 result.append("\n");
4316}
4317
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004318void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004319 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4320 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004321 result.appendFormat("DisplayColorSetting: %s\n",
4322 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004323
4324 // TODO: print out if wide-color mode is active or not
4325
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004326 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004327 const int32_t displayId = display->getId();
4328 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004329 continue;
4330 }
4331
Dominik Laskowski7e045462018-05-30 13:02:02 -07004332 result.appendFormat("Display %d color modes:\n", displayId);
4333 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004334 for (auto&& mode : modes) {
4335 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4336 }
4337
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004338 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004339 result.appendFormat(" Current color mode: %s (%d)\n",
4340 decodeColorMode(currentMode).c_str(), currentMode);
4341 }
4342 result.append("\n");
4343}
4344
David Sodman7e4ae112018-02-09 15:02:28 -08004345void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4346 std::string stringResult;
4347
4348 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004349 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4350 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004351 continue;
4352 }
4353
Dominik Laskowski05275f12018-11-01 15:03:24 -07004354 const auto& compositionInfoList = it->second;
4355 stringResult += base::StringPrintf("%s\n", display->getDebugName().c_str());
David Sodman7e4ae112018-02-09 15:02:28 -08004356 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4357 for (const auto& compositionInfo : compositionInfoList) {
4358 compositionInfo.dump(stringResult, nullptr);
4359 stringResult += base::StringPrintf("\n");
4360 }
4361 }
4362
4363 result.append(stringResult.c_str());
4364}
4365
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004366LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004367 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004368 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4369 const State& state = useDrawing ? mDrawingState : mCurrentState;
4370 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004371 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004372 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004373 });
4374
4375 return layersProto;
4376}
4377
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004378LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004379 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004380
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004381 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004382 resolution->set_w(display.getWidth());
4383 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004384
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004385 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4386 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4387 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004388
Dominik Laskowski7e045462018-05-30 13:02:02 -07004389 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004390 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004391 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004392 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004393 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004394 }
4395 });
4396
4397 return layersProto;
4398}
4399
Mathias Agopian74d211a2013-04-22 16:55:35 +02004400void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4401 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004402{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004403 bool colorize = false;
4404 if (index < args.size()
4405 && (args[index] == String16("--color"))) {
4406 colorize = true;
4407 index++;
4408 }
4409
4410 Colorizer colorizer(colorize);
4411
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004412 // figure out if we're stuck somewhere
4413 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004414 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004415 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4416
4417 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004418 * Dump library configuration.
4419 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004420
4421 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004422 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004423 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004424 appendSfConfigString(result);
4425 appendUiConfigString(result);
4426 appendGuiConfigString(result);
4427 result.append("\n");
4428
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004429 result.append("\nDisplay identification data:\n");
4430 dumpDisplayIdentificationData(result);
4431
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004432 result.append("\nWide-Color information:\n");
4433 dumpWideColorInfo(result);
4434
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004435 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004436 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004437 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004438 result.append(SyncFeatures::getInstance().toString());
4439 result.append("\n");
4440
Andy McFadden41d67d72014-04-25 16:58:34 -07004441 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004442 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004443 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004444
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004445 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4446 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004447 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4448 getHwComposer().isConnected(displayId)) {
4449 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004450 result.appendFormat("Display %d: "
4451 "app phase %" PRId64 " ns, "
4452 "sf phase %" PRId64 " ns, "
4453 "early app phase %" PRId64 " ns, "
4454 "early sf phase %" PRId64 " ns, "
4455 "early app gl phase %" PRId64 " ns, "
4456 "early sf gl phase %" PRId64 " ns, "
4457 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4458 displayId,
4459 vsyncPhaseOffsetNs,
4460 sfVsyncPhaseOffsetNs,
4461 appEarlyOffset,
4462 sfEarlyOffset,
4463 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004464 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004465 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004466 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004467 result.append("\n");
4468
Dan Stozab90cf072015-03-05 11:05:59 -08004469 // Dump static screen stats
4470 result.append("\n");
4471 dumpStaticScreenStats(result);
4472 result.append("\n");
4473
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004474 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4475
Dan Stozae77c7662016-05-13 11:37:28 -07004476 dumpBufferingStats(result);
4477
Andy McFadden4803b742012-09-24 19:07:20 -07004478 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004479 * Dump the visible layer list
4480 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004481 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004482 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004483 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4484 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004485 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004486
Chia-I Wu2f884132018-09-13 15:17:58 -07004487 {
4488 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4489 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4490 result.append(LayerProtoParser::layerTreeToString(layerTree).c_str());
4491 result.append("\n");
4492 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004493
David Sodman7e4ae112018-02-09 15:02:28 -08004494 result.append("\nFrame-Composition information:\n");
4495 dumpFrameCompositionInfo(result);
4496 result.append("\n");
4497
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004498 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004499 * Dump Display state
4500 */
4501
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004502 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004503 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004504 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004505 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004506 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004507 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004508 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004509
4510 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004511 * Dump SurfaceFlinger global state
4512 */
4513
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004514 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004515 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004516 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004517
Mathias Agopian888c8222012-08-04 21:10:38 -07004518 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004519 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004520
David Sodmanbc815282017-11-05 18:57:52 -08004521 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004522
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004523 if (display) {
4524 display->undefinedRegion.dump(result, "undefinedRegion");
4525 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4526 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004527 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004528 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004529 " gpu_to_cpu_unsupported : %d\n",
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004530 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004531
4532 if (display) {
4533 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4534 result.appendFormat(" refresh-rate : %f fps\n"
4535 " x-dpi : %f\n"
4536 " y-dpi : %f\n",
4537 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4538 activeConfig->getDpiY());
4539 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004540
Mathias Agopian74d211a2013-04-22 16:55:35 +02004541 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004542 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004543
Ana Krulec98b5b242018-08-10 15:03:23 -07004544 result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004545 /*
4546 * VSYNC state
4547 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004548 if (mUseScheduler) {
4549 mScheduler->dump(mAppConnectionHandle, result);
4550 } else {
4551 mEventThread->dump(result);
4552 }
Dan Stozae22aec72016-08-01 13:20:59 -07004553 result.append("\n");
4554
4555 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004556 * Tracing state
4557 */
4558 mTracing.dump(result);
4559 result.append("\n");
4560
4561 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004562 * HWC layer minidump
4563 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004564 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004565 const int32_t displayId = display->getId();
4566 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004567 continue;
4568 }
4569
Dominik Laskowski7e045462018-05-30 13:02:02 -07004570 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004571 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004572 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004573 result.append("\n");
4574 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004575
4576 /*
4577 * Dump HWComposer state
4578 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004579 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004580 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004581 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004582 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004583 result.appendFormat(" h/w composer %s\n",
4584 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004585 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004586
4587 /*
4588 * Dump gralloc state
4589 */
4590 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4591 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004592
4593 /*
4594 * Dump VrFlinger state if in use.
4595 */
4596 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4597 result.append("VrFlinger state:\n");
4598 result.append(mVrFlinger->Dump().c_str());
4599 result.append("\n");
4600 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004601}
4602
Dominik Laskowski7e045462018-05-30 13:02:02 -07004603const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004604 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004605 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004606 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004607 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004608 }
4609 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004610
4611 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4612 static const Vector<sp<Layer>> empty;
4613 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004614}
4615
Keun young Park63f165f2012-08-31 10:53:36 -07004616bool SurfaceFlinger::startDdmConnection()
4617{
4618 void* libddmconnection_dso =
4619 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4620 if (!libddmconnection_dso) {
4621 return false;
4622 }
4623 void (*DdmConnection_start)(const char* name);
4624 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004625 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004626 if (!DdmConnection_start) {
4627 dlclose(libddmconnection_dso);
4628 return false;
4629 }
4630 (*DdmConnection_start)(getServiceName());
4631 return true;
4632}
4633
Chia-I Wu28f320b2018-05-03 11:02:56 -07004634void SurfaceFlinger::updateColorMatrixLocked() {
4635 mat4 colorMatrix;
4636 if (mGlobalSaturationFactor != 1.0f) {
4637 // Rec.709 luma coefficients
4638 float3 luminance{0.213f, 0.715f, 0.072f};
4639 luminance *= 1.0f - mGlobalSaturationFactor;
4640 mat4 saturationMatrix = mat4(
4641 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4642 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4643 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4644 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4645 );
4646 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4647 } else {
4648 colorMatrix = mClientColorMatrix * mDaltonizer();
4649 }
4650
4651 if (mCurrentState.colorMatrix != colorMatrix) {
4652 mCurrentState.colorMatrix = colorMatrix;
4653 mCurrentState.colorMatrixChanged = true;
4654 setTransactionFlags(eTransactionNeeded);
4655 }
4656}
4657
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004658status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004659#pragma clang diagnostic push
4660#pragma clang diagnostic error "-Wswitch-enum"
4661 switch (static_cast<ISurfaceComposerTag>(code)) {
4662 // These methods should at minimum make sure that the client requested
4663 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004664 case BOOT_FINISHED:
4665 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004666 case CREATE_CONNECTION:
4667 case CREATE_DISPLAY:
4668 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004669 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004670 case GET_ACTIVE_COLOR_MODE:
4671 case GET_ANIMATION_FRAME_STATS:
4672 case GET_HDR_CAPABILITIES:
4673 case SET_ACTIVE_CONFIG:
4674 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004675 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004676 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004677 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4678 IPCThreadState* ipc = IPCThreadState::self();
4679 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4680 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004681 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004682 }
Robert Carr1db73f62016-12-21 12:58:51 -08004683 return OK;
4684 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004685 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004686 IPCThreadState* ipc = IPCThreadState::self();
4687 const int pid = ipc->getCallingPid();
4688 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004689 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4690 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004691 return PERMISSION_DENIED;
4692 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004693 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004694 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004695 // Used by apps to hook Choreographer to SurfaceFlinger.
4696 case CREATE_DISPLAY_EVENT_CONNECTION:
4697 // The following calls are currently used by clients that do not
4698 // request necessary permissions. However, they do not expose any secret
4699 // information, so it is OK to pass them.
4700 case AUTHENTICATE_SURFACE:
4701 case GET_ACTIVE_CONFIG:
4702 case GET_BUILT_IN_DISPLAY:
4703 case GET_DISPLAY_COLOR_MODES:
4704 case GET_DISPLAY_CONFIGS:
4705 case GET_DISPLAY_STATS:
4706 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4707 // Calling setTransactionState is safe, because you need to have been
4708 // granted a reference to Client* and Handle* to do anything with it.
4709 case SET_TRANSACTION_STATE:
4710 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004711 case CREATE_SCOPED_CONNECTION:
Ady Abraham2a6ab2a2018-10-26 14:25:30 -07004712 case IS_COLOR_MANAGEMET_USED:
Peiyong Lin0256f722018-08-31 15:45:10 -07004713 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004714 return OK;
4715 }
4716 case CAPTURE_LAYERS:
4717 case CAPTURE_SCREEN: {
4718 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004719 IPCThreadState* ipc = IPCThreadState::self();
4720 const int pid = ipc->getCallingPid();
4721 const int uid = ipc->getCallingUid();
4722 if ((uid != AID_GRAPHICS) &&
4723 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4724 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4725 return PERMISSION_DENIED;
4726 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004727 return OK;
4728 }
4729 // The following codes are deprecated and should never be allowed to access SF.
4730 case CONNECT_DISPLAY_UNUSED:
4731 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4732 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4733 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004734 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004735 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004736
4737 // These codes are used for the IBinder protocol to either interrogate the recipient
4738 // side of the transaction for its canonical interface descriptor or to dump its state.
4739 // We let them pass by default.
4740 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4741 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4742 code == IBinder::SYSPROPS_TRANSACTION) {
4743 return OK;
4744 }
Peiyong Lin3b44a032018-10-24 18:18:12 -07004745 // Numbers from 1000 to 1030 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004746 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin3b44a032018-10-24 18:18:12 -07004747 if (code >= 1000 && code <= 1030) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004748 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4749 return OK;
4750 }
4751 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4752 return PERMISSION_DENIED;
4753#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004754}
4755
Ana Krulec13be8ad2018-08-21 02:43:56 +00004756status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4757 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004758 status_t credentialCheck = CheckTransactCodeCredentials(code);
4759 if (credentialCheck != OK) {
4760 return credentialCheck;
4761 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004762
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004763 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4764 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004765 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004766 IPCThreadState* ipc = IPCThreadState::self();
4767 const int uid = ipc->getCallingUid();
4768 if (CC_UNLIKELY(uid != AID_SYSTEM
4769 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004770 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004771 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004772 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004773 return PERMISSION_DENIED;
4774 }
4775 int n;
4776 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004777 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004778 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004779 return NO_ERROR;
4780 case 1002: // SHOW_UPDATES
4781 n = data.readInt32();
4782 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004783 invalidateHwcGeometry();
4784 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004785 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004786 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004787 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004788 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004789 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004790 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004791 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004792 setTransactionFlags(
4793 eTransactionNeeded|
4794 eDisplayTransactionNeeded|
4795 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004796 return NO_ERROR;
4797 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004798 case 1006:{ // send empty update
4799 signalRefresh();
4800 return NO_ERROR;
4801 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004802 case 1008: // toggle use of hw composer
4803 n = data.readInt32();
4804 mDebugDisableHWC = n ? 1 : 0;
4805 invalidateHwcGeometry();
4806 repaintEverything();
4807 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004808 case 1009: // toggle use of transform hint
4809 n = data.readInt32();
4810 mDebugDisableTransformHint = n ? 1 : 0;
4811 invalidateHwcGeometry();
4812 repaintEverything();
4813 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004814 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004815 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004816 reply->writeInt32(0);
4817 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004818 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004819 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004820 return NO_ERROR;
4821 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004822 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004823 if (!display) {
4824 return NAME_NOT_FOUND;
4825 }
4826
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004827 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004828 return NO_ERROR;
4829 }
4830 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004831 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004832 // daltonize
4833 n = data.readInt32();
4834 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004835 case 1:
4836 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4837 break;
4838 case 2:
4839 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4840 break;
4841 case 3:
4842 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4843 break;
4844 default:
4845 mDaltonizer.setType(ColorBlindnessType::None);
4846 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004847 }
4848 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004849 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004850 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004851 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004852 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004853
4854 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004855 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004856 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004857 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004858 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004859 // apply a color matrix
4860 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004861 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004862 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004863 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004864 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004865 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004866 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004867 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004868 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004869 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004870 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004871
4872 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4873 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004874 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004875 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4876 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4877 }
4878
Chia-I Wu28f320b2018-05-03 11:02:56 -07004879 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004880 return NO_ERROR;
4881 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004882 // This is an experimental interface
4883 // Needs to be shifted to proper binder interface when we productize
4884 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004885 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07004886 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07004887 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004888 return NO_ERROR;
4889 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004890 case 1017: {
4891 n = data.readInt32();
4892 mForceFullDamage = static_cast<bool>(n);
4893 return NO_ERROR;
4894 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004895 case 1018: { // Modify Choreographer's phase offset
4896 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004897 if (mUseScheduler) {
4898 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
4899 } else {
4900 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4901 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004902 return NO_ERROR;
4903 }
4904 case 1019: { // Modify SurfaceFlinger's phase offset
4905 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004906 if (mUseScheduler) {
4907 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
4908 } else {
4909 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4910 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004911 return NO_ERROR;
4912 }
Irvel468051e2016-06-13 16:44:44 -07004913 case 1020: { // Layer updates interceptor
4914 n = data.readInt32();
4915 if (n) {
4916 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004917 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004918 }
4919 else{
4920 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004921 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004922 }
4923 return NO_ERROR;
4924 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004925 case 1021: { // Disable HWC virtual displays
4926 n = data.readInt32();
4927 mUseHwcVirtualDisplays = !n;
4928 return NO_ERROR;
4929 }
Romain Guy0147a172017-06-01 13:53:56 -07004930 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004931 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004932 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004933
Chia-I Wu28f320b2018-05-03 11:02:56 -07004934 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004935 return NO_ERROR;
4936 }
Romain Guy54f154a2017-10-24 21:40:32 +01004937 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004938 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004939 invalidateHwcGeometry();
4940 repaintEverything();
4941 return NO_ERROR;
4942 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004943 // Deprecate, use 1030 to check whether the device is color managed.
4944 case 1024: {
4945 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004946 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004947 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004948 n = data.readInt32();
4949 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004950 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004951 mTracing.enable();
4952 doTracing("tracing.enable");
4953 reply->writeInt32(NO_ERROR);
4954 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004955 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004956 status_t err = mTracing.disable();
4957 reply->writeInt32(err);
4958 }
4959 return NO_ERROR;
4960 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004961 case 1026: { // Get layer tracing status
4962 reply->writeBool(mTracing.isEnabled());
4963 return NO_ERROR;
4964 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004965 // Is a DisplayColorSetting supported?
4966 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004967 const auto display = getDefaultDisplayDevice();
4968 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004969 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004970 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004971
4972 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4973 switch (setting) {
4974 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07004975 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004976 break;
4977 case DisplayColorSetting::UNMANAGED:
4978 reply->writeBool(true);
4979 break;
4980 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004981 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004982 break;
4983 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004984 reply->writeBool(
4985 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004986 break;
4987 }
4988 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004989 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004990 // Is VrFlinger active?
4991 case 1028: {
4992 Mutex::Autolock _l(mStateLock);
4993 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4994 return NO_ERROR;
4995 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004996 // Is device color managed?
4997 case 1030: {
4998 reply->writeBool(useColorManagement);
4999 return NO_ERROR;
5000 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005001 }
5002 }
5003 return err;
5004}
5005
Steven Thomas6d8110b2017-08-31 18:24:21 -07005006void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005007 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005008 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005009}
5010
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005011// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5012class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005013public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005014 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5015 ~WindowDisconnector() {
5016 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005017 }
5018
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005019private:
5020 ANativeWindow* mWindow;
5021 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005022};
5023
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005024status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005025 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5026 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005027 uint32_t reqWidth, uint32_t reqHeight,
5028 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005029 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005030 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005031
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005032 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005033
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005034 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5035
Chia-I Wu20261cb2018-08-23 12:55:44 -07005036 sp<DisplayDevice> display;
5037 {
5038 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005039
Chia-I Wu20261cb2018-08-23 12:55:44 -07005040 display = getDisplayDeviceLocked(displayToken);
5041 if (!display) return BAD_VALUE;
5042
Chia-I Wucb023152018-08-28 12:57:23 -07005043 // set the requested width/height to the logical display viewport size
5044 // by default
5045 if (reqWidth == 0 || reqHeight == 0) {
5046 reqWidth = uint32_t(display->getViewport().width());
5047 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005048 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005049 }
5050
Peiyong Lin0e003c92018-09-17 11:09:51 -07005051 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5052 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005053
5054 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005055 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005056 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5057 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005058}
5059
5060status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005061 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5062 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005063 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005064 ATRACE_CALL();
5065
5066 class LayerRenderArea : public RenderArea {
5067 public:
Robert Carr578038f2018-03-09 12:25:24 -08005068 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005069 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5070 bool childrenOnly)
5071 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005072 mLayer(layer),
5073 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005074 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005075 mFlinger(flinger),
5076 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005077 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005078 Rect getBounds() const override {
5079 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005080 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005081 }
Marissa Wall61c58622018-07-18 10:12:20 -07005082 int getHeight() const override {
5083 return mLayer->getActiveHeight(mLayer->getDrawingState());
5084 }
5085 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005086 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005087 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005088 Rect getSourceCrop() const override {
5089 if (mCrop.isEmpty()) {
5090 return getBounds();
5091 } else {
5092 return mCrop;
5093 }
5094 }
Robert Carr578038f2018-03-09 12:25:24 -08005095 class ReparentForDrawing {
5096 public:
5097 const sp<Layer>& oldParent;
5098 const sp<Layer>& newParent;
5099
5100 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5101 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005102 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005103 }
Robert Carr15eae092018-03-23 13:43:53 -07005104 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005105 };
5106
5107 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005108 const Rect sourceCrop = getSourceCrop();
5109 // no need to check rotation because there is none
5110 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5111 sourceCrop.height() != getReqHeight();
5112
Robert Carr578038f2018-03-09 12:25:24 -08005113 if (!mChildrenOnly) {
5114 mTransform = mLayer->getTransform().inverse();
5115 drawLayers();
5116 } else {
5117 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005118 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005119 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5120 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005121
5122 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5123 drawLayers();
5124 }
5125 }
chaviwa76b2712017-09-20 12:02:26 -07005126
chaviwa76b2712017-09-20 12:02:26 -07005127 private:
chaviw7206d492017-11-10 16:16:12 -08005128 const sp<Layer> mLayer;
5129 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005130
5131 // In the "childrenOnly" case we reparent the children to a screenshot
5132 // layer which has no properties set and which does not draw.
5133 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005134 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005135 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005136
5137 SurfaceFlinger* mFlinger;
5138 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005139 };
5140
5141 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5142 auto parent = layerHandle->owner.promote();
5143
Robert Carr2e102c92018-10-23 12:11:15 -07005144 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005145 ALOGE("captureLayers called with a removed parent");
5146 return NAME_NOT_FOUND;
5147 }
5148
Robert Carr578038f2018-03-09 12:25:24 -08005149 const int uid = IPCThreadState::self()->getCallingUid();
5150 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5151 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5152 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5153 return PERMISSION_DENIED;
5154 }
5155
chaviw7206d492017-11-10 16:16:12 -08005156 Rect crop(sourceCrop);
5157 if (sourceCrop.width() <= 0) {
5158 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005159 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005160 }
5161
5162 if (sourceCrop.height() <= 0) {
5163 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005164 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005165 }
5166
5167 int32_t reqWidth = crop.width() * frameScale;
5168 int32_t reqHeight = crop.height() * frameScale;
5169
Chia-I Wu20261cb2018-08-23 12:55:44 -07005170 // really small crop or frameScale
5171 if (reqWidth <= 0) {
5172 reqWidth = 1;
5173 }
5174 if (reqHeight <= 0) {
5175 reqHeight = 1;
5176 }
5177
Peiyong Lin0e003c92018-09-17 11:09:51 -07005178 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005179
Robert Carr578038f2018-03-09 12:25:24 -08005180 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005181 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5182 if (!layer->isVisible()) {
5183 return;
Robert Carr578038f2018-03-09 12:25:24 -08005184 } else if (childrenOnly && layer == parent.get()) {
5185 return;
chaviwa76b2712017-09-20 12:02:26 -07005186 }
5187 visitor(layer);
5188 });
5189 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005190 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005191}
5192
5193status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5194 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005195 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005196 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005197 bool useIdentityTransform) {
5198 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005199
Peiyong Lin0e003c92018-09-17 11:09:51 -07005200 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005201 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5202 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005203 *outBuffer =
5204 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5205 static_cast<android_pixel_format>(reqPixelFormat), 1,
5206 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005207
5208 // This mutex protects syncFd and captureResult for communication of the return values from the
5209 // main thread back to this Binder thread
5210 std::mutex captureMutex;
5211 std::condition_variable captureCondition;
5212 std::unique_lock<std::mutex> captureLock(captureMutex);
5213 int syncFd = -1;
5214 std::optional<status_t> captureResult;
5215
Robert Carr03480e22018-01-04 16:02:06 -08005216 const int uid = IPCThreadState::self()->getCallingUid();
5217 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5218
Dominik Laskowski8c001672018-05-30 16:52:06 -07005219 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005220 // If there is a refresh pending, bug out early and tell the binder thread to try again
5221 // after the refresh.
5222 if (mRefreshPending) {
5223 ATRACE_NAME("Skipping screenshot for now");
5224 std::unique_lock<std::mutex> captureLock(captureMutex);
5225 captureResult = std::make_optional<status_t>(EAGAIN);
5226 captureCondition.notify_one();
5227 return;
5228 }
5229
5230 status_t result = NO_ERROR;
5231 int fd = -1;
5232 {
5233 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005234 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005235 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5236 useIdentityTransform, forSystem, &fd);
5237 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005238 }
5239
5240 {
5241 std::unique_lock<std::mutex> captureLock(captureMutex);
5242 syncFd = fd;
5243 captureResult = std::make_optional<status_t>(result);
5244 captureCondition.notify_one();
5245 }
5246 });
5247
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005248 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005249 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005250 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005251 while (*captureResult == EAGAIN) {
5252 captureResult.reset();
5253 result = postMessageAsync(message);
5254 if (result != NO_ERROR) {
5255 return result;
5256 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005257 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005258 }
5259 result = *captureResult;
5260 }
5261
5262 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005263 sync_wait(syncFd, -1);
5264 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005265 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005266
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005267 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005268}
5269
chaviwa76b2712017-09-20 12:02:26 -07005270void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005271 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005272 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005273 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005274
Lloyd Pique144e1162017-12-20 16:44:52 -08005275 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005276
chaviwa76b2712017-09-20 12:02:26 -07005277 const auto reqWidth = renderArea.getReqWidth();
5278 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005279 const auto sourceCrop = renderArea.getSourceCrop();
5280 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005281
Peiyong Lin0e003c92018-09-17 11:09:51 -07005282 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005283 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005284
Mathias Agopian180f10d2013-04-10 22:55:41 -07005285 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005286 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005287
5288 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005289 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005290 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005291
chaviw50da5042018-04-09 13:49:37 -07005292 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005293 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005294 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005295
chaviwa76b2712017-09-20 12:02:26 -07005296 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005297 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005298 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005299 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005300 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005301}
5302
chaviwa76b2712017-09-20 12:02:26 -07005303status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5304 TraverseLayersFunction traverseLayers,
5305 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005306 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005307 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005308 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005309 ATRACE_CALL();
5310
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005311 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005312
5313 traverseLayers([&](Layer* layer) {
5314 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5315 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005316
Robert Carr03480e22018-01-04 16:02:06 -08005317 // We allow the system server to take screenshots of secure layers for
5318 // use in situations like the Screen-rotation animation and place
5319 // the impetus on WindowManager to not persist them.
5320 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005321 ALOGW("FB is protected: PERMISSION_DENIED");
5322 return PERMISSION_DENIED;
5323 }
5324
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005325 // this binds the given EGLImage as a framebuffer for the
5326 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005327 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005328 if (bufferBond.getStatus() != NO_ERROR) {
5329 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005330 return INVALID_OPERATION;
5331 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005332
Dan Stozaabcda352017-06-01 14:37:39 -07005333 // this will in fact render into our dequeued buffer
5334 // via an FBO, which means we didn't have to create
5335 // an EGLSurface and therefore we're not
5336 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005337 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005338
Alec Mouri492bc572018-09-11 21:40:04 +00005339 base::unique_fd syncFd = getRenderEngine().flush();
5340 if (syncFd < 0) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005341 getRenderEngine().finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005342 }
Alec Mouri492bc572018-09-11 21:40:04 +00005343 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005344
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005345 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005346}
5347
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005348// ---------------------------------------------------------------------------
5349
Dan Stoza412903f2017-04-27 13:42:17 -07005350void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5351 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005352}
5353
Dan Stoza412903f2017-04-27 13:42:17 -07005354void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5355 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005356}
5357
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005358void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005359 const LayerVector::Visitor& visitor) {
5360 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005361 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005362 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005363 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005364 continue;
5365 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005366 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005367 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005368 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005369 return;
5370 }
chaviwa76b2712017-09-20 12:02:26 -07005371 if (!layer->isVisible()) {
5372 return;
5373 }
5374 visitor(layer);
5375 });
5376 }
5377}
5378
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005379}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005380
Lloyd Pique074e8122018-07-26 12:57:23 -07005381
Mathias Agopian3f844832013-08-07 21:24:32 -07005382#if defined(__gl_h_)
5383#error "don't include gl/gl.h in this file"
5384#endif
5385
5386#if defined(__gl2_h_)
5387#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005388#endif