blob: dec08fd629c6ce413d7c87e08d6bf8bbad11b16d [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Chia-I Wud49d6692018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070050#include <renderengine/RenderEngine.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070051#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070066#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070067#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020070#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080072#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080073#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070077#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070078#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070080#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081
Steven Thomasb02664d2017-07-26 18:48:28 -070082#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070083#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070084#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070085#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070086#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070087#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070088#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070089#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070090#include "Scheduler/EventControlThread.h"
91#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070092#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070093#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070094#include "Scheduler/Scheduler.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070095
Mathias Agopianff2ed702013-09-01 21:36:12 -070096#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070097
David Sodman7e4ae112018-02-09 15:02:28 -080098#include "android-base/stringprintf.h"
99
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900100#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800101#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700102#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800103#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900104#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900105
chaviw1d044282017-09-27 12:19:28 -0700106#include <layerproto/LayerProtoParser.h>
107
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800108#define DISPLAY_COUNT 1
109
110namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700111
Jaesoo Lee43518572017-01-23 19:03:16 +0900112using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900113using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700114using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700115using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700116using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700117using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900118
Steven Thomasb02664d2017-07-26 18:48:28 -0700119namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700120
121#pragma clang diagnostic push
122#pragma clang diagnostic error "-Wswitch-enum"
123
124bool isWideColorMode(const ColorMode colorMode) {
125 switch (colorMode) {
126 case ColorMode::DISPLAY_P3:
127 case ColorMode::ADOBE_RGB:
128 case ColorMode::DCI_P3:
129 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700130 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700131 case ColorMode::BT2100_PQ:
132 case ColorMode::BT2100_HLG:
133 return true;
134 case ColorMode::NATIVE:
135 case ColorMode::STANDARD_BT601_625:
136 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
137 case ColorMode::STANDARD_BT601_525:
138 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
139 case ColorMode::STANDARD_BT709:
140 case ColorMode::SRGB:
141 return false;
142 }
143 return false;
144}
145
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700146ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
147 switch (rotation) {
148 case ISurfaceComposer::eRotateNone:
149 return ui::Transform::ROT_0;
150 case ISurfaceComposer::eRotate90:
151 return ui::Transform::ROT_90;
152 case ISurfaceComposer::eRotate180:
153 return ui::Transform::ROT_180;
154 case ISurfaceComposer::eRotate270:
155 return ui::Transform::ROT_270;
156 }
157 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
158 return ui::Transform::ROT_0;
159}
160
Peiyong Linfca547f2018-07-09 13:03:33 -0700161#pragma clang diagnostic pop
162
Steven Thomasb02664d2017-07-26 18:48:28 -0700163class ConditionalLock {
164public:
165 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
166 if (lock) {
167 mMutex.lock();
168 }
169 }
170 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
171private:
172 Mutex& mMutex;
173 bool mLocked;
174};
Peiyong Linfca547f2018-07-09 13:03:33 -0700175
Steven Thomasb02664d2017-07-26 18:48:28 -0700176} // namespace anonymous
177
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800178// ---------------------------------------------------------------------------
179
Mathias Agopian99b49842011-06-27 16:05:52 -0700180const String16 sHardwareTest("android.permission.HARDWARE_TEST");
181const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
182const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
183const String16 sDump("android.permission.DUMP");
184
185// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800186int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
187int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700188int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700189bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800190uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800191bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800192bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800193int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800194// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600195bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700196int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700197bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700198bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700199Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
200ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
201Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
202ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700203
Kalle Raitaa099a242017-01-11 11:17:29 -0800204std::string getHwcServiceName() {
205 char value[PROPERTY_VALUE_MAX] = {};
206 property_get("debug.sf.hwc_service_name", value, "default");
207 ALOGI("Using HWComposer service: '%s'", value);
208 return std::string(value);
209}
210
211bool useTrebleTestingOverride() {
212 char value[PROPERTY_VALUE_MAX] = {};
213 property_get("debug.sf.treble_testing_override", value, "false");
214 ALOGI("Treble testing override: '%s'", value);
215 return std::string(value) == "true";
216}
217
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800218std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
219 switch(displayColorSetting) {
220 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700221 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800222 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700223 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800224 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700225 return std::string("Enhanced");
226 default:
227 return std::string("Unknown ") +
228 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800229 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800230}
231
David Sodmanbc815282017-11-05 18:57:52 -0800232SurfaceFlingerBE::SurfaceFlingerBE()
233 : mHwcServiceName(getHwcServiceName()),
234 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800235 mFrameBuckets(),
236 mTotalTime(0),
237 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800238 mComposerSequenceId(0) {
239}
240
Lloyd Pique90c115d2018-09-18 21:39:42 -0700241SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
242 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800243 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700244 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700245 mTransactionPending(false),
246 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700247 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700248 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800249 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700250 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800251 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800252 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800253 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800254 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800255 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700256 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700257 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700258 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700259 mDebugInTransaction(0),
260 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700261 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700262 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700263 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800264 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800265 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800266 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700267 mVrFlingerRequestsDisplay(false),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700268 mMainThreadId(std::this_thread::get_id()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800269
Lloyd Pique90c115d2018-09-18 21:39:42 -0700270SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
271 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800272 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800273
274 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
275 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
276
277 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
278 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
279
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800280 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
281 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800282
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700283 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
284 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
285
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700286 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
287 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
288
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800289 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
290 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
291
Steven Thomas050b2c82017-03-06 11:45:16 -0800292 // Vr flinger is only enabled on Daydream ready devices.
293 useVrFlinger = getBool< ISurfaceFlingerConfigs,
294 &ISurfaceFlingerConfigs::useVrFlinger>(false);
295
Fabien Sanglard1971b632017-03-10 14:50:03 -0800296 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
297 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
298
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600299 hasWideColorDisplay =
300 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700301 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700302 getBool<V1_2::ISurfaceFlingerConfigs,
303 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
304
305 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
306 if (surfaceFlingerConfigsServiceV1_2) {
307 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
Peiyong Linc6780972018-10-28 15:24:08 -0700308 [&](auto tmpDefaultDataspace, auto tmpDefaultPixelFormat,
309 auto tmpWideColorGamutDataspace, auto tmpWideColorGamutPixelFormat) {
310 defaultCompositionDataspace = tmpDefaultDataspace;
311 defaultCompositionPixelFormat = tmpDefaultPixelFormat;
312 wideColorGamutCompositionDataspace = tmpWideColorGamutDataspace;
313 wideColorGamutCompositionPixelFormat = tmpWideColorGamutPixelFormat;
314 });
Peiyong Lin0256f722018-08-31 15:45:10 -0700315 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600316
Peiyong Linb3839ad2018-09-05 15:37:19 -0700317 useContextPriority = getBool<ISurfaceFlingerConfigs,
318 &ISurfaceFlingerConfigs::useContextPriority>(true);
319
Iris Chang7501ed62018-04-30 14:45:42 +0800320 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700321 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
322 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800323 V1_1::DisplayOrientation::ORIENTATION_0);
324
325 switch (primaryDisplayOrientation) {
326 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700327 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800328 break;
329 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700330 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800331 break;
332 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700333 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800334 break;
335 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700336 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800337 break;
338 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700339 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800340
Lloyd Pique90c115d2018-09-18 21:39:42 -0700341 mPrimaryDispSync =
342 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
343 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700344
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800345 // debugging stuff...
346 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700347
Mathias Agopianb4b17302013-03-20 18:36:41 -0700348 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700349 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700350
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800351 property_get("debug.sf.showupdates", value, "0");
352 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700353
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700354 property_get("debug.sf.ddms", value, "0");
355 mDebugDDMS = atoi(value);
356 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700357 if (!startDdmConnection()) {
358 // start failed, and DDMS debugging not enabled
359 mDebugDDMS = 0;
360 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700361 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700362 ALOGI_IF(mDebugRegion, "showupdates enabled");
363 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700364
365 property_get("debug.sf.disable_backpressure", value, "0");
366 mPropagateBackpressure = !atoi(value);
367 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700368
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800369 property_get("debug.sf.enable_hwc_vds", value, "0");
370 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800371 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800372
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800373 property_get("ro.sf.disable_triple_buffer", value, "1");
374 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800375 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700376
Yiwei Zhang243b3782018-05-15 17:40:04 -0700377 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700378 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
379 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
380
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200381 property_get("debug.sf.early_phase_offset_ns", value, "-1");
382 const int earlySfOffsetNs = atoi(value);
383
384 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
385 const int earlyGlSfOffsetNs = atoi(value);
386
387 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
388 const int earlyAppOffsetNs = atoi(value);
389
390 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
391 const int earlyGlAppOffsetNs = atoi(value);
392
Ana Krulec98b5b242018-08-10 15:03:23 -0700393 property_get("debug.sf.use_scheduler", value, "0");
394 mUseScheduler = atoi(value);
395
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200396 const VSyncModulator::Offsets earlyOffsets =
397 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
398 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
399 const VSyncModulator::Offsets earlyGlOffsets =
400 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
401 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
402 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
403 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700404
Romain Guy11d63f42017-07-20 12:47:14 -0700405 // We should be reading 'persist.sys.sf.color_saturation' here
406 // but since /data may be encrypted, we need to wait until after vold
407 // comes online to attempt to read the property. The property is
408 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800409
410 if (useTrebleTestingOverride()) {
411 // Without the override SurfaceFlinger cannot connect to HIDL
412 // services that are not listed in the manifests. Considered
413 // deriving the setting from the set service name, but it
414 // would be brittle if the name that's not 'default' is used
415 // for production purposes later on.
416 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
417 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800418}
419
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800420void SurfaceFlinger::onFirstRef()
421{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800422 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800423}
424
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800425SurfaceFlinger::~SurfaceFlinger()
426{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800427}
428
Dan Stozac7014012014-02-14 15:03:43 -0800429void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800430{
431 // the window manager died on us. prepare its eulogy.
432
Andy McFadden13a082e2012-08-24 10:16:42 -0700433 // restore initial conditions (default device unblank, etc)
434 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800435
436 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700437 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800438}
439
Robert Carr1db73f62016-12-21 12:58:51 -0800440static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700441 status_t err = client->initCheck();
442 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800443 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800444 }
Robert Carr1db73f62016-12-21 12:58:51 -0800445 return nullptr;
446}
447
448sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
449 return initClient(new Client(this));
450}
451
452sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
453 const sp<IGraphicBufferProducer>& gbp) {
454 if (authenticateSurfaceTexture(gbp) == false) {
455 return nullptr;
456 }
457 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
458 if (layer == nullptr) {
459 return nullptr;
460 }
461
462 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800463}
464
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700465sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
466 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700467{
468 class DisplayToken : public BBinder {
469 sp<SurfaceFlinger> flinger;
470 virtual ~DisplayToken() {
471 // no more references, this display must be terminated
472 Mutex::Autolock _l(flinger->mStateLock);
473 flinger->mCurrentState.displays.removeItem(this);
474 flinger->setTransactionFlags(eDisplayTransactionNeeded);
475 }
476 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700477 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700478 : flinger(flinger) {
479 }
480 };
481
482 sp<BBinder> token = new DisplayToken(this);
483
484 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700485 DisplayDeviceState info;
486 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700487 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700488 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700489 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800490 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700491 return token;
492}
493
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700494void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700495 Mutex::Autolock _l(mStateLock);
496
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700497 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700498 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700499 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700500 return;
501 }
502
503 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700504 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700505 ALOGE("destroyDisplay called for non-virtual display");
506 return;
507 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700508 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700509 mCurrentState.displays.removeItemsAt(idx);
510 setTransactionFlags(eDisplayTransactionNeeded);
511}
512
Mathias Agopiane57f2922012-08-09 16:29:12 -0700513sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700514 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700515 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800516 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700517 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700518 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700519}
520
Ady Abraham37965d42018-11-01 13:43:32 -0700521status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
522 if (!outGetColorManagement) {
523 return BAD_VALUE;
524 }
525 *outGetColorManagement = useColorManagement;
526 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700527}
528
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800529void SurfaceFlinger::bootFinished()
530{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700531 if (mStartPropertySetThread->join() != NO_ERROR) {
532 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800533 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800534 const nsecs_t now = systemTime();
535 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000536 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700537
538 // wait patiently for the window manager death
539 const String16 name("window");
540 sp<IBinder> window(defaultServiceManager()->getService(name));
541 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700542 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700543 }
544
Steven Thomas050b2c82017-03-06 11:45:16 -0800545 if (mVrFlinger) {
546 mVrFlinger->OnBootFinished();
547 }
548
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700549 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700550 // formerly we would just kill the process, but we now ask it to exit so it
551 // can choose where to stop the animation.
552 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700553
554 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
555 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
556 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700557
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800558 postMessageAsync(new LambdaMessage([this] {
559 readPersistentProperties();
560 mBootStage = BootStage::FINISHED;
561 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800562}
563
Dan Stoza436ccf32018-06-21 12:10:12 -0700564uint32_t SurfaceFlinger::getNewTexture() {
565 {
566 std::lock_guard lock(mTexturePoolMutex);
567 if (!mTexturePool.empty()) {
568 uint32_t name = mTexturePool.back();
569 mTexturePool.pop_back();
570 ATRACE_INT("TexturePoolSize", mTexturePool.size());
571 return name;
572 }
573
574 // The pool was too small, so increase it for the future
575 ++mTexturePoolSize;
576 }
577
578 // The pool was empty, so we need to get a new texture name directly using a
579 // blocking call to the main thread
580 uint32_t name = 0;
581 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
582 return name;
583}
584
Mathias Agopian3f844832013-08-07 21:24:32 -0700585void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700586 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700587}
588
Wei Wangf9b05ee2017-07-19 20:59:39 -0700589// Do not call property_set on main thread which will be blocked by init
590// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700591void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700592 ALOGI( "SurfaceFlinger's main thread ready to run. "
593 "Initializing graphics H/W...");
594
Thierry Strudel2924d012017-08-14 15:19:37 -0700595 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900596
Steven Thomasb02664d2017-07-26 18:48:28 -0700597 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800598
Steven Thomasb02664d2017-07-26 18:48:28 -0700599 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700600 if (mUseScheduler) {
Lloyd Pique90c115d2018-09-18 21:39:42 -0700601 mScheduler = getFactory().createScheduler(
Ana Krulece588e312018-09-18 12:32:24 -0700602 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Ana Krulec98b5b242018-08-10 15:03:23 -0700603 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700604 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700605 [this] { resyncWithRateLimit(); },
606 impl::EventThread::InterceptVSyncsCallback());
607 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700608 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700609 [this] { resyncWithRateLimit(); },
610 [this](nsecs_t timestamp) {
611 mInterceptor->saveVSyncEvent(timestamp);
612 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800613
Ana Krulec98b5b242018-08-10 15:03:23 -0700614 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700615 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
616 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700617 } else {
618 mEventThreadSource =
619 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
620 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
621 mEventThread =
622 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
623 [this] { resyncWithRateLimit(); },
624 impl::EventThread::InterceptVSyncsCallback(),
625 "appEventThread");
626 mSfEventThreadSource =
627 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
628 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
629
630 mSFEventThread =
631 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
632 [this] { resyncWithRateLimit(); },
633 [this](nsecs_t timestamp) {
634 mInterceptor->saveVSyncEvent(timestamp);
635 },
636 "sfEventThread");
637 mEventQueue->setEventThread(mSFEventThread.get());
638 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
639 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800640
Steven Thomasb02664d2017-07-26 18:48:28 -0700641 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700642 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700643 renderEngineFeature |= (useColorManagement ?
644 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700645 renderEngineFeature |= (useContextPriority ?
646 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700647
648 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
649 getBE().mRenderEngine =
Peiyong Linc6780972018-10-28 15:24:08 -0700650 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
651 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800652 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700653
654 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
655 "Starting with vr flinger active is not currently supported.");
Lloyd Pique90c115d2018-09-18 21:39:42 -0700656 getBE().mHwc = getFactory().createHWComposer(getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -0700657 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800658 // Process any initial hotplug and resulting display changes.
659 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700660 const auto display = getDefaultDisplayDeviceLocked();
661 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
662 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
663 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800664
Lloyd Piquefcd86612017-12-14 17:15:36 -0800665 // make the default display GLContext current so that we can create textures
666 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700667 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800668
Steven Thomas050b2c82017-03-06 11:45:16 -0800669 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700670 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700671 // This callback is called from the vr flinger dispatch thread. We
672 // need to call signalTransaction(), which requires holding
673 // mStateLock when we're not on the main thread. Acquiring
674 // mStateLock from the vr flinger dispatch thread might trigger a
675 // deadlock in surface flinger (see b/66916578), so post a message
676 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700677 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700678 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
679 mVrFlingerRequestsDisplay = requestDisplay;
680 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700681 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800682 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700683 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
684 getHwComposer()
685 .getHwcDisplayId(display->getId())
686 .value_or(0),
687 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800688 if (!mVrFlinger) {
689 ALOGE("Failed to start vrflinger");
690 }
691 }
692
Lloyd Pique90c115d2018-09-18 21:39:42 -0700693 mEventControlThread = getFactory().createEventControlThread(
Lloyd Pique379adc12018-01-22 17:31:47 -0800694 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700695
Mathias Agopian92a979a2012-08-02 18:32:23 -0700696 // initialize our drawing state
697 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700698
Andy McFadden13a082e2012-08-24 10:16:42 -0700699 // set initial conditions (e.g. unblank default device)
700 initializeDisplays();
701
David Sodmanbc815282017-11-05 18:57:52 -0800702 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700703
Wei Wangf9b05ee2017-07-19 20:59:39 -0700704 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700705
706 const bool presentFenceReliable =
707 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
708 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700709
710 if (mStartPropertySetThread->Start() != NO_ERROR) {
711 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800712 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800713
Chia-I Wud49d6692018-06-27 07:17:41 +0800714 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
715 // is used to saturate legacy sRGB content. However, to make sure the same color under
716 // Display P3 will be saturated to the same color, we intentionally break the API spec
717 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
718 // such saturation matrix on Display P3 is understood fully, the API should always return
719 // identify matrix.
720 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
721 Dataspace::SRGB_LINEAR);
722
723 // we will apply this on Display P3.
724 if (mEnhancedSaturationMatrix != mat4()) {
725 ColorSpace srgb(ColorSpace::sRGB());
726 ColorSpace displayP3(ColorSpace::DisplayP3());
727 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
728 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
729 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
730 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800731
Dan Stoza9e56aa02015-11-02 13:00:03 -0800732 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700733}
734
Romain Guy11d63f42017-07-20 12:47:14 -0700735void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700736 Mutex::Autolock _l(mStateLock);
737
Romain Guy11d63f42017-07-20 12:47:14 -0700738 char value[PROPERTY_VALUE_MAX];
739
740 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800741 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700742 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800743 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100744
745 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700746 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700747}
748
Mathias Agopiana67e4182012-06-19 17:26:12 -0700749void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800750 // Start boot animation service by setting a property mailbox
751 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700752 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800753 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700754 if (mStartPropertySetThread->join() != NO_ERROR) {
755 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800756 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700757}
758
Mathias Agopian875d8e12013-06-07 15:35:48 -0700759size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800760 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700761}
762
Mathias Agopian875d8e12013-06-07 15:35:48 -0700763size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800764 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700765}
766
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800767// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800768
Jamie Gennis582270d2011-08-17 18:19:00 -0700769bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800770 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800771 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800772 return authenticateSurfaceTextureLocked(bufferProducer);
773}
774
775bool SurfaceFlinger::authenticateSurfaceTextureLocked(
776 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800777 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800778 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800779}
780
Brian Anderson6b376712017-04-04 10:51:39 -0700781status_t SurfaceFlinger::getSupportedFrameTimestamps(
782 std::vector<FrameEvent>* outSupported) const {
783 *outSupported = {
784 FrameEvent::REQUESTED_PRESENT,
785 FrameEvent::ACQUIRE,
786 FrameEvent::LATCH,
787 FrameEvent::FIRST_REFRESH_START,
788 FrameEvent::LAST_REFRESH_START,
789 FrameEvent::GPU_COMPOSITION_DONE,
790 FrameEvent::DEQUEUE_READY,
791 FrameEvent::RELEASE,
792 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700793 ConditionalLock _l(mStateLock,
794 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700795 if (!getHwComposer().hasCapability(
796 HWC2::Capability::PresentFenceIsNotReliable)) {
797 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
798 }
799 return NO_ERROR;
800}
801
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700802status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
803 Vector<DisplayInfo>* configs) {
804 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700805 return BAD_VALUE;
806 }
807
Jesse Hall692c7232012-11-08 15:41:56 -0800808 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700809 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
810 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700811 type = i;
812 break;
813 }
814 }
815
816 if (type < 0) {
817 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700818 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700819
Mathias Agopian8b736f12012-08-13 17:54:26 -0700820 // TODO: Not sure if display density should handled by SF any longer
821 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700822 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700823 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700824 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800825 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700826 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700827 }
828 return density;
829 }
830 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700831 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700832 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700833 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700834 return getDensityFromProperty("ro.sf.lcd_density"); }
835 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700836
Dan Stoza7f7da322014-05-02 15:26:25 -0700837 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700838
Steven Thomas6d8110b2017-08-31 18:24:21 -0700839 ConditionalLock _l(mStateLock,
840 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800841 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700842 DisplayInfo info = DisplayInfo();
843
Dan Stoza9e56aa02015-11-02 13:00:03 -0800844 float xdpi = hwConfig->getDpiX();
845 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700846
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700847 info.w = hwConfig->getWidth();
848 info.h = hwConfig->getHeight();
849 // Default display viewport to display width and height
850 info.viewportW = info.w;
851 info.viewportH = info.h;
852
Dan Stoza7f7da322014-05-02 15:26:25 -0700853 if (type == DisplayDevice::DISPLAY_PRIMARY) {
854 // The density of the device is provided by a build property
855 float density = Density::getBuildDensity() / 160.0f;
856 if (density == 0) {
857 // the build doesn't provide a density -- this is wrong!
858 // use xdpi instead
859 ALOGE("ro.sf.lcd_density must be defined as a build property");
860 density = xdpi / 160.0f;
861 }
862 if (Density::getEmuDensity()) {
863 // if "qemu.sf.lcd_density" is specified, it overrides everything
864 xdpi = ydpi = density = Density::getEmuDensity();
865 density /= 160.0f;
866 }
867 info.density = density;
868
869 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700870 const auto display = getDefaultDisplayDeviceLocked();
871 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700872
873 // This is for screenrecord
874 const Rect viewport = display->getViewport();
875 if (viewport.isValid()) {
876 info.viewportW = uint32_t(viewport.getWidth());
877 info.viewportH = uint32_t(viewport.getHeight());
878 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700879 } else {
880 // TODO: where should this value come from?
881 static const int TV_DENSITY = 213;
882 info.density = TV_DENSITY / 160.0f;
883 info.orientation = 0;
884 }
885
Dan Stoza7f7da322014-05-02 15:26:25 -0700886 info.xdpi = xdpi;
887 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800888 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900889 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800890
Andy McFadden91b2ca82014-06-13 14:04:23 -0700891 // This is how far in advance a buffer must be queued for
892 // presentation at a given time. If you want a buffer to appear
893 // on the screen at time N, you must submit the buffer before
894 // (N - presentationDeadline).
895 //
896 // Normally it's one full refresh period (to give SF a chance to
897 // latch the buffer), but this can be reduced by configuring a
898 // DispSync offset. Any additional delays introduced by the hardware
899 // composer or panel must be accounted for here.
900 //
901 // We add an additional 1ms to allow for processing time and
902 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800903 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800904 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700905
906 // All non-virtual displays are currently considered secure.
907 info.secure = true;
908
Iris Chang7501ed62018-04-30 14:45:42 +0800909 if (type == DisplayDevice::DISPLAY_PRIMARY &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700910 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800911 std::swap(info.w, info.h);
912 }
913
Michael Wright28f24d02016-07-12 13:30:53 -0700914 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700915 }
916
Dan Stoza7f7da322014-05-02 15:26:25 -0700917 return NO_ERROR;
918}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700919
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700920status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
921 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700922 return BAD_VALUE;
923 }
924
Ana Krulece588e312018-09-18 12:32:24 -0700925 // FIXME for now we always return stats for the primary display.
926 if (mUseScheduler) {
927 mScheduler->getDisplayStatInfo(stats);
928 } else {
929 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
930 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
931 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700932 return NO_ERROR;
933}
934
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700935int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
936 const auto display = getDisplayDevice(displayToken);
937 if (!display) {
938 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800939 return BAD_VALUE;
940 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700941
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700942 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700943}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700944
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700945void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
946 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700947 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700948 return;
949 }
950
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700951 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700952 ALOGW("Trying to set config for virtual display");
953 return;
954 }
955
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700956 display->setActiveConfig(mode);
957 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700958}
959
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700960status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700961 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700962 Vector<DisplayInfo> configs;
963 getDisplayConfigs(displayToken, &configs);
964 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
965 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
966 configs.size());
967 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700968 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700969 const auto display = getDisplayDevice(displayToken);
970 if (!display) {
971 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
972 displayToken.get());
973 } else if (display->isVirtual()) {
974 ALOGW("Attempt to set active config %d for virtual display", mode);
975 } else {
976 setActiveConfigInternal(display, mode);
977 }
978 }));
979
Mathias Agopian888c8222012-08-04 21:10:38 -0700980 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700981}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700982status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
983 Vector<ColorMode>* outColorModes) {
984 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700985 return BAD_VALUE;
986 }
987
Michael Wright28f24d02016-07-12 13:30:53 -0700988 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700989 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
990 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700991 type = i;
992 break;
993 }
994 }
995
996 if (type < 0) {
997 return type;
998 }
999
Peiyong Lina52f0292018-03-14 17:26:31 -07001000 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001001 {
1002 ConditionalLock _l(mStateLock,
1003 std::this_thread::get_id() != mMainThreadId);
1004 modes = getHwComposer().getColorModes(type);
1005 }
Michael Wright28f24d02016-07-12 13:30:53 -07001006 outColorModes->clear();
1007 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1008
1009 return NO_ERROR;
1010}
1011
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001012ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1013 if (const auto display = getDisplayDevice(displayToken)) {
1014 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001015 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001016 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001017}
1018
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001019void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1020 Dataspace dataSpace, RenderIntent renderIntent) {
1021 ColorMode currentMode = display->getActiveColorMode();
1022 Dataspace currentDataSpace = display->getCompositionDataSpace();
1023 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001024
Peiyong Lin38e9a562018-04-10 16:24:20 -07001025 if (mode == currentMode && dataSpace == currentDataSpace &&
1026 renderIntent == currentRenderIntent) {
1027 return;
1028 }
1029
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001030 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001031 ALOGW("Trying to set config for virtual display");
1032 return;
1033 }
1034
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001035 display->setActiveColorMode(mode);
1036 display->setCompositionDataSpace(dataSpace);
1037 display->setActiveRenderIntent(renderIntent);
1038 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001039
1040 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001041 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1042 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001043}
1044
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001045status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001046 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001047 Vector<ColorMode> modes;
1048 getDisplayColorModes(displayToken, &modes);
1049 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1050 if (mode < ColorMode::NATIVE || !exists) {
1051 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1052 decodeColorMode(mode).c_str(), mode, displayToken.get());
1053 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001054 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001055 const auto display = getDisplayDevice(displayToken);
1056 if (!display) {
1057 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1058 decodeColorMode(mode).c_str(), mode, displayToken.get());
1059 } else if (display->isVirtual()) {
1060 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1061 decodeColorMode(mode).c_str(), mode);
1062 } else {
1063 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1064 RenderIntent::COLORIMETRIC);
1065 }
1066 }));
1067
Michael Wright28f24d02016-07-12 13:30:53 -07001068 return NO_ERROR;
1069}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001070
Svetoslavd85084b2014-03-20 10:28:31 -07001071status_t SurfaceFlinger::clearAnimationFrameStats() {
1072 Mutex::Autolock _l(mStateLock);
1073 mAnimFrameTracker.clearStats();
1074 return NO_ERROR;
1075}
1076
1077status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1078 Mutex::Autolock _l(mStateLock);
1079 mAnimFrameTracker.getStats(outStats);
1080 return NO_ERROR;
1081}
1082
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001083status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1084 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001085 Mutex::Autolock _l(mStateLock);
1086
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001087 const auto display = getDisplayDeviceLocked(displayToken);
1088 if (!display) {
1089 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001090 return BAD_VALUE;
1091 }
1092
Peiyong Linfb069302018-04-25 14:34:31 -07001093 // At this point the DisplayDeivce should already be set up,
1094 // meaning the luminance information is already queried from
1095 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001096 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001097 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1098 capabilities.getDesiredMaxLuminance(),
1099 capabilities.getDesiredMaxAverageLuminance(),
1100 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001101
1102 return NO_ERROR;
1103}
1104
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001105status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001106 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001107 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001108
Chia-I Wu90f669f2017-10-05 14:24:41 -07001109 if (mInjectVSyncs == enable) {
1110 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001111 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001112
Ana Krulec98b5b242018-08-10 15:03:23 -07001113 // TODO(akrulec): Part of the Injector should be refactored, so that it
1114 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001115 if (enable) {
1116 ALOGV("VSync Injections enabled");
1117 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001118 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001119 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001120 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001121 impl::EventThread::InterceptVSyncsCallback(),
1122 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001123 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001124 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001125 } else {
1126 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001127 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001128 }
1129
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001130 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001131 }));
1132
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001133 return NO_ERROR;
1134}
1135
1136status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001137 Mutex::Autolock _l(mStateLock);
1138
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001139 if (!mInjectVSyncs) {
1140 ALOGE("VSync Injections not enabled");
1141 return BAD_VALUE;
1142 }
1143 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1144 ALOGV("Injecting VSync inside SurfaceFlinger");
1145 mVSyncInjector->onInjectSyncEvent(when);
1146 }
1147 return NO_ERROR;
1148}
1149
Lloyd Pique755e3192018-01-31 16:46:15 -08001150status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1151 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001152 // Try to acquire a lock for 1s, fail gracefully
1153 const status_t err = mStateLock.timedLock(s2ns(1));
1154 const bool locked = (err == NO_ERROR);
1155 if (!locked) {
1156 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1157 return TIMED_OUT;
1158 }
1159
1160 outLayers->clear();
1161 mCurrentState.traverseInZOrder([&](Layer* layer) {
1162 outLayers->push_back(layer->getLayerDebugInfo());
1163 });
1164
1165 mStateLock.unlock();
1166 return NO_ERROR;
1167}
1168
Peiyong Linc6780972018-10-28 15:24:08 -07001169status_t SurfaceFlinger::getCompositionPreference(
1170 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1171 Dataspace* outWideColorGamutDataspace,
1172 ui::PixelFormat* outWideColorGamutPixelFormat) const {
1173 *outDataspace = defaultCompositionDataspace;
1174 *outPixelFormat = defaultCompositionPixelFormat;
1175 *outWideColorGamutDataspace = wideColorGamutCompositionDataspace;
1176 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001177 return NO_ERROR;
1178}
1179
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001180// ----------------------------------------------------------------------------
1181
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001182sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1183 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001184 if (mUseScheduler) {
1185 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1186 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1187 } else {
1188 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1189 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001190 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001191 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1192 return mSFEventThread->createEventConnection();
1193 } else {
1194 return mEventThread->createEventConnection();
1195 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001196 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001197}
1198
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001199// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001200
1201void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001202 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001203}
1204
1205void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001206 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001207}
1208
1209void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001210 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001211}
1212
1213void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001214 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001215 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001216}
1217
1218status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001219 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001220 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001221}
1222
1223status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001224 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001225 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001226 if (res == NO_ERROR) {
1227 msg->wait();
1228 }
1229 return res;
1230}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001231
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001232void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001233 do {
1234 waitForEvent();
1235 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001236}
1237
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001238void SurfaceFlinger::enableHardwareVsync() {
1239 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001240 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001241 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001242 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001243 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001244 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001245}
1246
Jesse Hall948fe0c2013-10-14 12:56:09 -07001247void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001248 Mutex::Autolock _l(mHWVsyncLock);
1249
Jesse Hall948fe0c2013-10-14 12:56:09 -07001250 if (makeAvailable) {
1251 mHWVsyncAvailable = true;
1252 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001253 // Hardware vsync is not currently available, so abort the resync
1254 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001255 return;
1256 }
1257
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001258 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1259 if (!getHwComposer().isConnected(displayId)) {
1260 return;
1261 }
1262
1263 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001264 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001265
Ana Krulece588e312018-09-18 12:32:24 -07001266 if (mUseScheduler) {
1267 mScheduler->setVsyncPeriod(period);
1268 } else {
1269 mPrimaryDispSync->reset();
1270 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001271
Ana Krulece588e312018-09-18 12:32:24 -07001272 if (!mPrimaryHWVsyncEnabled) {
1273 mPrimaryDispSync->beginResync();
1274 mEventControlThread->setVsyncEnabled(true);
1275 mPrimaryHWVsyncEnabled = true;
1276 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001277 }
1278}
1279
Jesse Hall948fe0c2013-10-14 12:56:09 -07001280void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001281 Mutex::Autolock _l(mHWVsyncLock);
1282 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001283 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001284 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001285 mPrimaryHWVsyncEnabled = false;
1286 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001287 if (makeUnavailable) {
1288 mHWVsyncAvailable = false;
1289 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001290}
1291
Tim Murray4a4e4a22016-04-19 16:29:23 +00001292void SurfaceFlinger::resyncWithRateLimit() {
1293 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001294
1295 // No explicit locking is needed here since EventThread holds a lock while calling this method
1296 static nsecs_t sLastResyncAttempted = 0;
1297 const nsecs_t now = systemTime();
1298 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001299 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001300 }
Dan Stoza57164302017-05-08 14:03:54 -07001301 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001302}
1303
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001304void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1305 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001306 ATRACE_NAME("SF onVsync");
1307
Steven Thomas3cfac282017-02-06 12:29:30 -08001308 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001309 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001310 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001311 return;
1312 }
1313
1314 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001315 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001316 return;
1317 }
1318
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001319 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1320 // For now, we don't do anything with external display vsyncs.
1321 return;
1322 }
1323
Ana Krulece588e312018-09-18 12:32:24 -07001324 if (mUseScheduler) {
1325 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001326 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001327 bool needsHwVsync = false;
1328 { // Scope for the lock
1329 Mutex::Autolock _l(mHWVsyncLock);
1330 if (mPrimaryHWVsyncEnabled) {
1331 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1332 }
1333 }
1334
1335 if (needsHwVsync) {
1336 enableHardwareVsync();
1337 } else {
1338 disableHardwareVsync(false);
1339 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001340 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001341}
1342
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001343void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001344 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1345 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001346}
1347
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001348void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001349 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001350 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001351 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001352
Lloyd Piqueba04e622017-12-14 17:11:26 -08001353 // Ignore events that do not have the right sequenceId.
1354 if (sequenceId != getBE().mComposerSequenceId) {
1355 return;
1356 }
1357
Steven Thomasb02664d2017-07-26 18:48:28 -07001358 // Only lock if we're not on the main thread. This function is normally
1359 // called on a hwbinder thread, but for the primary display it's called on
1360 // the main thread with the state lock already held, so don't attempt to
1361 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001362 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001363
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001364 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001365
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001366 if (std::this_thread::get_id() == mMainThreadId) {
1367 // Process all pending hot plug events immediately if we are on the main thread.
1368 processDisplayHotplugEventsLocked();
1369 }
1370
Lloyd Piqueba04e622017-12-14 17:11:26 -08001371 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001372}
1373
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001374void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001375 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001376 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001377 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001378 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001379 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001380}
1381
Dan Stoza9e56aa02015-11-02 13:00:03 -08001382void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001383 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001384 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001385 getHwComposer().setVsyncEnabled(disp,
1386 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001387}
1388
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001389// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001390void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001391 if (mUseScheduler) {
1392 mScheduler->disableHardwareVsync(true);
1393 } else {
1394 disableHardwareVsync(true);
1395 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001396 // Clear the drawing state so that the logic inside of
1397 // handleTransactionLocked will fire. It will determine the delta between
1398 // mCurrentState and mDrawingState and re-apply all changes when we make the
1399 // transition.
1400 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001401 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001402 mDisplays.clear();
1403}
1404
Steven Thomas050b2c82017-03-06 11:45:16 -08001405void SurfaceFlinger::updateVrFlinger() {
1406 if (!mVrFlinger)
1407 return;
1408 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001409 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001410 return;
1411 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001412
David Sodman105b7dc2017-11-04 20:28:14 -07001413 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001414 ALOGE("Vr flinger is only supported for remote hardware composer"
1415 " service connections. Ignoring request to transition to vr"
1416 " flinger.");
1417 mVrFlingerRequestsDisplay = false;
1418 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001419 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001420
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001421 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001422
Steven Thomas0123ac62018-07-12 11:32:34 -07001423 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001424 LOG_ALWAYS_FATAL_IF(!display);
1425 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001426 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1427 // called below. Clear the reference now so we don't accidentally use it
1428 // later.
1429 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001430
Steven Thomasb02664d2017-07-26 18:48:28 -07001431 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001432 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001433 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001434
Steven Thomasb02664d2017-07-26 18:48:28 -07001435 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001436 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Pique90c115d2018-09-18 21:39:42 -07001437 getBE().mHwc = getFactory().createHWComposer(
1438 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -07001439 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001440
David Sodman105b7dc2017-11-04 20:28:14 -07001441 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1442 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001443
1444 if (vrFlingerRequestsDisplay) {
1445 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001446 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001447
1448 mVisibleRegionsDirty = true;
1449 invalidateHwcGeometry();
1450
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001451 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001452 display = getDefaultDisplayDeviceLocked();
1453 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001454 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001455
Steven Thomasb02664d2017-07-26 18:48:28 -07001456 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001457 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001458 const nsecs_t period = activeConfig->getVsyncPeriod();
1459 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001460
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001461 // The present fences returned from vr_hwc are not an accurate
1462 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001463 if (mUseScheduler) {
1464 mScheduler->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() || !hasSyncFramework);
1465 } else {
1466 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1467 !hasSyncFramework);
1468 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001469
Steven Thomasb02664d2017-07-26 18:48:28 -07001470 // Use phase of 0 since phase is not known.
1471 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001472 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1473 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001474
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001475 resyncToHardwareVsync(false);
1476
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001477 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001478 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001479}
1480
Mathias Agopian4fec8732012-06-29 14:12:52 -07001481void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001482 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001483 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001484 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001485 bool frameMissed = !mHadClientComposition &&
1486 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001487 (mPreviousPresentFence->getSignalTime() ==
1488 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001489 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001490 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001491 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001492 mTimeStats.incrementMissedFrames();
1493 if (mPropagateBackpressure) {
1494 signalLayerUpdate();
1495 break;
1496 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001497 }
Dan Stoza50182882016-07-08 12:02:20 -07001498
Steven Thomas050b2c82017-03-06 11:45:16 -08001499 // Now that we're going to make it to the handleMessageTransaction()
1500 // call below it's safe to call updateVrFlinger(), which will
1501 // potentially trigger a display handoff.
1502 updateVrFlinger();
1503
Dan Stoza6b9454d2014-11-07 16:00:59 -08001504 bool refreshNeeded = handleMessageTransaction();
1505 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001506 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001507 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001508 // Signal a refresh if a transaction modified the window state,
1509 // a new buffer was latched, or if HWC has requested a full
1510 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001511 signalRefresh();
1512 }
1513 break;
1514 }
1515 case MessageQueue::REFRESH: {
1516 handleMessageRefresh();
1517 break;
1518 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001519 }
1520}
1521
Dan Stoza6b9454d2014-11-07 16:00:59 -08001522bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001523 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001524 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001525 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001526 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001527 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001528 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001529}
1530
Mathias Agopian4fec8732012-06-29 14:12:52 -07001531void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001532 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001533
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001534 mRefreshPending = false;
1535
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001536 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001537 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001538 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001539 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001540 for (const auto& [token, display] : mDisplays) {
1541 beginFrame(display);
1542 prepareFrame(display);
1543 doDebugFlashRegions(display, repaintEverything);
1544 doComposition(display, repaintEverything);
1545 }
1546
Adrian Roos1e1a1282017-11-01 19:05:31 +01001547 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001548 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001549
1550 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001551 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001552
Dan Stozabfbffeb2016-07-21 14:49:33 -07001553 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001554 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001555 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001556 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001557 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001558
Alec Mouri86770e52018-09-24 22:40:58 +00001559 // Setup RenderEngine sync fences if native sync is supported.
1560 if (getBE().mRenderEngine->useNativeFenceSync()) {
1561 if (mHadClientComposition) {
1562 base::unique_fd flushFence(getRenderEngine().flush());
1563 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1564 getBE().flushFence = new Fence(std::move(flushFence));
1565 } else {
1566 // Cleanup for hygiene.
1567 getBE().flushFence = Fence::NO_FENCE;
1568 }
1569 }
1570
Jorim Jaggi90535212018-05-23 23:44:06 +02001571 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001572
David Sodman7e4ae112018-02-09 15:02:28 -08001573 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001574 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001575 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001576 compositionInfo.hwc.hwcLayer = nullptr;
1577 }
David Sodmanba340492018-08-05 21:51:33 -07001578 }
David Sodman7e4ae112018-02-09 15:02:28 -08001579
1580 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001581}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001582
David Sodmanfa9b2af2017-12-24 13:28:59 -08001583
1584bool SurfaceFlinger::handleMessageInvalidate() {
1585 ATRACE_CALL();
1586 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001587}
1588
David Sodman79bba0e2018-08-05 18:07:49 -07001589void SurfaceFlinger::calculateWorkingSet() {
1590 ATRACE_CALL();
1591 ALOGV(__FUNCTION__);
1592
David Sodman79bba0e2018-08-05 18:07:49 -07001593 // build the h/w work list
1594 if (CC_UNLIKELY(mGeometryInvalid)) {
1595 mGeometryInvalid = false;
1596 for (const auto& [token, display] : mDisplays) {
1597 const auto displayId = display->getId();
1598 if (displayId >= 0) {
1599 const Vector<sp<Layer>>& currentLayers(
1600 display->getVisibleLayersSortedByZ());
1601 for (size_t i = 0; i < currentLayers.size(); i++) {
1602 const auto& layer = currentLayers[i];
1603
1604 if (!layer->hasHwcLayer(displayId)) {
1605 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1606 layer->forceClientComposition(displayId);
1607 continue;
1608 }
1609 }
1610
1611 layer->setGeometry(display, i);
1612 if (mDebugDisableHWC || mDebugRegion) {
1613 layer->forceClientComposition(displayId);
1614 }
1615 }
1616 }
1617 }
1618 }
1619
1620 // Set the per-frame data
1621 for (const auto& [token, display] : mDisplays) {
1622 const auto displayId = display->getId();
1623 if (displayId < 0) {
1624 continue;
1625 }
1626
1627 if (mDrawingState.colorMatrixChanged) {
1628 display->setColorTransform(mDrawingState.colorMatrix);
1629 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1630 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1631 "display %d: %d", displayId, result);
1632 }
1633 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1634 if (layer->isHdrY410()) {
1635 layer->forceClientComposition(displayId);
1636 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1637 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1638 !display->hasHDR10Support()) {
1639 layer->forceClientComposition(displayId);
1640 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1641 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1642 !display->hasHLGSupport()) {
1643 layer->forceClientComposition(displayId);
1644 }
1645
Peiyong Lind3788632018-09-18 16:01:31 -07001646 // TODO(b/111562338) remove when composer 2.3 is shipped.
1647 if (layer->hasColorTransform()) {
1648 layer->forceClientComposition(displayId);
1649 }
1650
David Sodman79bba0e2018-08-05 18:07:49 -07001651 if (layer->getForceClientComposition(displayId)) {
1652 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1653 layer->setCompositionType(displayId, HWC2::Composition::Client);
1654 continue;
1655 }
1656
1657 layer->setPerFrameData(display);
1658 }
1659
Peiyong Lin13effd12018-07-24 17:01:47 -07001660 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001661 ColorMode colorMode;
1662 Dataspace dataSpace;
1663 RenderIntent renderIntent;
1664 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1665 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1666 }
1667 }
1668
1669 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001670
1671 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001672 getBE().mCompositionInfo[token].clear();
1673
David Sodmanba340492018-08-05 21:51:33 -07001674 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001675 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001676 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1677 if (!layer->setHwcLayer(displayId)) {
1678 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1679 }
David Sodman15fb96e2018-01-07 10:23:24 -08001680 layer->getBE().compositionInfo.hwc.displayId = displayId;
Dominik Laskowski05275f12018-11-01 15:03:24 -07001681 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001682 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1683 }
1684 }
David Sodman79bba0e2018-08-05 18:07:49 -07001685}
1686
David Sodmanfa9b2af2017-12-24 13:28:59 -08001687void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001688{
1689 // is debugging enabled
1690 if (CC_LIKELY(!mDebugRegion))
1691 return;
1692
David Sodmanfa9b2af2017-12-24 13:28:59 -08001693 if (display->isPoweredOn()) {
1694 // transform the dirty region into this screen's coordinate space
1695 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1696 if (!dirtyRegion.isEmpty()) {
1697 // redraw the whole screen
1698 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001699
David Sodmanfa9b2af2017-12-24 13:28:59 -08001700 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001701 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001702 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001703
David Sodmanfa9b2af2017-12-24 13:28:59 -08001704 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001705 }
1706 }
1707
David Sodmanfa9b2af2017-12-24 13:28:59 -08001708 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001709
1710 if (mDebugRegion > 1) {
1711 usleep(mDebugRegion * 1000);
1712 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001713
Dominik Laskowski05275f12018-11-01 15:03:24 -07001714 prepareFrame(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001715}
1716
Adrian Roos1e1a1282017-11-01 19:05:31 +01001717void SurfaceFlinger::doTracing(const char* where) {
1718 ATRACE_CALL();
1719 ATRACE_NAME(where);
1720 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001721 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001722 }
1723}
1724
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001725void SurfaceFlinger::logLayerStats() {
1726 ATRACE_CALL();
1727 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001728 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001729 if (display->isPrimary()) {
1730 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001731 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001732 }
1733 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001734
1735 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001736 }
1737}
1738
David Sodman2b406362017-12-15 13:33:47 -08001739void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001740{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001741 ATRACE_CALL();
1742 ALOGV("preComposition");
1743
David Sodman2b406362017-12-15 13:33:47 -08001744 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1745
Mathias Agopiancd60f992012-08-16 16:28:27 -07001746 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001747 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001748 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001749 needExtraInvalidate = true;
1750 }
Robert Carr2047fae2016-11-28 14:09:09 -08001751 });
1752
Mathias Agopiancd60f992012-08-16 16:28:27 -07001753 if (needExtraInvalidate) {
1754 signalLayerUpdate();
1755 }
1756}
1757
Ana Krulece588e312018-09-18 12:32:24 -07001758void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1759 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001760 // Update queue of past composite+present times and determine the
1761 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001762 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001763 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001764 while (!getBE().mCompositePresentTimes.empty()) {
1765 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001766 // Cached values should have been updated before calling this method,
1767 // which helps avoid duplicate syscalls.
1768 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1769 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1770 break;
1771 }
1772 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001773 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001774 }
1775
1776 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001777 while (getBE().mCompositePresentTimes.size() > 16) {
1778 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001779 }
1780
Ana Krulece588e312018-09-18 12:32:24 -07001781 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001782}
1783
Ana Krulece588e312018-09-18 12:32:24 -07001784void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1785 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001786 // Integer division and modulo round toward 0 not -inf, so we need to
1787 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001788 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1789 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1790 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001791
Brian Andersond0010582017-03-07 13:20:31 -08001792 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1793 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001794 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001795 }
1796
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001797 // Snap the latency to a value that removes scheduling jitter from the
1798 // composition and present times, which often have >1ms of jitter.
1799 // Reducing jitter is important if an app attempts to extrapolate
1800 // something (such as user input) to an accurate diasplay time.
1801 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1802 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001803 nsecs_t bias = stats.vsyncPeriod / 2;
1804 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1805 nsecs_t snappedCompositeToPresentLatency =
1806 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001807
David Sodman99974d22017-11-28 12:04:33 -08001808 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001809 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1810 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001811 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001812}
1813
David Sodman2b406362017-12-15 13:33:47 -08001814void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001815{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001816 ATRACE_CALL();
1817 ALOGV("postComposition");
1818
Brian Anderson3546a3f2016-07-14 11:51:14 -07001819 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001820 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001821 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001822 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001823 }
1824
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001825 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001826 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001827
David Sodman73beded2017-11-15 11:56:06 -08001828 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001829 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001830 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001831 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001832 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001833 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001834 } else {
1835 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1836 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001837
David Sodman73beded2017-11-15 11:56:06 -08001838 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001839 mPreviousPresentFence =
1840 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1841 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001842 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001843
Ana Krulece588e312018-09-18 12:32:24 -07001844 DisplayStatInfo stats;
1845 if (mUseScheduler) {
1846 mScheduler->getDisplayStatInfo(&stats);
1847 } else {
1848 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1849 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
1850 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001851
David Sodman2b406362017-12-15 13:33:47 -08001852 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001853 // when we started doing work for this frame, but that should be okay
1854 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07001855 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001856 CompositorTiming compositorTiming;
1857 {
David Sodman99974d22017-11-28 12:04:33 -08001858 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1859 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001860 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001861
Robert Carr2047fae2016-11-28 14:09:09 -08001862 mDrawingState.traverseInZOrder([&](Layer* layer) {
1863 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001864 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001865 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001866 recordBufferingStats(layer->getName().string(),
1867 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001868 }
Robert Carr2047fae2016-11-28 14:09:09 -08001869 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001870
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001871 if (presentFenceTime->isValid()) {
Ana Krulece588e312018-09-18 12:32:24 -07001872 if (mUseScheduler) {
1873 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001874 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001875 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
1876 enableHardwareVsync();
1877 } else {
1878 disableHardwareVsync(false);
1879 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001880 }
1881 }
1882
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001883 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001884 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07001885 if (mUseScheduler) {
1886 mScheduler->enableHardwareVsync();
1887 } else {
1888 enableHardwareVsync();
1889 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001890 }
1891 }
1892
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001893 if (mAnimCompositionPending) {
1894 mAnimCompositionPending = false;
1895
Brian Anderson4e606e32017-03-16 15:34:57 -07001896 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001897 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001898 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001899 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001900 // The HWC doesn't support present fences, so use the refresh
1901 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001902 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001903 mAnimFrameTracker.setActualPresentTime(presentTime);
1904 }
1905 mAnimFrameTracker.advanceFrame();
1906 }
Dan Stozab90cf072015-03-05 11:05:59 -08001907
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001908 mTimeStats.incrementTotalFrames();
1909 if (mHadClientComposition) {
1910 mTimeStats.incrementClientCompositionFrames();
1911 }
1912
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001913 mTimeStats.setPresentFenceGlobal(presentFenceTime);
1914
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001915 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001916 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001917 return;
1918 }
1919
1920 nsecs_t currentTime = systemTime();
1921 if (mHasPoweredOff) {
1922 mHasPoweredOff = false;
1923 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001924 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001925 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001926 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1927 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001928 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001929 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001930 }
David Sodman4a36e932017-11-07 14:29:47 -08001931 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001932 }
David Sodman4a36e932017-11-07 14:29:47 -08001933 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001934
1935 {
1936 std::lock_guard lock(mTexturePoolMutex);
1937 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1938 if (refillCount > 0) {
1939 const size_t offset = mTexturePool.size();
1940 mTexturePool.resize(mTexturePoolSize);
1941 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1942 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1943 }
1944 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001945}
1946
1947void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001948 ATRACE_CALL();
1949 ALOGV("rebuildLayerStacks");
1950
Mathias Agopiancd60f992012-08-16 16:28:27 -07001951 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001952 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001953 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001954 mVisibleRegionsDirty = false;
1955 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001956
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001957 for (const auto& pair : mDisplays) {
1958 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001959 Region opaqueRegion;
1960 Region dirtyRegion;
1961 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001962 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001963 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001964 const Rect bounds = display->getBounds();
1965 if (display->isPoweredOn()) {
1966 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001967
Jeff Sharkey76488112017-02-27 14:15:18 -07001968 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001969 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001970 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001971 Region drawRegion(tr.transform(
1972 layer->visibleNonTransparentRegion));
1973 drawRegion.andSelf(bounds);
1974 if (!drawRegion.isEmpty()) {
1975 layersSortedByZ.add(layer);
1976 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001977 // Clear out the HWC layer if this layer was
1978 // previously visible, but no longer is
1979 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001980 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001981 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001982 // WM changes display->layerStack upon sleep/awake.
1983 // Here we make sure we delete the HWC layers even if
1984 // WM changed their layer stack.
1985 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001986 }
1987
1988 // If a layer is not going to get a release fence because
1989 // it is invisible, but it is also going to release its
1990 // old buffer, add it to the list of layers needing
1991 // fences.
1992 if (hwcLayerDestroyed) {
1993 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1994 mLayersWithQueuedFrames.cend(), layer);
1995 if (found != mLayersWithQueuedFrames.cend()) {
1996 layersNeedingFences.add(layer);
1997 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001998 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001999 });
2000 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002001 display->setVisibleLayersSortedByZ(layersSortedByZ);
2002 display->setLayersNeedingFences(layersNeedingFences);
2003 display->undefinedRegion.set(bounds);
2004 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2005 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002006 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002007 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002008}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002009
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002010// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002011// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002012// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002013// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002014// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002015// The returned HDR data space is one of
2016// - Dataspace::UNKNOWN
2017// - Dataspace::BT2020_HLG
2018// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002019Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2020 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07002021 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002022 *outHdrDataSpace = Dataspace::UNKNOWN;
2023
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002024 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002025 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002026 case Dataspace::V0_SCRGB:
2027 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002028 case Dataspace::BT2020:
2029 case Dataspace::BT2020_ITU:
2030 case Dataspace::BT2020_LINEAR:
2031 case Dataspace::DISPLAY_BT2020:
2032 bestDataSpace = Dataspace::DISPLAY_BT2020;
2033 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002034 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002035 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002036 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002037 case Dataspace::BT2020_PQ:
2038 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002039 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002040 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002041 case Dataspace::BT2020_HLG:
2042 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002043 // When there's mixed PQ content and HLG content, we set the HDR
2044 // data space to be BT2020_PQ and convert HLG to PQ.
2045 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2046 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002047 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002048 break;
2049 default:
2050 break;
2051 }
Romain Guy54f154a2017-10-24 21:40:32 +01002052 }
2053
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002054 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002055}
2056
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002057// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002058void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2059 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002060 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2061 *outMode = ColorMode::NATIVE;
2062 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002063 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002064 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002065 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002066
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002067 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002068 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002069
Peiyong Lindfde5112018-06-05 10:58:41 -07002070 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002071 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002072 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002073 if (isHdr) {
2074 bestDataSpace = hdrDataSpace;
2075 }
2076
Chia-I Wu0d711262018-05-21 15:19:35 -07002077 RenderIntent intent;
2078 switch (mDisplayColorSetting) {
2079 case DisplayColorSetting::MANAGED:
2080 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002081 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002082 break;
2083 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002084 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002085 break;
2086 default: // vendor display color setting
2087 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2088 break;
2089 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002090
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002091 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002092}
2093
David Sodmanfa9b2af2017-12-24 13:28:59 -08002094void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002095{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002096 bool dirty = !display->getDirtyRegion(false).isEmpty();
2097 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2098 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002099
David Sodmanfa9b2af2017-12-24 13:28:59 -08002100 // If nothing has changed (!dirty), don't recompose.
2101 // If something changed, but we don't currently have any visible layers,
2102 // and didn't when we last did a composition, then skip it this time.
2103 // The second rule does two things:
2104 // - When all layers are removed from a display, we'll emit one black
2105 // frame, then nothing more until we get new layers.
2106 // - When a display is created with a private layer stack, we won't
2107 // emit any black frames until a layer is added to the layer stack.
2108 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002109
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002110 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2111 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002112 mustRecompose ? "doing" : "skipping",
2113 dirty ? "+" : "-",
2114 empty ? "+" : "-",
2115 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002116
David Sodmanfa9b2af2017-12-24 13:28:59 -08002117 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002118
David Sodmanfa9b2af2017-12-24 13:28:59 -08002119 if (mustRecompose) {
2120 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002121 }
2122}
2123
David Sodmanfa9b2af2017-12-24 13:28:59 -08002124void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002125{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002126 if (!display->isPoweredOn()) {
2127 return;
David Sodman2b406362017-12-15 13:33:47 -08002128 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002129
Dominik Laskowski05275f12018-11-01 15:03:24 -07002130 status_t result = display->prepareFrame(getHwComposer(),
2131 getBE().mCompositionInfo[display->getDisplayToken()]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08002132 ALOGE_IF(result != NO_ERROR,
2133 "prepareFrame for display %d failed:"
2134 " %d (%s)",
2135 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002136}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002137
David Sodmanfa9b2af2017-12-24 13:28:59 -08002138void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002139 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002140 ALOGV("doComposition");
2141
David Sodmanfa9b2af2017-12-24 13:28:59 -08002142 if (display->isPoweredOn()) {
2143 // transform the dirty region into this screen's coordinate space
2144 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002145
David Sodmanfa9b2af2017-12-24 13:28:59 -08002146 // repaint the framebuffer (if needed)
2147 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002148
David Sodmanfa9b2af2017-12-24 13:28:59 -08002149 display->dirtyRegion.clear();
2150 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002151 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002152 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002153}
2154
David Sodmanfa9b2af2017-12-24 13:28:59 -08002155void SurfaceFlinger::postFrame()
2156{
2157 // |mStateLock| not needed as we are on the main thread
2158 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2159 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2160 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2161 logFrameStats();
2162 }
2163 }
2164}
2165
2166void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002167{
Mathias Agopian841cde52012-03-01 15:44:37 -08002168 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002169 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002170
David Sodmanfa9b2af2017-12-24 13:28:59 -08002171 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002172
David Sodmanfa9b2af2017-12-24 13:28:59 -08002173 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002174 const auto displayId = display->getId();
2175 if (displayId >= 0) {
2176 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002177 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002178 display->onSwapBuffersCompleted();
2179 display->makeCurrent();
David Sodman15094112018-10-11 09:39:37 -07002180 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002181 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002182
Chia-I Wu7b549592017-11-15 09:14:57 -08002183 // The layer buffer from the previous frame (if any) is released
2184 // by HWC only when the release fence from this frame (if any) is
2185 // signaled. Always get the release fence from HWC first.
David Sodman15094112018-10-11 09:39:37 -07002186 auto hwcLayer = layer->getHwcLayer(displayId);
2187 if (displayId >= 0) {
2188 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002189 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002190
2191 // If the layer was client composited in the previous frame, we
2192 // need to merge with the previous client target acquire fence.
2193 // Since we do not track that, always merge with the current
2194 // client target acquire fence when it is available, even though
2195 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002196 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002197 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002198 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002199 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002200
David Sodman15094112018-10-11 09:39:37 -07002201 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002202 }
Chia-I Wu83806892017-11-16 10:50:20 -08002203
2204 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002205 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002206 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002207 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002208 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002209 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002210 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002211 }
2212 }
2213
Dominik Laskowski7e045462018-05-30 13:02:02 -07002214 if (displayId >= 0) {
2215 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002216 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002217 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002218}
2219
Mathias Agopian87baae12012-07-31 12:38:26 -07002220void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002221{
Mathias Agopian841cde52012-03-01 15:44:37 -08002222 ATRACE_CALL();
2223
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002224 // here we keep a copy of the drawing state (that is the state that's
2225 // going to be overwritten by handleTransactionLocked()) outside of
2226 // mStateLock so that the side-effects of the State assignment
2227 // don't happen with mStateLock held (which can cause deadlocks).
2228 State drawingState(mDrawingState);
2229
Mathias Agopianca4d3602011-05-19 15:38:14 -07002230 Mutex::Autolock _l(mStateLock);
2231 const nsecs_t now = systemTime();
2232 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002233
Mathias Agopianca4d3602011-05-19 15:38:14 -07002234 // Here we're guaranteed that some transaction flags are set
2235 // so we can call handleTransactionLocked() unconditionally.
2236 // We call getTransactionFlags(), which will also clear the flags,
2237 // with mStateLock held to guarantee that mCurrentState won't change
2238 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002239
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002240 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002241 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002242 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002243
Mathias Agopianca4d3602011-05-19 15:38:14 -07002244 mLastTransactionTime = systemTime() - now;
2245 mDebugInTransaction = 0;
2246 invalidateHwcGeometry();
2247 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002248}
2249
Dominik Laskowski7e045462018-05-30 13:02:02 -07002250DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002251 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002252 // Figure out whether the event is for the primary display or an
2253 // external display by matching the Hwc display id against one for a
2254 // connected display. If we did not find a match, we then check what
2255 // displays are not already connected to determine the type. If we don't
2256 // have a connected primary display, we assume the new display is meant to
2257 // be the primary display, and then if we don't have an external display,
2258 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002259 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2260 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002261 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002262 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002263 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002264 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002265 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002266 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002267 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002268 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002269 return DisplayDevice::DISPLAY_EXTERNAL;
2270 }
2271
2272 return DisplayDevice::DISPLAY_ID_INVALID;
2273}
2274
Lloyd Piqueba04e622017-12-14 17:11:26 -08002275void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2276 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002277 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002278 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002279 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002280 continue;
2281 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002282
2283 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2284 ALOGE("External displays are not supported by the vr hardware composer.");
2285 continue;
2286 }
2287
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002288 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002289 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002290 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002291 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002292 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002293
2294 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002295 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002296 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002297 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002298 DisplayDeviceState info;
2299 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002300 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2301 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002302 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002303 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002304 mInterceptor->saveDisplayCreation(info);
2305 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002306 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002307 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002308
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002309 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002310 if (idx >= 0) {
2311 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002312 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002313 mCurrentState.displays.removeItemsAt(idx);
2314 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002315 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002316 }
2317
2318 processDisplayChangesLocked();
2319 }
2320
2321 mPendingHotplugEvents.clear();
2322}
2323
Lloyd Pique99d3da52018-01-22 17:48:03 -08002324sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002325 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002326 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002327 DisplayDeviceCreationArgs creationArgs(this, displayToken, state.type, displayId);
2328 creationArgs.isSecure = state.isSecure;
2329 creationArgs.displaySurface = dispSurface;
2330 creationArgs.hasWideColorGamut = false;
2331 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002332
Peiyong Lin13effd12018-07-24 17:01:47 -07002333 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002334 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002335 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002336 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002337 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002338 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002339
Dominik Laskowski7e045462018-05-30 13:02:02 -07002340 std::vector<RenderIntent> renderIntents =
2341 getHwComposer().getRenderIntents(displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002342 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002343 }
tangrobin6753a022018-08-10 10:58:54 +08002344 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002345
tangrobin6753a022018-08-10 10:58:54 +08002346 if (displayId >= 0) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002347 getHwComposer().getHdrCapabilities(displayId, &creationArgs.hdrCapabilities);
2348 creationArgs.supportedPerFrameMetadata =
2349 getHwComposer().getSupportedPerFrameMetadata(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002350 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002351
Lloyd Pique90c115d2018-09-18 21:39:42 -07002352 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002353 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002354 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002355
2356 /*
2357 * Create our display's surface
2358 */
Peiyong Lin833074a2018-08-28 11:53:54 -07002359 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002360 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002361 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002362 renderSurface->setNativeWindow(nativeWindow.get());
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002363 creationArgs.displayWidth = renderSurface->getWidth();
2364 creationArgs.displayHeight = renderSurface->getHeight();
2365 creationArgs.renderSurface = std::move(renderSurface);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002366
2367 // Make sure that composition can never be stalled by a virtual display
2368 // consumer that isn't processing buffers fast enough. We have to do this
2369 // in two places:
2370 // * Here, in case the display is composed entirely by HWC.
2371 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2372 // window's swap interval in eglMakeCurrent, so they'll override the
2373 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002374 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002375 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2376 }
2377
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002378 creationArgs.displayInstallOrientation = state.type == DisplayDevice::DISPLAY_PRIMARY
2379 ? primaryDisplayOrientation
2380 : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002381
Lloyd Pique99d3da52018-01-22 17:48:03 -08002382 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002383 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002384
Lloyd Pique90c115d2018-09-18 21:39:42 -07002385 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002386
2387 if (maxFrameBufferAcquiredBuffers >= 3) {
2388 nativeWindowSurface->preallocateBuffers();
2389 }
2390
2391 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002392 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002393 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002394 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002395 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002396 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002397 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002398 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002399 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002400 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002401 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002402 display->setLayerStack(state.layerStack);
2403 display->setProjection(state.orientation, state.viewport, state.frame);
2404 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002405
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002406 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002407}
2408
Lloyd Pique347200f2017-12-14 17:00:15 -08002409void SurfaceFlinger::processDisplayChangesLocked() {
2410 // here we take advantage of Vector's copy-on-write semantics to
2411 // improve performance by skipping the transaction entirely when
2412 // know that the lists are identical
2413 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2414 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2415 if (!curr.isIdenticalTo(draw)) {
2416 mVisibleRegionsDirty = true;
2417 const size_t cc = curr.size();
2418 size_t dc = draw.size();
2419
2420 // find the displays that were removed
2421 // (ie: in drawing state but not in current state)
2422 // also handle displays that changed
2423 // (ie: displays that are in both lists)
2424 for (size_t i = 0; i < dc;) {
2425 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2426 if (j < 0) {
2427 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002428 // Call makeCurrent() on the primary display so we can
2429 // be sure that nothing associated with this display
2430 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002431 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2432 defaultDisplay->makeCurrent();
2433 }
2434 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2435 display->disconnect(getHwComposer());
2436 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002437 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002438 if (mUseScheduler) {
2439 mScheduler->hotplugReceived(mAppConnectionHandle,
2440 EventThread::DisplayType::Primary, false);
2441 } else {
2442 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2443 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002444 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002445 if (mUseScheduler) {
2446 mScheduler->hotplugReceived(mAppConnectionHandle,
2447 EventThread::DisplayType::External, false);
2448 } else {
2449 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2450 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002451 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002452 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002453 } else {
2454 // this display is in both lists. see if something changed.
2455 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002456 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002457 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2458 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2459 if (state_binder != draw_binder) {
2460 // changing the surface is like destroying and
2461 // recreating the DisplayDevice, so we just remove it
2462 // from the drawing state, so that it get re-added
2463 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002464 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2465 display->disconnect(getHwComposer());
2466 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002467 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002468 mDrawingState.displays.removeItemsAt(i);
2469 dc--;
2470 // at this point we must loop to the next item
2471 continue;
2472 }
2473
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002474 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002475 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002476 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002477 }
2478 if ((state.orientation != draw[i].orientation) ||
2479 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002480 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002481 }
2482 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002483 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002484 }
2485 }
2486 }
2487 ++i;
2488 }
2489
2490 // find displays that were added
2491 // (ie: in current state but not in drawing state)
2492 for (size_t i = 0; i < cc; i++) {
2493 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2494 const DisplayDeviceState& state(curr[i]);
2495
2496 sp<DisplaySurface> dispSurface;
2497 sp<IGraphicBufferProducer> producer;
2498 sp<IGraphicBufferProducer> bqProducer;
2499 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002500 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002501
Dominik Laskowski7e045462018-05-30 13:02:02 -07002502 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002503 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002504 // Virtual displays without a surface are dormant:
2505 // they have external state (layer stack, projection,
2506 // etc.) but no internal state (i.e. a DisplayDevice).
2507 if (state.surface != nullptr) {
2508 // Allow VR composer to use virtual displays.
2509 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2510 int width = 0;
2511 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2512 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2513 int height = 0;
2514 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2515 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2516 int intFormat = 0;
2517 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2518 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002519 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002520
Dominik Laskowski7e045462018-05-30 13:02:02 -07002521 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2522 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002523 }
2524
2525 // TODO: Plumb requested format back up to consumer
2526
2527 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002528 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002529 bqProducer, bqConsumer,
2530 state.displayName);
2531
2532 dispSurface = vds;
2533 producer = vds;
2534 }
2535 } else {
2536 ALOGE_IF(state.surface != nullptr,
2537 "adding a supported display, but rendering "
2538 "surface is provided (%p), ignoring it",
2539 state.surface.get());
2540
Dominik Laskowski7e045462018-05-30 13:02:02 -07002541 displayId = state.type;
2542 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002543 producer = bqProducer;
2544 }
2545
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002546 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002547 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002548 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002549 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002550 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002551 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002552 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002553 if (mUseScheduler) {
2554 mScheduler->hotplugReceived(mAppConnectionHandle,
2555 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002556 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002557 } else {
2558 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2559 true);
2560 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002561 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002562 if (mUseScheduler) {
2563 mScheduler->hotplugReceived(mAppConnectionHandle,
2564 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002565 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002566 } else {
2567 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2568 true);
2569 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002570 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002571 }
2572 }
2573 }
2574 }
2575 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002576
2577 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002578}
2579
Mathias Agopian87baae12012-07-31 12:38:26 -07002580void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002581{
Dan Stoza7dde5992015-05-22 09:51:44 -07002582 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002583 mCurrentState.traverseInZOrder([](Layer* layer) {
2584 layer->notifyAvailableFrames();
2585 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002586
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002587 /*
2588 * Traversal of the children
2589 * (perform the transaction for each of them if needed)
2590 */
2591
Mathias Agopian3559b072012-08-15 13:46:03 -07002592 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002593 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002594 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002595 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002596
2597 const uint32_t flags = layer->doTransaction(0);
2598 if (flags & Layer::eVisibleRegion)
2599 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002600 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002601 }
2602
2603 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002604 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002605 */
2606
Mathias Agopiane57f2922012-08-09 16:29:12 -07002607 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002608 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002609 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002610 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002611
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002612 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002613 // The transform hint might have changed for some layers
2614 // (either because a display has changed, or because a layer
2615 // as changed).
2616 //
2617 // Walk through all the layers in currentLayers,
2618 // and update their transform hint.
2619 //
2620 // If a layer is visible only on a single display, then that
2621 // display is used to calculate the hint, otherwise we use the
2622 // default display.
2623 //
2624 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2625 // the hint is set before we acquire a buffer from the surface texture.
2626 //
2627 // NOTE: layer transactions have taken place already, so we use their
2628 // drawing state. However, SurfaceFlinger's own transaction has not
2629 // happened yet, so we must use the current state layer list
2630 // (soon to become the drawing state list).
2631 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002632 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002633 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002634 bool first = true;
2635 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002636 // NOTE: we rely on the fact that layers are sorted by
2637 // layerStack first (so we don't have to traverse the list
2638 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002639 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002640 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002641 currentlayerStack = layerStack;
2642 // figure out if this layerstack is mirrored
2643 // (more than one display) if so, pick the default display,
2644 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002645 hintDisplay = nullptr;
2646 for (const auto& [token, display] : mDisplays) {
2647 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2648 if (hintDisplay) {
2649 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002650 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002651 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002652 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002653 }
2654 }
2655 }
2656 }
Chet Haase91d25932013-04-11 15:24:55 -07002657
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002658 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002659 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2660 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002661
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002662 // could be null when this layer is using a layerStack
2663 // that is not visible on any display. Also can occur at
2664 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002665 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002666 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002667
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002668 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002669 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002670 if (hintDisplay) {
2671 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002672 }
Robert Carr2047fae2016-11-28 14:09:09 -08002673
2674 first = false;
2675 });
Mathias Agopian84300952012-11-21 16:02:13 -08002676 }
2677
2678
Mathias Agopian3559b072012-08-15 13:46:03 -07002679 /*
2680 * Perform our own transaction if needed
2681 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002682
2683 if (mLayersAdded) {
2684 mLayersAdded = false;
2685 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002686 mVisibleRegionsDirty = true;
2687 }
2688
2689 // some layers might have been removed, so
2690 // we need to update the regions they're exposing.
2691 if (mLayersRemoved) {
2692 mLayersRemoved = false;
2693 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002694 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002695 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002696 // this layer is not visible anymore
2697 // TODO: we could traverse the tree from front to back and
2698 // compute the actual visible region
2699 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002700 Region visibleReg;
2701 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002702 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002703 }
Robert Carr2047fae2016-11-28 14:09:09 -08002704 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002705 }
2706
2707 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002708
2709 updateCursorAsync();
2710}
2711
2712void SurfaceFlinger::updateCursorAsync()
2713{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002714 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002715 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002716 continue;
2717 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002718
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002719 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2720 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002721 }
2722 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002723}
2724
2725void SurfaceFlinger::commitTransaction()
2726{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002727 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002728 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002729 for (const auto& l : mLayersPendingRemoval) {
2730 recordBufferingStats(l->getName().string(),
2731 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002732
2733 // We need to release the HWC layers when the Layer is removed
2734 // from the current state otherwise the HWC layer just continues
2735 // showing at its last configured state until we eventually
2736 // abandon the buffer queue.
2737 if (l->isRemovedFromCurrentState()) {
2738 l->destroyAllHwcLayers();
2739 l->releasePendingBuffer(systemTime());
2740 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002741 }
2742 mLayersPendingRemoval.clear();
2743 }
2744
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002745 // If this transaction is part of a window animation then the next frame
2746 // we composite should be considered an animation as well.
2747 mAnimCompositionPending = mAnimTransactionPending;
2748
Mathias Agopian4fec8732012-06-29 14:12:52 -07002749 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002750 // clear the "changed" flags in current state
2751 mCurrentState.colorMatrixChanged = false;
2752
Robert Carr1f0a16a2016-10-24 16:27:39 -07002753 mDrawingState.traverseInZOrder([](Layer* layer) {
2754 layer->commitChildList();
2755 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002756 mTransactionPending = false;
2757 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002758 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002759}
2760
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002761void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2762 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002763 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002764 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002765
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002766 Region aboveOpaqueLayers;
2767 Region aboveCoveredLayers;
2768 Region dirty;
2769
Mathias Agopian87baae12012-07-31 12:38:26 -07002770 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002771
Robert Carr2047fae2016-11-28 14:09:09 -08002772 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002773 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002774 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002775
Jesse Hall01e29052013-02-19 16:13:35 -08002776 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002777 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002778 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002779 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002780
Mathias Agopianab028732010-03-16 16:41:46 -07002781 /*
2782 * opaqueRegion: area of a surface that is fully opaque.
2783 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002784 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002785
2786 /*
2787 * visibleRegion: area of a surface that is visible on screen
2788 * and not fully transparent. This is essentially the layer's
2789 * footprint minus the opaque regions above it.
2790 * Areas covered by a translucent surface are considered visible.
2791 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002792 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002793
2794 /*
2795 * coveredRegion: area of a surface that is covered by all
2796 * visible regions above it (which includes the translucent areas).
2797 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002798 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002799
Jesse Halla8026d22012-09-25 13:25:04 -07002800 /*
2801 * transparentRegion: area of a surface that is hinted to be completely
2802 * transparent. This is only used to tell when the layer has no visible
2803 * non-transparent regions and can be removed from the layer list. It
2804 * does not affect the visibleRegion of this layer or any layers
2805 * beneath it. The hint may not be correct if apps don't respect the
2806 * SurfaceView restrictions (which, sadly, some don't).
2807 */
2808 Region transparentRegion;
2809
Mathias Agopianab028732010-03-16 16:41:46 -07002810
2811 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002812 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002813 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002814 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002815 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002816 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002817 if (!visibleRegion.isEmpty()) {
2818 // Remove the transparent area from the visible region
2819 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002820 if (tr.preserveRects()) {
2821 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002822 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002823 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002824 // transformation too complex, can't do the
2825 // transparent region optimization.
2826 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002827 }
Mathias Agopianab028732010-03-16 16:41:46 -07002828 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002829
Mathias Agopianab028732010-03-16 16:41:46 -07002830 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002831 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002832 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002833 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002834 // the opaque region is the layer's footprint
2835 opaqueRegion = visibleRegion;
2836 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002837 }
2838 }
2839
Robert Carre5f4f692018-01-12 13:12:28 -08002840 if (visibleRegion.isEmpty()) {
2841 layer->clearVisibilityRegions();
2842 return;
2843 }
2844
Mathias Agopianab028732010-03-16 16:41:46 -07002845 // Clip the covered region to the visible region
2846 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2847
2848 // Update aboveCoveredLayers for next (lower) layer
2849 aboveCoveredLayers.orSelf(visibleRegion);
2850
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002851 // subtract the opaque region covered by the layers above us
2852 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002853
2854 // compute this layer's dirty region
2855 if (layer->contentDirty) {
2856 // we need to invalidate the whole region
2857 dirty = visibleRegion;
2858 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002859 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002860 layer->contentDirty = false;
2861 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002862 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002863 * the exposed region consists of two components:
2864 * 1) what's VISIBLE now and was COVERED before
2865 * 2) what's EXPOSED now less what was EXPOSED before
2866 *
2867 * note that (1) is conservative, we start with the whole
2868 * visible region but only keep what used to be covered by
2869 * something -- which mean it may have been exposed.
2870 *
2871 * (2) handles areas that were not covered by anything but got
2872 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002873 */
Mathias Agopianab028732010-03-16 16:41:46 -07002874 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002875 const Region oldVisibleRegion = layer->visibleRegion;
2876 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002877 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2878 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002879 }
2880 dirty.subtractSelf(aboveOpaqueLayers);
2881
2882 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002883 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002884
Mathias Agopianab028732010-03-16 16:41:46 -07002885 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002886 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002887
Jesse Halla8026d22012-09-25 13:25:04 -07002888 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002889 layer->setVisibleRegion(visibleRegion);
2890 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002891 layer->setVisibleNonTransparentRegion(
2892 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002893 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002894
Mathias Agopian87baae12012-07-31 12:38:26 -07002895 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002896}
2897
Chia-I Wuab0c3192017-08-01 11:29:00 -07002898void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002899 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002900 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2901 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002902 }
2903 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002904}
2905
Dan Stoza6b9454d2014-11-07 16:00:59 -08002906bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002907{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002908 ALOGV("handlePageFlip");
2909
Brian Andersond6927fb2016-07-23 23:37:30 -07002910 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002911
Mathias Agopian4fec8732012-06-29 14:12:52 -07002912 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002913 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002914 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002915
2916 // Store the set of layers that need updates. This set must not change as
2917 // buffers are being latched, as this could result in a deadlock.
2918 // Example: Two producers share the same command stream and:
2919 // 1.) Layer 0 is latched
2920 // 2.) Layer 0 gets a new frame
2921 // 2.) Layer 1 gets a new frame
2922 // 3.) Layer 1 is latched.
2923 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2924 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002925 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002926 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002927 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002928 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2929 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002930 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002931 } else {
2932 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002933 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002934 } else {
2935 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002936 }
Robert Carr2047fae2016-11-28 14:09:09 -08002937 });
2938
Dan Stoza9e56aa02015-11-02 13:00:03 -08002939 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri86770e52018-09-24 22:40:58 +00002940 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
Dan Stozaee44edd2015-03-23 15:50:23 -07002941 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002942 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002943 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002944 newDataLatched = true;
2945 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002946 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002947
Alec Mouri86770e52018-09-24 22:40:58 +00002948 // Clear the renderengine fence here...
2949 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
2950 // clear instead of sp::clear.
2951 getBE().flushFence = Fence::NO_FENCE;
2952
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002953 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002954
2955 // If we will need to wake up at some time in the future to deal with a
2956 // queued frame that shouldn't be displayed during this vsync period, wake
2957 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002958 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002959 signalLayerUpdate();
2960 }
2961
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002962 // enter boot animation on first buffer latch
2963 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2964 ALOGI("Enter boot animation");
2965 mBootStage = BootStage::BOOTANIMATION;
2966 }
2967
Dan Stoza6b9454d2014-11-07 16:00:59 -08002968 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002969 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002970}
2971
Mathias Agopianad456f92011-01-13 17:53:01 -08002972void SurfaceFlinger::invalidateHwcGeometry()
2973{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002974 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002975}
2976
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002977void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2978 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002979 // We only need to actually compose the display if:
2980 // 1) It is being handled by hardware composer, which may need this to
2981 // keep its virtual display state machine in sync, or
2982 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002983 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002984 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002985 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002986 return;
2987 }
2988
Dan Stoza9e56aa02015-11-02 13:00:03 -08002989 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002990 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002991
2992 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002993 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002994}
2995
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002996bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002997 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002998
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002999 const Region bounds(display->bounds());
3000 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003001 const auto displayId = display->getId();
3002 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003003 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003004
Peiyong Lind3788632018-09-18 16:01:31 -07003005 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003006 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003007 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003008
Dan Stoza9e56aa02015-11-02 13:00:03 -08003009 if (hasClientComposition) {
3010 ALOGV("hasClientComposition");
3011
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003012 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003013 if (display->hasWideColorGamut()) {
3014 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003015 }
3016 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003017 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003018 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003019
Dominik Laskowski7e045462018-05-30 13:02:02 -07003020 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003021 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3022 HWC2::Capability::SkipClientColorTransform);
3023
Peiyong Lind3788632018-09-18 16:01:31 -07003024 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003025 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3026 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003027 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003028 }
3029
Chia-I Wud49d6692018-06-27 07:17:41 +08003030 // The current enhanced saturation matrix is designed to enhance Display P3,
3031 // thus we only apply this matrix when the render intent is not colorimetric
3032 // and the output color space is Display P3.
3033 needsEnhancedColorMatrix =
3034 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3035 outputDataspace == Dataspace::DISPLAY_P3);
3036 if (needsEnhancedColorMatrix) {
3037 colorMatrix *= mEnhancedSaturationMatrix;
3038 }
3039
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003040 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003041 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003042 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003043 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003044
3045 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003046 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3047 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3048 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003049 }
3050 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003051 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003052
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003053 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003054 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003055 // when using overlays, we assume a fully transparent framebuffer
3056 // NOTE: we could reduce how much we need to clear, for instance
3057 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003058 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003059 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003060 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003061 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003062 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003063 // we're left with the letterbox region
3064 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003065 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003066
3067 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003068 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003069
Mathias Agopianb9494d52012-04-18 02:28:45 -07003070 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003071 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003072 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003073 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003074 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003075 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003076
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003077 const Rect& bounds = display->getBounds();
3078 const Rect& scissor = display->getScissor();
3079 if (scissor != bounds) {
3080 // scissor doesn't match the screen's dimensions, so we
3081 // need to clear everything outside of it and enable
3082 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003083
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003084 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003085 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003086 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003087 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003088
Mathias Agopian85d751c2012-08-29 16:59:24 -07003089 /*
3090 * and then, render the layers targeted at the framebuffer
3091 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003092
Dan Stoza9e56aa02015-11-02 13:00:03 -08003093 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003094 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003095 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003096 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003097 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003098 displayTransform.transform(layer->visibleRegion)));
3099 ALOGV("Layer: %s", layer->getName().string());
3100 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003101 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003102 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003103 case HWC2::Composition::Cursor:
3104 case HWC2::Composition::Device:
3105 case HWC2::Composition::Sideband:
3106 case HWC2::Composition::SolidColor: {
David Sodmanc1498e62018-09-12 14:36:26 -07003107 const Layer::State& state(layer->getDrawingState());
3108 if (layer->getClearClientTarget(displayId) && !firstLayer &&
3109 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3110 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003111 // never clear the very first layer since we're
3112 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003113 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003114 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003115 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003116 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003117 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003118 if (layer->hasColorTransform()) {
3119 mat4 tmpMatrix;
3120 if (applyColorMatrix) {
3121 tmpMatrix = mDrawingState.colorMatrix;
3122 }
3123 tmpMatrix *= layer->getColorTransform();
3124 if (needsEnhancedColorMatrix) {
3125 tmpMatrix *= mEnhancedSaturationMatrix;
3126 }
3127 getRenderEngine().setColorTransform(tmpMatrix);
3128 } else {
3129 getRenderEngine().setColorTransform(colorMatrix);
3130 }
David Sodmanc1498e62018-09-12 14:36:26 -07003131 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003132 break;
3133 }
3134 default:
3135 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003136 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003137 } else {
3138 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003139 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003140 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003141 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003142
Peiyong Lind3788632018-09-18 16:01:31 -07003143 // Clear color transform matrix at the end of the frame.
3144 getRenderEngine().setColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003145
Mathias Agopianf45c5102012-10-24 16:29:17 -07003146 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003147 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003148 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003149}
3150
Chia-I Wu28e3a252018-09-07 12:05:02 -07003151void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003152 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003153 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003154}
3155
Dan Stoza7d89d062015-04-30 13:29:25 -07003156status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003157 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003158 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003159 const sp<Layer>& lbc,
3160 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003161{
Dan Stoza7d89d062015-04-30 13:29:25 -07003162 // add this layer to the current state list
3163 {
3164 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003165 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003166 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3167 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003168 return NO_MEMORY;
3169 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003170 if (parent == nullptr) {
3171 mCurrentState.layersSortedByZ.add(lbc);
3172 } else {
Robert Carr2e102c92018-10-23 12:11:15 -07003173 if (parent->isRemovedFromCurrentState()) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003174 ALOGE("addClientLayer called with a removed parent");
3175 return NAME_NOT_FOUND;
3176 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003177 parent->addChild(lbc);
3178 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003179
Yiwei Zhang243b3782018-05-15 17:40:04 -07003180 if (gbc != nullptr) {
3181 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3182 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3183 mMaxGraphicBufferProducerListSize,
3184 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3185 mGraphicBufferProducerList.size(),
3186 mMaxGraphicBufferProducerListSize, mNumLayers);
3187 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003188 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003189 }
3190
Mathias Agopian96f08192010-06-02 23:28:45 -07003191 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003192 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003193
Dan Stoza7d89d062015-04-30 13:29:25 -07003194 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003195}
3196
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003197status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003198 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003199 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3200}
Robert Carr7f9b8992017-03-10 11:08:39 -08003201
Robert Carr2e102c92018-10-23 12:11:15 -07003202status_t SurfaceFlinger::removeLayerLocked(const Mutex& lock, const sp<Layer>& layer,
chaviwca27f252018-02-06 16:46:39 -08003203 bool topLevelOnly) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003204 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003205 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003206 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003207 if (topLevelOnly) {
3208 return NO_ERROR;
3209 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003210 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003211 } else {
3212 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003213 }
3214
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003215 layer->onRemovedFromCurrentState();
Robert Carr2e102c92018-10-23 12:11:15 -07003216
3217 markLayerPendingRemovalLocked(lock, layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003218 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003219}
3220
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003221uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003222 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003223}
3224
Mathias Agopian3f844832013-08-07 21:24:32 -07003225uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003226 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003227}
3228
Mathias Agopian3f844832013-08-07 21:24:32 -07003229uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003230 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003231}
3232
3233uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003234 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003235 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003236 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003237 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003238 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003239 }
3240 return old;
3241}
3242
chaviwca27f252018-02-06 16:46:39 -08003243bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3244 for (const ComposerState& state : states) {
3245 // Here we need to check that the interface we're given is indeed
3246 // one of our own. A malicious client could give us a nullptr
3247 // IInterface, or one of its own or even one of our own but a
3248 // different type. All these situations would cause us to crash.
3249 if (state.client == nullptr) {
3250 return true;
3251 }
3252
3253 sp<IBinder> binder = IInterface::asBinder(state.client);
3254 if (binder == nullptr) {
3255 return true;
3256 }
3257
3258 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3259 return true;
3260 }
3261 }
3262 return false;
3263}
3264
Mathias Agopian8b33f032012-07-24 20:43:54 -07003265void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003266 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003267 const Vector<DisplayState>& displays,
3268 uint32_t flags)
3269{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003270 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003271 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003272 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003273
chaviwca27f252018-02-06 16:46:39 -08003274 if (containsAnyInvalidClientState(states)) {
3275 return;
3276 }
3277
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003278 if (flags & eAnimation) {
3279 // For window updates that are part of an animation we must wait for
3280 // previous animation "frames" to be handled.
3281 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003282 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003283 if (CC_UNLIKELY(err != NO_ERROR)) {
3284 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003285 // caller after a few seconds.
3286 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3287 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003288 mAnimTransactionPending = false;
3289 break;
3290 }
3291 }
3292 }
3293
chaviwca27f252018-02-06 16:46:39 -08003294 for (const DisplayState& display : displays) {
3295 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003296 }
3297
chaviwca27f252018-02-06 16:46:39 -08003298 for (const ComposerState& state : states) {
3299 transactionFlags |= setClientStateLocked(state);
3300 }
3301
3302 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3303 // as destroyed should only occur after setting all other states. This is to allow for a
3304 // child re-parent to happen before marking its original parent as destroyed (which would
3305 // then mark the child as destroyed).
3306 for (const ComposerState& state : states) {
3307 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003308 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003309
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003310 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3311 // anyway. This can be used as a flush mechanism for previous async transactions.
3312 // Empty animation transaction can be used to simulate back-pressure, so also force a
3313 // transaction for empty animation transactions.
3314 if (transactionFlags == 0 &&
3315 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003316 transactionFlags = eTransactionNeeded;
3317 }
3318
Mathias Agopian386aa982011-11-07 21:58:03 -08003319 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003320 if (mInterceptor->isEnabled()) {
3321 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003322 }
Irvel468051e2016-06-13 16:44:44 -07003323
Mathias Agopian386aa982011-11-07 21:58:03 -08003324 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003325 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3326 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003327 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003328
3329 // if this is a synchronous transaction, wait for it to take effect
3330 // before returning.
3331 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003332 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003333 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003334 if (flags & eAnimation) {
3335 mAnimTransactionPending = true;
3336 }
3337 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003338 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3339 if (CC_UNLIKELY(err != NO_ERROR)) {
3340 // just in case something goes wrong in SF, return to the
3341 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003342 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3343 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003344 break;
3345 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003346 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003347 }
3348}
3349
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003350uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3351 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3352 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003353
Mathias Agopiane57f2922012-08-09 16:29:12 -07003354 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003355 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3356
3357 const uint32_t what = s.what;
3358 if (what & DisplayState::eSurfaceChanged) {
3359 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3360 state.surface = s.surface;
3361 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003362 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003363 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003364 if (what & DisplayState::eLayerStackChanged) {
3365 if (state.layerStack != s.layerStack) {
3366 state.layerStack = s.layerStack;
3367 flags |= eDisplayTransactionNeeded;
3368 }
3369 }
3370 if (what & DisplayState::eDisplayProjectionChanged) {
3371 if (state.orientation != s.orientation) {
3372 state.orientation = s.orientation;
3373 flags |= eDisplayTransactionNeeded;
3374 }
3375 if (state.frame != s.frame) {
3376 state.frame = s.frame;
3377 flags |= eDisplayTransactionNeeded;
3378 }
3379 if (state.viewport != s.viewport) {
3380 state.viewport = s.viewport;
3381 flags |= eDisplayTransactionNeeded;
3382 }
3383 }
3384 if (what & DisplayState::eDisplaySizeChanged) {
3385 if (state.width != s.width) {
3386 state.width = s.width;
3387 flags |= eDisplayTransactionNeeded;
3388 }
3389 if (state.height != s.height) {
3390 state.height = s.height;
3391 flags |= eDisplayTransactionNeeded;
3392 }
3393 }
3394
Mathias Agopiane57f2922012-08-09 16:29:12 -07003395 return flags;
3396}
3397
Robert Carrd4ae7f32018-06-07 16:10:57 -07003398bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3399 IPCThreadState* ipc = IPCThreadState::self();
3400 const int pid = ipc->getCallingPid();
3401 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003402 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003403 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003404 return false;
3405 }
3406 return true;
3407}
3408
chaviwca27f252018-02-06 16:46:39 -08003409uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3410 const layer_state_t& s = composerState.state;
3411 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3412
Mathias Agopian13127d82013-03-05 17:47:11 -08003413 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003414 if (layer == nullptr) {
3415 return 0;
3416 }
3417
chaviw8b3871a2017-11-01 17:41:01 -07003418 uint32_t flags = 0;
3419
3420 const uint32_t what = s.what;
3421 bool geometryAppliesWithResize =
3422 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003423
3424 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3425 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003426 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003427 layer->pushPendingState();
3428 }
3429
chaviw8b3871a2017-11-01 17:41:01 -07003430 if (what & layer_state_t::ePositionChanged) {
3431 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3432 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003433 }
chaviw8b3871a2017-11-01 17:41:01 -07003434 }
3435 if (what & layer_state_t::eLayerChanged) {
3436 // NOTE: index needs to be calculated before we update the state
3437 const auto& p = layer->getParent();
3438 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003439 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003440 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003441 mCurrentState.layersSortedByZ.removeAt(idx);
3442 mCurrentState.layersSortedByZ.add(layer);
3443 // we need traversal (state changed)
3444 // AND transaction (list changed)
3445 flags |= eTransactionNeeded|eTraversalNeeded;
3446 }
chaviw8b3871a2017-11-01 17:41:01 -07003447 } else {
3448 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003449 flags |= eTransactionNeeded|eTraversalNeeded;
3450 }
3451 }
chaviw8b3871a2017-11-01 17:41:01 -07003452 }
3453 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003454 // NOTE: index needs to be calculated before we update the state
3455 const auto& p = layer->getParent();
3456 if (p == nullptr) {
3457 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3458 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3459 mCurrentState.layersSortedByZ.removeAt(idx);
3460 mCurrentState.layersSortedByZ.add(layer);
3461 // we need traversal (state changed)
3462 // AND transaction (list changed)
3463 flags |= eTransactionNeeded|eTraversalNeeded;
3464 }
3465 } else {
3466 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3467 flags |= eTransactionNeeded|eTraversalNeeded;
3468 }
chaviw8b3871a2017-11-01 17:41:01 -07003469 }
3470 }
3471 if (what & layer_state_t::eSizeChanged) {
3472 if (layer->setSize(s.w, s.h)) {
3473 flags |= eTraversalNeeded;
3474 }
3475 }
3476 if (what & layer_state_t::eAlphaChanged) {
3477 if (layer->setAlpha(s.alpha))
3478 flags |= eTraversalNeeded;
3479 }
3480 if (what & layer_state_t::eColorChanged) {
3481 if (layer->setColor(s.color))
3482 flags |= eTraversalNeeded;
3483 }
Peiyong Lind3788632018-09-18 16:01:31 -07003484 if (what & layer_state_t::eColorTransformChanged) {
3485 if (layer->setColorTransform(s.colorTransform)) {
3486 flags |= eTraversalNeeded;
3487 }
3488 }
chaviw8b3871a2017-11-01 17:41:01 -07003489 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003490 // TODO: b/109894387
3491 //
3492 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3493 // rotation. To see the problem observe that if we have a square parent, and a child
3494 // of the same size, then we rotate the child 45 degrees around it's center, the child
3495 // must now be cropped to a non rectangular 8 sided region.
3496 //
3497 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3498 // private API, and the WindowManager only uses rotation in one case, which is on a top
3499 // level layer in which cropping is not an issue.
3500 //
3501 // However given that abuse of rotation matrices could lead to surfaces extending outside
3502 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3503 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3504 // transformations.
3505 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003506 flags |= eTraversalNeeded;
3507 }
3508 if (what & layer_state_t::eTransparentRegionChanged) {
3509 if (layer->setTransparentRegionHint(s.transparentRegion))
3510 flags |= eTraversalNeeded;
3511 }
3512 if (what & layer_state_t::eFlagsChanged) {
3513 if (layer->setFlags(s.flags, s.mask))
3514 flags |= eTraversalNeeded;
3515 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003516 if (what & layer_state_t::eCropChanged_legacy) {
3517 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003518 flags |= eTraversalNeeded;
3519 }
chaviw8b3871a2017-11-01 17:41:01 -07003520 if (what & layer_state_t::eLayerStackChanged) {
3521 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3522 // We only allow setting layer stacks for top level layers,
3523 // everything else inherits layer stack from its parent.
3524 if (layer->hasParent()) {
3525 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3526 layer->getName().string());
3527 } else if (idx < 0) {
3528 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3529 "that also does not appear in the top level layer list. Something"
3530 " has gone wrong.", layer->getName().string());
3531 } else if (layer->setLayerStack(s.layerStack)) {
3532 mCurrentState.layersSortedByZ.removeAt(idx);
3533 mCurrentState.layersSortedByZ.add(layer);
3534 // we need traversal (state changed)
3535 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003536 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003537 }
3538 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003539 if (what & layer_state_t::eDeferTransaction_legacy) {
3540 if (s.barrierHandle_legacy != nullptr) {
3541 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3542 } else if (s.barrierGbp_legacy != nullptr) {
3543 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003544 if (authenticateSurfaceTextureLocked(gbp)) {
3545 const auto& otherLayer =
3546 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003547 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003548 } else {
3549 ALOGE("Attempt to defer transaction to to an"
3550 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003551 }
3552 }
chaviw8b3871a2017-11-01 17:41:01 -07003553 // We don't trigger a traversal here because if no other state is
3554 // changed, we don't want this to cause any more work
3555 }
3556 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003557 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003558 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003559 if (!hadParent) {
3560 mCurrentState.layersSortedByZ.remove(layer);
3561 }
chaviw8b3871a2017-11-01 17:41:01 -07003562 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003563 }
chaviw8b3871a2017-11-01 17:41:01 -07003564 }
3565 if (what & layer_state_t::eReparentChildren) {
3566 if (layer->reparentChildren(s.reparentHandle)) {
3567 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003568 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003569 }
chaviw8b3871a2017-11-01 17:41:01 -07003570 if (what & layer_state_t::eDetachChildren) {
3571 layer->detachChildren();
3572 }
3573 if (what & layer_state_t::eOverrideScalingModeChanged) {
3574 layer->setOverrideScalingMode(s.overrideScalingMode);
3575 // We don't trigger a traversal here because if no other state is
3576 // changed, we don't want this to cause any more work
3577 }
Marissa Wall61c58622018-07-18 10:12:20 -07003578 if (what & layer_state_t::eTransformChanged) {
3579 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3580 }
3581 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3582 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3583 flags |= eTraversalNeeded;
3584 }
3585 if (what & layer_state_t::eCropChanged) {
3586 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3587 }
3588 if (what & layer_state_t::eBufferChanged) {
3589 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3590 }
3591 if (what & layer_state_t::eAcquireFenceChanged) {
3592 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3593 }
3594 if (what & layer_state_t::eDataspaceChanged) {
3595 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3596 }
3597 if (what & layer_state_t::eHdrMetadataChanged) {
3598 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3599 }
3600 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3601 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3602 }
3603 if (what & layer_state_t::eApiChanged) {
3604 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3605 }
3606 if (what & layer_state_t::eSidebandStreamChanged) {
3607 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3608 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003609 return flags;
3610}
3611
chaviwca27f252018-02-06 16:46:39 -08003612void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3613 const layer_state_t& state = composerState.state;
3614 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3615
3616 sp<Layer> layer(client->getLayerUser(state.surface));
3617 if (layer == nullptr) {
3618 return;
3619 }
3620
chaviwca27f252018-02-06 16:46:39 -08003621 if (state.what & layer_state_t::eDestroySurface) {
3622 removeLayerLocked(mStateLock, layer);
3623 }
3624}
3625
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003626status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003627 const String8& name,
3628 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003629 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003630 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003631 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003632{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003633 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003634 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003635 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003636 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003637 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003638
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003639 status_t result = NO_ERROR;
3640
3641 sp<Layer> layer;
3642
Cody Northropbc755282017-03-31 12:00:08 -06003643 String8 uniqueName = getUniqueLayerName(name);
3644
Mathias Agopian3165cc22012-08-08 19:42:09 -07003645 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003646 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003647 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3648 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003649
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003650 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003651 case ISurfaceComposerClient::eFXSurfaceBufferState:
3652 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3653 break;
chaviw13fdc492017-06-27 12:40:18 -07003654 case ISurfaceComposerClient::eFXSurfaceColor:
3655 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003656 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003657 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003658 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003659 case ISurfaceComposerClient::eFXSurfaceContainer:
3660 result = createContainerLayer(client,
3661 uniqueName, w, h, flags,
3662 handle, &layer);
3663 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003664 default:
3665 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003666 break;
3667 }
3668
Dan Stoza7d89d062015-04-30 13:29:25 -07003669 if (result != NO_ERROR) {
3670 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003671 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003672
Chia-I Wuab0c3192017-08-01 11:29:00 -07003673 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3674 // TODO b/64227542
3675 if (windowType == 441731) {
3676 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3677 layer->setPrimaryDisplayOnly();
3678 }
3679
Albert Chaulk479c60c2017-01-27 14:21:34 -05003680 layer->setInfo(windowType, ownerUid);
3681
Robert Carr1f0a16a2016-10-24 16:27:39 -07003682 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003683 if (result != NO_ERROR) {
3684 return result;
3685 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003686 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003687
3688 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003689 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003690}
3691
Cody Northropbc755282017-03-31 12:00:08 -06003692String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3693{
3694 bool matchFound = true;
3695 uint32_t dupeCounter = 0;
3696
3697 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3698 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3699
Dan Stoza436ccf32018-06-21 12:10:12 -07003700 // Grab the state lock since we're accessing mCurrentState
3701 Mutex::Autolock lock(mStateLock);
3702
Cody Northropbc755282017-03-31 12:00:08 -06003703 // Loop over layers until we're sure there is no matching name
3704 while (matchFound) {
3705 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003706 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003707 if (layer->getName() == uniqueName) {
3708 matchFound = true;
3709 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3710 }
3711 });
3712 }
3713
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003714 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3715 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003716
3717 return uniqueName;
3718}
3719
Marissa Wallfd668622018-05-10 10:21:13 -07003720status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3721 uint32_t w, uint32_t h, uint32_t flags,
3722 PixelFormat& format, sp<IBinder>* handle,
3723 sp<IGraphicBufferProducer>* gbp,
3724 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003725 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003726 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003727 case PIXEL_FORMAT_TRANSPARENT:
3728 case PIXEL_FORMAT_TRANSLUCENT:
3729 format = PIXEL_FORMAT_RGBA_8888;
3730 break;
3731 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003732 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003733 break;
3734 }
3735
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003736 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003737 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003738 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003739 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003740 *handle = layer->getHandle();
3741 *gbp = layer->getProducer();
3742 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003743 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003744
Marissa Wallfd668622018-05-10 10:21:13 -07003745 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003746 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003747}
3748
Marissa Wall61c58622018-07-18 10:12:20 -07003749status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3750 uint32_t w, uint32_t h, uint32_t flags,
3751 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003752 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003753 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003754 *handle = layer->getHandle();
3755 *outLayer = layer;
3756
3757 return NO_ERROR;
3758}
3759
chaviw13fdc492017-06-27 12:40:18 -07003760status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003761 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003762 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003763{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003764 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003765 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003766 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003767}
3768
Robert Carr6b3f6c52018-08-13 13:05:17 -07003769status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3770 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3771 sp<IBinder>* handle, sp<Layer>* outLayer)
3772{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003773 *outLayer =
3774 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003775 *handle = (*outLayer)->getHandle();
3776 return NO_ERROR;
3777}
3778
3779
Mathias Agopianac9fa422013-02-11 16:40:36 -08003780status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003781{
Robert Carr9524cb32017-02-13 11:32:32 -08003782 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003783 status_t err = NO_ERROR;
3784 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003785 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003786 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003787 err = removeLayer(l);
3788 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3789 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003790 }
3791 return err;
3792}
3793
Robert Carr2e102c92018-10-23 12:11:15 -07003794void SurfaceFlinger::markLayerPendingRemovalLocked(const Mutex&, const sp<Layer>& layer) {
3795 mLayersPendingRemoval.add(layer);
3796 mLayersRemoved = true;
3797 setTransactionFlags(eTransactionNeeded);
3798}
3799
3800void SurfaceFlinger::onHandleDestroyed(const sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003801{
Robert Carr2e102c92018-10-23 12:11:15 -07003802 Mutex::Autolock lock(mStateLock);
3803 markLayerPendingRemovalLocked(mStateLock, layer);
Rob Carr4bba3702018-10-08 21:53:30 +00003804}
3805
Mathias Agopianb60314a2012-04-10 22:09:54 -07003806// ---------------------------------------------------------------------------
3807
Andy McFadden13a082e2012-08-24 10:16:42 -07003808void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003809 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3810 if (!displayToken) return;
3811
Jesse Hall01e29052013-02-19 16:13:35 -08003812 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003813 Vector<ComposerState> state;
3814 Vector<DisplayState> displays;
3815 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003816 d.what = DisplayState::eDisplayProjectionChanged |
3817 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003818 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003819 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003820 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003821 d.frame.makeInvalid();
3822 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003823 d.width = 0;
3824 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003825 displays.add(d);
3826 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003827
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003828 const auto display = getDisplayDevice(displayToken);
3829 if (!display) return;
3830
3831 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3832
3833 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003834 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003835 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003836
Brian Andersond0010582017-03-07 13:20:31 -08003837 // Use phase of 0 since phase is not known.
3838 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07003839 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
3840 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003841}
3842
3843void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003844 // Async since we may be called from the main thread.
3845 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003846}
3847
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003848void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3849 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003850 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003851 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003852
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003853 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003854 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003855 return;
3856 }
3857
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003858 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003859 ALOGW("Trying to set power mode for virtual display");
3860 return;
3861 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003862
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003863 display->setPowerMode(mode);
3864
Lloyd Pique4dccc412018-01-22 17:21:36 -08003865 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003866 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003867 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003868 if (idx < 0) {
3869 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3870 return;
3871 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003872 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003873 }
3874
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003875 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003876 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003877 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003878 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003879 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003880 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003881 if (mUseScheduler) {
3882 mScheduler->onScreenAcquired(mAppConnectionHandle);
3883 } else {
3884 mEventThread->onScreenAcquired();
3885 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07003886 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003887 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003888
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003889 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003890 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003891 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003892
3893 struct sched_param param = {0};
3894 param.sched_priority = 1;
3895 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3896 ALOGW("Couldn't set SCHED_FIFO on display on");
3897 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003898 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003899 // Turn off the display
3900 struct sched_param param = {0};
3901 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3902 ALOGW("Couldn't set SCHED_OTHER on display off");
3903 }
3904
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003905 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07003906 if (mUseScheduler) {
3907 mScheduler->disableHardwareVsync(true);
3908 } else {
3909 disableHardwareVsync(true); // also cancels any in-progress resync
3910 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07003911 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003912 if (mUseScheduler) {
3913 mScheduler->onScreenReleased(mAppConnectionHandle);
3914 } else {
3915 mEventThread->onScreenReleased();
3916 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07003917 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003918
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003919 getHwComposer().setPowerMode(type, mode);
3920 mVisibleRegionsDirty = true;
3921 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003922 } else if (mode == HWC_POWER_MODE_DOZE ||
3923 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003924 // Update display while dozing
3925 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003926 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003927 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003928 if (mUseScheduler) {
3929 mScheduler->onScreenAcquired(mAppConnectionHandle);
3930 } else {
3931 mEventThread->onScreenAcquired();
3932 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003933 resyncToHardwareVsync(true);
3934 }
3935 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3936 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003937 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07003938 if (mUseScheduler) {
3939 mScheduler->disableHardwareVsync(true);
3940 } else {
3941 disableHardwareVsync(true); // also cancels any in-progress resync
3942 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003943 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003944 if (mUseScheduler) {
3945 mScheduler->onScreenReleased(mAppConnectionHandle);
3946 } else {
3947 mEventThread->onScreenReleased();
3948 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003949 }
3950 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003951 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003952 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003953 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003954 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003955
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003956 if (display->isPrimary()) {
3957 mTimeStats.setPowerMode(mode);
3958 }
3959
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003960 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003961}
3962
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003963void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003964 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003965 const auto display = getDisplayDevice(displayToken);
3966 if (!display) {
3967 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3968 displayToken.get());
3969 } else if (display->isVirtual()) {
3970 ALOGW("Attempt to set power mode %d for virtual display", mode);
3971 } else {
3972 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003973 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003974 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003975}
3976
3977// ---------------------------------------------------------------------------
3978
Lloyd Pique755e3192018-01-31 16:46:15 -08003979status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3980 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003981 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003982
Mathias Agopianbd115332013-04-18 16:41:04 -07003983 IPCThreadState* ipc = IPCThreadState::self();
3984 const int pid = ipc->getCallingPid();
3985 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003986
Mathias Agopianbd115332013-04-18 16:41:04 -07003987 if ((uid != AID_SHELL) &&
3988 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003989 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003990 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003991 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003992 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003993 // (this would indicate SF is stuck, but we want to be able to
3994 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003995 status_t err = mStateLock.timedLock(s2ns(1));
3996 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003997 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003998 result.appendFormat(
3999 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4000 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004001 }
4002
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004003 bool dumpAll = true;
4004 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004005 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004006
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004007 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004008 if ((index < numArgs) &&
4009 (args[index] == String16("--list"))) {
4010 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004011 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004012 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004013 }
4014
4015 if ((index < numArgs) &&
4016 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004017 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004018 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004019 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004020 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004021
4022 if ((index < numArgs) &&
4023 (args[index] == String16("--latency-clear"))) {
4024 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004025 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004026 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004027 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004028
4029 if ((index < numArgs) &&
4030 (args[index] == String16("--dispsync"))) {
4031 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004032 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004033 dumpAll = false;
4034 }
Dan Stozab90cf072015-03-05 11:05:59 -08004035
4036 if ((index < numArgs) &&
4037 (args[index] == String16("--static-screen"))) {
4038 index++;
4039 dumpStaticScreenStats(result);
4040 dumpAll = false;
4041 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004042
4043 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004044 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004045 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004046 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004047 dumpAll = false;
4048 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004049
4050 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4051 index++;
4052 dumpWideColorInfo(result);
4053 dumpAll = false;
4054 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004055
4056 if ((index < numArgs) &&
4057 (args[index] == String16("--enable-layer-stats"))) {
4058 index++;
4059 mLayerStats.enable();
4060 dumpAll = false;
4061 }
4062
4063 if ((index < numArgs) &&
4064 (args[index] == String16("--disable-layer-stats"))) {
4065 index++;
4066 mLayerStats.disable();
4067 dumpAll = false;
4068 }
4069
4070 if ((index < numArgs) &&
4071 (args[index] == String16("--clear-layer-stats"))) {
4072 index++;
4073 mLayerStats.clear();
4074 dumpAll = false;
4075 }
4076
4077 if ((index < numArgs) &&
4078 (args[index] == String16("--dump-layer-stats"))) {
4079 index++;
4080 mLayerStats.dump(result);
4081 dumpAll = false;
4082 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004083
4084 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004085 (args[index] == String16("--frame-composition"))) {
4086 index++;
4087 dumpFrameCompositionInfo(result);
4088 dumpAll = false;
4089 }
4090
4091 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004092 (args[index] == String16("--display-identification"))) {
4093 index++;
4094 dumpDisplayIdentificationData(result);
4095 dumpAll = false;
4096 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004097
4098 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4099 index++;
4100 mTimeStats.parseArgs(asProto, args, index, result);
4101 dumpAll = false;
4102 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004103 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004104
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004105 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004106 if (asProto) {
4107 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4108 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4109 } else {
4110 dumpAllLocked(args, index, result);
4111 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004112 }
4113
Mathias Agopian9795c422009-08-26 16:36:26 -07004114 if (locked) {
4115 mStateLock.unlock();
4116 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004117 }
4118 write(fd, result.string(), result.size());
4119 return NO_ERROR;
4120}
4121
Dan Stozac7014012014-02-14 15:03:43 -08004122void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4123 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004124{
Robert Carr2047fae2016-11-28 14:09:09 -08004125 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004126 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004127 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004128}
4129
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004130void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004131 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004132{
4133 String8 name;
4134 if (index < args.size()) {
4135 name = String8(args[index]);
4136 index++;
4137 }
4138
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004139 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4140 getHwComposer().isConnected(displayId)) {
4141 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4142 const nsecs_t period = activeConfig->getVsyncPeriod();
4143 result.appendFormat("%" PRId64 "\n", period);
4144 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004145
4146 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004147 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004148 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004149 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004150 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004151 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004152 }
Robert Carr2047fae2016-11-28 14:09:09 -08004153 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004154 }
4155}
4156
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004157void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004158 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004159{
4160 String8 name;
4161 if (index < args.size()) {
4162 name = String8(args[index]);
4163 index++;
4164 }
4165
Robert Carr2047fae2016-11-28 14:09:09 -08004166 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004167 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004168 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004169 }
Robert Carr2047fae2016-11-28 14:09:09 -08004170 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004171
Svetoslavd85084b2014-03-20 10:28:31 -07004172 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004173}
4174
Jamie Gennis6547ff42013-07-16 20:12:42 -07004175// This should only be called from the main thread. Otherwise it would need
4176// the lock and should use mCurrentState rather than mDrawingState.
4177void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004178 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004179 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004180 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004181
4182 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4183}
4184
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004185void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004186{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004187 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004188
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004189 if (isLayerTripleBufferingDisabled())
4190 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004191
4192 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004193 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004194 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004195 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004196 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4197 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004198 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004199}
4200
Dan Stozab90cf072015-03-05 11:05:59 -08004201void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4202{
4203 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004204 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4205 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004206 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004207 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004208 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4209 b + 1, bucketTimeSec, percent);
4210 }
David Sodman4a36e932017-11-07 14:29:47 -08004211 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004212 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004213 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004214 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004215 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004216}
4217
Dan Stozae77c7662016-05-13 11:37:28 -07004218void SurfaceFlinger::recordBufferingStats(const char* layerName,
4219 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004220 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4221 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004222 for (const auto& segment : history) {
4223 if (!segment.usedThirdBuffer) {
4224 stats.twoBufferTime += segment.totalTime;
4225 }
4226 if (segment.occupancyAverage < 1.0f) {
4227 stats.doubleBufferedTime += segment.totalTime;
4228 } else if (segment.occupancyAverage < 2.0f) {
4229 stats.tripleBufferedTime += segment.totalTime;
4230 }
4231 ++stats.numSegments;
4232 stats.totalTime += segment.totalTime;
4233 }
4234}
4235
Brian Andersond6927fb2016-07-23 23:37:30 -07004236void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4237 result.appendFormat("Layer frame timestamps:\n");
4238
4239 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4240 const size_t count = currentLayers.size();
4241 for (size_t i=0 ; i<count ; i++) {
4242 currentLayers[i]->dumpFrameEvents(result);
4243 }
4244}
4245
Dan Stozae77c7662016-05-13 11:37:28 -07004246void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4247 result.append("Buffering stats:\n");
4248 result.append(" [Layer name] <Active time> <Two buffer> "
4249 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004250 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004251 typedef std::tuple<std::string, float, float, float> BufferTuple;
4252 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004253 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004254 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004255 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004256 if (stats.numSegments == 0) {
4257 continue;
4258 }
4259 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4260 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4261 stats.totalTime;
4262 float doubleBufferRatio = static_cast<float>(
4263 stats.doubleBufferedTime) / stats.totalTime;
4264 float tripleBufferRatio = static_cast<float>(
4265 stats.tripleBufferedTime) / stats.totalTime;
4266 sorted.insert({activeTime, {name, twoBufferRatio,
4267 doubleBufferRatio, tripleBufferRatio}});
4268 }
4269 for (const auto& sortedPair : sorted) {
4270 float activeTime = sortedPair.first;
4271 const BufferTuple& values = sortedPair.second;
4272 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4273 std::get<0>(values).c_str(), activeTime,
4274 std::get<1>(values), std::get<2>(values),
4275 std::get<3>(values));
4276 }
4277 result.append("\n");
4278}
4279
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004280void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004281 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004282 const int32_t displayId = display->getId();
4283 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4284 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004285 continue;
4286 }
4287
Dominik Laskowski7e045462018-05-30 13:02:02 -07004288 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004289 uint8_t port;
4290 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004291 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004292 result.append("no identification data\n");
4293 continue;
4294 }
4295
4296 if (!isEdid(data)) {
4297 result.append("unknown identification data: ");
4298 for (uint8_t byte : data) {
4299 result.appendFormat("%x ", byte);
4300 }
4301 result.append("\n");
4302 continue;
4303 }
4304
4305 const auto edid = parseEdid(data);
4306 if (!edid) {
4307 result.append("invalid EDID: ");
4308 for (uint8_t byte : data) {
4309 result.appendFormat("%x ", byte);
4310 }
4311 result.append("\n");
4312 continue;
4313 }
4314
4315 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4316 result.append(edid->displayName.data(), edid->displayName.length());
4317 result.append("\"\n");
4318 }
4319 result.append("\n");
4320}
4321
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004322void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004323 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4324 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004325 result.appendFormat("DisplayColorSetting: %s\n",
4326 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004327
4328 // TODO: print out if wide-color mode is active or not
4329
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004330 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004331 const int32_t displayId = display->getId();
4332 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004333 continue;
4334 }
4335
Dominik Laskowski7e045462018-05-30 13:02:02 -07004336 result.appendFormat("Display %d color modes:\n", displayId);
4337 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004338 for (auto&& mode : modes) {
4339 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4340 }
4341
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004342 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004343 result.appendFormat(" Current color mode: %s (%d)\n",
4344 decodeColorMode(currentMode).c_str(), currentMode);
4345 }
4346 result.append("\n");
4347}
4348
David Sodman7e4ae112018-02-09 15:02:28 -08004349void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4350 std::string stringResult;
4351
4352 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004353 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4354 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004355 continue;
4356 }
4357
Dominik Laskowski05275f12018-11-01 15:03:24 -07004358 const auto& compositionInfoList = it->second;
4359 stringResult += base::StringPrintf("%s\n", display->getDebugName().c_str());
David Sodman7e4ae112018-02-09 15:02:28 -08004360 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4361 for (const auto& compositionInfo : compositionInfoList) {
4362 compositionInfo.dump(stringResult, nullptr);
4363 stringResult += base::StringPrintf("\n");
4364 }
4365 }
4366
4367 result.append(stringResult.c_str());
4368}
4369
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004370LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004371 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004372 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4373 const State& state = useDrawing ? mDrawingState : mCurrentState;
4374 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004375 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004376 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004377 });
4378
4379 return layersProto;
4380}
4381
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004382LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004383 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004384
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004385 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004386 resolution->set_w(display.getWidth());
4387 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004388
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004389 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4390 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4391 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004392
Dominik Laskowski7e045462018-05-30 13:02:02 -07004393 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004394 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004395 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004396 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004397 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004398 }
4399 });
4400
4401 return layersProto;
4402}
4403
Mathias Agopian74d211a2013-04-22 16:55:35 +02004404void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4405 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004406{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004407 bool colorize = false;
4408 if (index < args.size()
4409 && (args[index] == String16("--color"))) {
4410 colorize = true;
4411 index++;
4412 }
4413
4414 Colorizer colorizer(colorize);
4415
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004416 // figure out if we're stuck somewhere
4417 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004418 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004419 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4420
4421 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004422 * Dump library configuration.
4423 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004424
4425 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004426 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004427 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004428 appendSfConfigString(result);
4429 appendUiConfigString(result);
4430 appendGuiConfigString(result);
4431 result.append("\n");
4432
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004433 result.append("\nDisplay identification data:\n");
4434 dumpDisplayIdentificationData(result);
4435
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004436 result.append("\nWide-Color information:\n");
4437 dumpWideColorInfo(result);
4438
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004439 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004440 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004441 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004442 result.append(SyncFeatures::getInstance().toString());
4443 result.append("\n");
4444
Andy McFadden41d67d72014-04-25 16:58:34 -07004445 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004446 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004447 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004448
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004449 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4450 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004451 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4452 getHwComposer().isConnected(displayId)) {
4453 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004454 result.appendFormat("Display %d: "
4455 "app phase %" PRId64 " ns, "
4456 "sf phase %" PRId64 " ns, "
4457 "early app phase %" PRId64 " ns, "
4458 "early sf phase %" PRId64 " ns, "
4459 "early app gl phase %" PRId64 " ns, "
4460 "early sf gl phase %" PRId64 " ns, "
4461 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4462 displayId,
4463 vsyncPhaseOffsetNs,
4464 sfVsyncPhaseOffsetNs,
4465 appEarlyOffset,
4466 sfEarlyOffset,
4467 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004468 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004469 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004470 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004471 result.append("\n");
4472
Dan Stozab90cf072015-03-05 11:05:59 -08004473 // Dump static screen stats
4474 result.append("\n");
4475 dumpStaticScreenStats(result);
4476 result.append("\n");
4477
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004478 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4479
Dan Stozae77c7662016-05-13 11:37:28 -07004480 dumpBufferingStats(result);
4481
Andy McFadden4803b742012-09-24 19:07:20 -07004482 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004483 * Dump the visible layer list
4484 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004485 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004486 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004487 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4488 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004489 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004490
Chia-I Wu2f884132018-09-13 15:17:58 -07004491 {
4492 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4493 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4494 result.append(LayerProtoParser::layerTreeToString(layerTree).c_str());
4495 result.append("\n");
4496 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004497
David Sodman7e4ae112018-02-09 15:02:28 -08004498 result.append("\nFrame-Composition information:\n");
4499 dumpFrameCompositionInfo(result);
4500 result.append("\n");
4501
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004502 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004503 * Dump Display state
4504 */
4505
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004506 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004507 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004508 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004509 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004510 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004511 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004512 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004513
4514 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004515 * Dump SurfaceFlinger global state
4516 */
4517
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004518 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004519 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004520 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004521
Mathias Agopian888c8222012-08-04 21:10:38 -07004522 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004523 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004524
David Sodmanbc815282017-11-05 18:57:52 -08004525 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004526
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004527 if (display) {
4528 display->undefinedRegion.dump(result, "undefinedRegion");
4529 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4530 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004531 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004532 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004533 " gpu_to_cpu_unsupported : %d\n",
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004534 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004535
4536 if (display) {
4537 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4538 result.appendFormat(" refresh-rate : %f fps\n"
4539 " x-dpi : %f\n"
4540 " y-dpi : %f\n",
4541 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4542 activeConfig->getDpiY());
4543 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004544
Mathias Agopian74d211a2013-04-22 16:55:35 +02004545 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004546 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004547
Ana Krulec98b5b242018-08-10 15:03:23 -07004548 result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004549 /*
4550 * VSYNC state
4551 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004552 if (mUseScheduler) {
4553 mScheduler->dump(mAppConnectionHandle, result);
4554 } else {
4555 mEventThread->dump(result);
4556 }
Dan Stozae22aec72016-08-01 13:20:59 -07004557 result.append("\n");
4558
4559 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004560 * Tracing state
4561 */
4562 mTracing.dump(result);
4563 result.append("\n");
4564
4565 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004566 * HWC layer minidump
4567 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004568 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004569 const int32_t displayId = display->getId();
4570 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004571 continue;
4572 }
4573
Dominik Laskowski7e045462018-05-30 13:02:02 -07004574 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004575 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004576 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004577 result.append("\n");
4578 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004579
4580 /*
4581 * Dump HWComposer state
4582 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004583 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004584 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004585 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004586 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004587 result.appendFormat(" h/w composer %s\n",
4588 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004589 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004590
4591 /*
4592 * Dump gralloc state
4593 */
4594 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4595 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004596
4597 /*
4598 * Dump VrFlinger state if in use.
4599 */
4600 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4601 result.append("VrFlinger state:\n");
4602 result.append(mVrFlinger->Dump().c_str());
4603 result.append("\n");
4604 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004605}
4606
Dominik Laskowski7e045462018-05-30 13:02:02 -07004607const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004608 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004609 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004610 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004611 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004612 }
4613 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004614
4615 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4616 static const Vector<sp<Layer>> empty;
4617 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004618}
4619
Keun young Park63f165f2012-08-31 10:53:36 -07004620bool SurfaceFlinger::startDdmConnection()
4621{
4622 void* libddmconnection_dso =
4623 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4624 if (!libddmconnection_dso) {
4625 return false;
4626 }
4627 void (*DdmConnection_start)(const char* name);
4628 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004629 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004630 if (!DdmConnection_start) {
4631 dlclose(libddmconnection_dso);
4632 return false;
4633 }
4634 (*DdmConnection_start)(getServiceName());
4635 return true;
4636}
4637
Chia-I Wu28f320b2018-05-03 11:02:56 -07004638void SurfaceFlinger::updateColorMatrixLocked() {
4639 mat4 colorMatrix;
4640 if (mGlobalSaturationFactor != 1.0f) {
4641 // Rec.709 luma coefficients
4642 float3 luminance{0.213f, 0.715f, 0.072f};
4643 luminance *= 1.0f - mGlobalSaturationFactor;
4644 mat4 saturationMatrix = mat4(
4645 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4646 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4647 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4648 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4649 );
4650 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4651 } else {
4652 colorMatrix = mClientColorMatrix * mDaltonizer();
4653 }
4654
4655 if (mCurrentState.colorMatrix != colorMatrix) {
4656 mCurrentState.colorMatrix = colorMatrix;
4657 mCurrentState.colorMatrixChanged = true;
4658 setTransactionFlags(eTransactionNeeded);
4659 }
4660}
4661
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004662status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004663#pragma clang diagnostic push
4664#pragma clang diagnostic error "-Wswitch-enum"
4665 switch (static_cast<ISurfaceComposerTag>(code)) {
4666 // These methods should at minimum make sure that the client requested
4667 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004668 case BOOT_FINISHED:
4669 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004670 case CREATE_CONNECTION:
4671 case CREATE_DISPLAY:
4672 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004673 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004674 case GET_ACTIVE_COLOR_MODE:
4675 case GET_ANIMATION_FRAME_STATS:
4676 case GET_HDR_CAPABILITIES:
4677 case SET_ACTIVE_CONFIG:
4678 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004679 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004680 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004681 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4682 IPCThreadState* ipc = IPCThreadState::self();
4683 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4684 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004685 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004686 }
Robert Carr1db73f62016-12-21 12:58:51 -08004687 return OK;
4688 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004689 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004690 IPCThreadState* ipc = IPCThreadState::self();
4691 const int pid = ipc->getCallingPid();
4692 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004693 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4694 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004695 return PERMISSION_DENIED;
4696 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004697 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004698 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004699 // Used by apps to hook Choreographer to SurfaceFlinger.
4700 case CREATE_DISPLAY_EVENT_CONNECTION:
4701 // The following calls are currently used by clients that do not
4702 // request necessary permissions. However, they do not expose any secret
4703 // information, so it is OK to pass them.
4704 case AUTHENTICATE_SURFACE:
4705 case GET_ACTIVE_CONFIG:
4706 case GET_BUILT_IN_DISPLAY:
4707 case GET_DISPLAY_COLOR_MODES:
4708 case GET_DISPLAY_CONFIGS:
4709 case GET_DISPLAY_STATS:
4710 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4711 // Calling setTransactionState is safe, because you need to have been
4712 // granted a reference to Client* and Handle* to do anything with it.
4713 case SET_TRANSACTION_STATE:
4714 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004715 case CREATE_SCOPED_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004716 case GET_COLOR_MANAGEMENT:
Peiyong Lin0256f722018-08-31 15:45:10 -07004717 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004718 return OK;
4719 }
4720 case CAPTURE_LAYERS:
4721 case CAPTURE_SCREEN: {
4722 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004723 IPCThreadState* ipc = IPCThreadState::self();
4724 const int pid = ipc->getCallingPid();
4725 const int uid = ipc->getCallingUid();
4726 if ((uid != AID_GRAPHICS) &&
4727 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4728 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4729 return PERMISSION_DENIED;
4730 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004731 return OK;
4732 }
4733 // The following codes are deprecated and should never be allowed to access SF.
4734 case CONNECT_DISPLAY_UNUSED:
4735 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4736 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4737 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004738 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004739 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004740
4741 // These codes are used for the IBinder protocol to either interrogate the recipient
4742 // side of the transaction for its canonical interface descriptor or to dump its state.
4743 // We let them pass by default.
4744 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4745 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4746 code == IBinder::SYSPROPS_TRANSACTION) {
4747 return OK;
4748 }
Peiyong Lin3b44a032018-10-24 18:18:12 -07004749 // Numbers from 1000 to 1030 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004750 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin3b44a032018-10-24 18:18:12 -07004751 if (code >= 1000 && code <= 1030) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004752 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4753 return OK;
4754 }
4755 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4756 return PERMISSION_DENIED;
4757#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004758}
4759
Ana Krulec13be8ad2018-08-21 02:43:56 +00004760status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4761 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004762 status_t credentialCheck = CheckTransactCodeCredentials(code);
4763 if (credentialCheck != OK) {
4764 return credentialCheck;
4765 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004766
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004767 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4768 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004769 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004770 IPCThreadState* ipc = IPCThreadState::self();
4771 const int uid = ipc->getCallingUid();
4772 if (CC_UNLIKELY(uid != AID_SYSTEM
4773 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004774 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004775 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004776 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004777 return PERMISSION_DENIED;
4778 }
4779 int n;
4780 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004781 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004782 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004783 return NO_ERROR;
4784 case 1002: // SHOW_UPDATES
4785 n = data.readInt32();
4786 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004787 invalidateHwcGeometry();
4788 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004789 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004790 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004791 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004792 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004793 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004794 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004795 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004796 setTransactionFlags(
4797 eTransactionNeeded|
4798 eDisplayTransactionNeeded|
4799 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004800 return NO_ERROR;
4801 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004802 case 1006:{ // send empty update
4803 signalRefresh();
4804 return NO_ERROR;
4805 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004806 case 1008: // toggle use of hw composer
4807 n = data.readInt32();
4808 mDebugDisableHWC = n ? 1 : 0;
4809 invalidateHwcGeometry();
4810 repaintEverything();
4811 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004812 case 1009: // toggle use of transform hint
4813 n = data.readInt32();
4814 mDebugDisableTransformHint = n ? 1 : 0;
4815 invalidateHwcGeometry();
4816 repaintEverything();
4817 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004818 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004819 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004820 reply->writeInt32(0);
4821 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004822 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004823 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004824 return NO_ERROR;
4825 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004826 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004827 if (!display) {
4828 return NAME_NOT_FOUND;
4829 }
4830
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004831 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004832 return NO_ERROR;
4833 }
4834 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004835 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004836 // daltonize
4837 n = data.readInt32();
4838 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004839 case 1:
4840 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4841 break;
4842 case 2:
4843 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4844 break;
4845 case 3:
4846 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4847 break;
4848 default:
4849 mDaltonizer.setType(ColorBlindnessType::None);
4850 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004851 }
4852 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004853 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004854 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004855 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004856 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004857
4858 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004859 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004860 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004861 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004862 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004863 // apply a color matrix
4864 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004865 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004866 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004867 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004868 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004869 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004870 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004871 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004872 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004873 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004874 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004875
4876 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4877 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004878 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004879 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4880 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4881 }
4882
Chia-I Wu28f320b2018-05-03 11:02:56 -07004883 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004884 return NO_ERROR;
4885 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004886 // This is an experimental interface
4887 // Needs to be shifted to proper binder interface when we productize
4888 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004889 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07004890 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07004891 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004892 return NO_ERROR;
4893 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004894 case 1017: {
4895 n = data.readInt32();
4896 mForceFullDamage = static_cast<bool>(n);
4897 return NO_ERROR;
4898 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004899 case 1018: { // Modify Choreographer's phase offset
4900 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004901 if (mUseScheduler) {
4902 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
4903 } else {
4904 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4905 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004906 return NO_ERROR;
4907 }
4908 case 1019: { // Modify SurfaceFlinger's phase offset
4909 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004910 if (mUseScheduler) {
4911 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
4912 } else {
4913 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4914 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004915 return NO_ERROR;
4916 }
Irvel468051e2016-06-13 16:44:44 -07004917 case 1020: { // Layer updates interceptor
4918 n = data.readInt32();
4919 if (n) {
4920 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004921 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004922 }
4923 else{
4924 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004925 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004926 }
4927 return NO_ERROR;
4928 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004929 case 1021: { // Disable HWC virtual displays
4930 n = data.readInt32();
4931 mUseHwcVirtualDisplays = !n;
4932 return NO_ERROR;
4933 }
Romain Guy0147a172017-06-01 13:53:56 -07004934 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004935 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004936 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004937
Chia-I Wu28f320b2018-05-03 11:02:56 -07004938 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004939 return NO_ERROR;
4940 }
Romain Guy54f154a2017-10-24 21:40:32 +01004941 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004942 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004943 invalidateHwcGeometry();
4944 repaintEverything();
4945 return NO_ERROR;
4946 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004947 // Deprecate, use 1030 to check whether the device is color managed.
4948 case 1024: {
4949 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004950 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004951 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004952 n = data.readInt32();
4953 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004954 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004955 mTracing.enable();
4956 doTracing("tracing.enable");
4957 reply->writeInt32(NO_ERROR);
4958 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004959 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004960 status_t err = mTracing.disable();
4961 reply->writeInt32(err);
4962 }
4963 return NO_ERROR;
4964 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004965 case 1026: { // Get layer tracing status
4966 reply->writeBool(mTracing.isEnabled());
4967 return NO_ERROR;
4968 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004969 // Is a DisplayColorSetting supported?
4970 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004971 const auto display = getDefaultDisplayDevice();
4972 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004973 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004974 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004975
4976 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4977 switch (setting) {
4978 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07004979 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004980 break;
4981 case DisplayColorSetting::UNMANAGED:
4982 reply->writeBool(true);
4983 break;
4984 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004985 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004986 break;
4987 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004988 reply->writeBool(
4989 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004990 break;
4991 }
4992 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004993 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004994 // Is VrFlinger active?
4995 case 1028: {
4996 Mutex::Autolock _l(mStateLock);
4997 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4998 return NO_ERROR;
4999 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005000 // Is device color managed?
5001 case 1030: {
5002 reply->writeBool(useColorManagement);
5003 return NO_ERROR;
5004 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005005 }
5006 }
5007 return err;
5008}
5009
Steven Thomas6d8110b2017-08-31 18:24:21 -07005010void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005011 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005012 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005013}
5014
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005015// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5016class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005017public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005018 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5019 ~WindowDisconnector() {
5020 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005021 }
5022
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005023private:
5024 ANativeWindow* mWindow;
5025 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005026};
5027
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005028status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005029 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5030 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005031 uint32_t reqWidth, uint32_t reqHeight,
5032 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005033 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005034 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005035
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005036 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005037
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005038 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5039
Chia-I Wu20261cb2018-08-23 12:55:44 -07005040 sp<DisplayDevice> display;
5041 {
5042 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005043
Chia-I Wu20261cb2018-08-23 12:55:44 -07005044 display = getDisplayDeviceLocked(displayToken);
5045 if (!display) return BAD_VALUE;
5046
Chia-I Wucb023152018-08-28 12:57:23 -07005047 // set the requested width/height to the logical display viewport size
5048 // by default
5049 if (reqWidth == 0 || reqHeight == 0) {
5050 reqWidth = uint32_t(display->getViewport().width());
5051 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005052 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005053 }
5054
Peiyong Lin0e003c92018-09-17 11:09:51 -07005055 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5056 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005057
5058 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005059 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005060 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5061 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005062}
5063
5064status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005065 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5066 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005067 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005068 ATRACE_CALL();
5069
5070 class LayerRenderArea : public RenderArea {
5071 public:
Robert Carr578038f2018-03-09 12:25:24 -08005072 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005073 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5074 bool childrenOnly)
5075 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005076 mLayer(layer),
5077 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005078 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005079 mFlinger(flinger),
5080 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005081 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005082 Rect getBounds() const override {
5083 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005084 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005085 }
Marissa Wall61c58622018-07-18 10:12:20 -07005086 int getHeight() const override {
5087 return mLayer->getActiveHeight(mLayer->getDrawingState());
5088 }
5089 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005090 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005091 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005092 Rect getSourceCrop() const override {
5093 if (mCrop.isEmpty()) {
5094 return getBounds();
5095 } else {
5096 return mCrop;
5097 }
5098 }
Robert Carr578038f2018-03-09 12:25:24 -08005099 class ReparentForDrawing {
5100 public:
5101 const sp<Layer>& oldParent;
5102 const sp<Layer>& newParent;
5103
5104 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5105 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005106 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005107 }
Robert Carr15eae092018-03-23 13:43:53 -07005108 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005109 };
5110
5111 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005112 const Rect sourceCrop = getSourceCrop();
5113 // no need to check rotation because there is none
5114 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5115 sourceCrop.height() != getReqHeight();
5116
Robert Carr578038f2018-03-09 12:25:24 -08005117 if (!mChildrenOnly) {
5118 mTransform = mLayer->getTransform().inverse();
5119 drawLayers();
5120 } else {
5121 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005122 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005123 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5124 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005125
5126 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5127 drawLayers();
5128 }
5129 }
chaviwa76b2712017-09-20 12:02:26 -07005130
chaviwa76b2712017-09-20 12:02:26 -07005131 private:
chaviw7206d492017-11-10 16:16:12 -08005132 const sp<Layer> mLayer;
5133 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005134
5135 // In the "childrenOnly" case we reparent the children to a screenshot
5136 // layer which has no properties set and which does not draw.
5137 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005138 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005139 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005140
5141 SurfaceFlinger* mFlinger;
5142 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005143 };
5144
5145 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5146 auto parent = layerHandle->owner.promote();
5147
Robert Carr2e102c92018-10-23 12:11:15 -07005148 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005149 ALOGE("captureLayers called with a removed parent");
5150 return NAME_NOT_FOUND;
5151 }
5152
Robert Carr578038f2018-03-09 12:25:24 -08005153 const int uid = IPCThreadState::self()->getCallingUid();
5154 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5155 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5156 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5157 return PERMISSION_DENIED;
5158 }
5159
chaviw7206d492017-11-10 16:16:12 -08005160 Rect crop(sourceCrop);
5161 if (sourceCrop.width() <= 0) {
5162 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005163 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005164 }
5165
5166 if (sourceCrop.height() <= 0) {
5167 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005168 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005169 }
5170
5171 int32_t reqWidth = crop.width() * frameScale;
5172 int32_t reqHeight = crop.height() * frameScale;
5173
Chia-I Wu20261cb2018-08-23 12:55:44 -07005174 // really small crop or frameScale
5175 if (reqWidth <= 0) {
5176 reqWidth = 1;
5177 }
5178 if (reqHeight <= 0) {
5179 reqHeight = 1;
5180 }
5181
Peiyong Lin0e003c92018-09-17 11:09:51 -07005182 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005183
Robert Carr578038f2018-03-09 12:25:24 -08005184 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005185 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5186 if (!layer->isVisible()) {
5187 return;
Robert Carr578038f2018-03-09 12:25:24 -08005188 } else if (childrenOnly && layer == parent.get()) {
5189 return;
chaviwa76b2712017-09-20 12:02:26 -07005190 }
5191 visitor(layer);
5192 });
5193 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005194 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005195}
5196
5197status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5198 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005199 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005200 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005201 bool useIdentityTransform) {
5202 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005203
Peiyong Lin0e003c92018-09-17 11:09:51 -07005204 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005205 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5206 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005207 *outBuffer =
5208 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5209 static_cast<android_pixel_format>(reqPixelFormat), 1,
5210 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005211
5212 // This mutex protects syncFd and captureResult for communication of the return values from the
5213 // main thread back to this Binder thread
5214 std::mutex captureMutex;
5215 std::condition_variable captureCondition;
5216 std::unique_lock<std::mutex> captureLock(captureMutex);
5217 int syncFd = -1;
5218 std::optional<status_t> captureResult;
5219
Robert Carr03480e22018-01-04 16:02:06 -08005220 const int uid = IPCThreadState::self()->getCallingUid();
5221 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5222
Dominik Laskowski8c001672018-05-30 16:52:06 -07005223 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005224 // If there is a refresh pending, bug out early and tell the binder thread to try again
5225 // after the refresh.
5226 if (mRefreshPending) {
5227 ATRACE_NAME("Skipping screenshot for now");
5228 std::unique_lock<std::mutex> captureLock(captureMutex);
5229 captureResult = std::make_optional<status_t>(EAGAIN);
5230 captureCondition.notify_one();
5231 return;
5232 }
5233
5234 status_t result = NO_ERROR;
5235 int fd = -1;
5236 {
5237 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005238 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005239 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5240 useIdentityTransform, forSystem, &fd);
5241 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005242 }
5243
5244 {
5245 std::unique_lock<std::mutex> captureLock(captureMutex);
5246 syncFd = fd;
5247 captureResult = std::make_optional<status_t>(result);
5248 captureCondition.notify_one();
5249 }
5250 });
5251
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005252 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005253 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005254 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005255 while (*captureResult == EAGAIN) {
5256 captureResult.reset();
5257 result = postMessageAsync(message);
5258 if (result != NO_ERROR) {
5259 return result;
5260 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005261 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005262 }
5263 result = *captureResult;
5264 }
5265
5266 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005267 sync_wait(syncFd, -1);
5268 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005269 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005270
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005271 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005272}
5273
chaviwa76b2712017-09-20 12:02:26 -07005274void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005275 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005276 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005277 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005278
Lloyd Pique144e1162017-12-20 16:44:52 -08005279 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005280
chaviwa76b2712017-09-20 12:02:26 -07005281 const auto reqWidth = renderArea.getReqWidth();
5282 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005283 const auto sourceCrop = renderArea.getSourceCrop();
5284 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005285
Peiyong Lin0e003c92018-09-17 11:09:51 -07005286 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005287 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005288
Mathias Agopian180f10d2013-04-10 22:55:41 -07005289 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005290 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005291
5292 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005293 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005294 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005295
chaviw50da5042018-04-09 13:49:37 -07005296 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005297 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005298 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005299
chaviwa76b2712017-09-20 12:02:26 -07005300 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005301 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005302 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005303 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005304 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005305}
5306
chaviwa76b2712017-09-20 12:02:26 -07005307status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5308 TraverseLayersFunction traverseLayers,
5309 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005310 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005311 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005312 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005313 ATRACE_CALL();
5314
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005315 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005316
5317 traverseLayers([&](Layer* layer) {
5318 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5319 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005320
Robert Carr03480e22018-01-04 16:02:06 -08005321 // We allow the system server to take screenshots of secure layers for
5322 // use in situations like the Screen-rotation animation and place
5323 // the impetus on WindowManager to not persist them.
5324 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005325 ALOGW("FB is protected: PERMISSION_DENIED");
5326 return PERMISSION_DENIED;
5327 }
5328
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005329 // this binds the given EGLImage as a framebuffer for the
5330 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005331 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005332 if (bufferBond.getStatus() != NO_ERROR) {
5333 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005334 return INVALID_OPERATION;
5335 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005336
Dan Stozaabcda352017-06-01 14:37:39 -07005337 // this will in fact render into our dequeued buffer
5338 // via an FBO, which means we didn't have to create
5339 // an EGLSurface and therefore we're not
5340 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005341 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005342
Alec Mouri492bc572018-09-11 21:40:04 +00005343 base::unique_fd syncFd = getRenderEngine().flush();
5344 if (syncFd < 0) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005345 getRenderEngine().finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005346 }
Alec Mouri492bc572018-09-11 21:40:04 +00005347 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005348
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005349 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005350}
5351
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005352// ---------------------------------------------------------------------------
5353
Dan Stoza412903f2017-04-27 13:42:17 -07005354void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5355 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005356}
5357
Dan Stoza412903f2017-04-27 13:42:17 -07005358void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5359 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005360}
5361
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005362void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005363 const LayerVector::Visitor& visitor) {
5364 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005365 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005366 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005367 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005368 continue;
5369 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005370 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005371 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005372 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005373 return;
5374 }
chaviwa76b2712017-09-20 12:02:26 -07005375 if (!layer->isVisible()) {
5376 return;
5377 }
5378 visitor(layer);
5379 });
5380 }
5381}
5382
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005383}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005384
Lloyd Pique074e8122018-07-26 12:57:23 -07005385
Mathias Agopian3f844832013-08-07 21:24:32 -07005386#if defined(__gl_h_)
5387#error "don't include gl/gl.h in this file"
5388#endif
5389
5390#if defined(__gl2_h_)
5391#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005392#endif