blob: 7871971554e8f1bfb9652e529e0fe90e0f3dc8bd [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Chia-I Wud49d6692018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070050#include <renderengine/RenderEngine.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070051#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070066#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070067#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020070#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080072#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080073#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070077#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070078#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070080#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081
Steven Thomasb02664d2017-07-26 18:48:28 -070082#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070083#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070084#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070085#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070086#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070087#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070088#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070089#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070090#include "Scheduler/EventControlThread.h"
91#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070092#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070093#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070094#include "Scheduler/Scheduler.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070095
Mathias Agopianff2ed702013-09-01 21:36:12 -070096#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070097
David Sodman7e4ae112018-02-09 15:02:28 -080098#include "android-base/stringprintf.h"
99
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900100#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800101#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700102#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800103#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900104#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900105
chaviw1d044282017-09-27 12:19:28 -0700106#include <layerproto/LayerProtoParser.h>
107
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800108#define DISPLAY_COUNT 1
109
110namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700111
Jaesoo Lee43518572017-01-23 19:03:16 +0900112using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900113using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700114using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700115using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700116using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700117using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900118
Steven Thomasb02664d2017-07-26 18:48:28 -0700119namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700120
121#pragma clang diagnostic push
122#pragma clang diagnostic error "-Wswitch-enum"
123
124bool isWideColorMode(const ColorMode colorMode) {
125 switch (colorMode) {
126 case ColorMode::DISPLAY_P3:
127 case ColorMode::ADOBE_RGB:
128 case ColorMode::DCI_P3:
129 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700130 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700131 case ColorMode::BT2100_PQ:
132 case ColorMode::BT2100_HLG:
133 return true;
134 case ColorMode::NATIVE:
135 case ColorMode::STANDARD_BT601_625:
136 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
137 case ColorMode::STANDARD_BT601_525:
138 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
139 case ColorMode::STANDARD_BT709:
140 case ColorMode::SRGB:
141 return false;
142 }
143 return false;
144}
145
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700146ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
147 switch (rotation) {
148 case ISurfaceComposer::eRotateNone:
149 return ui::Transform::ROT_0;
150 case ISurfaceComposer::eRotate90:
151 return ui::Transform::ROT_90;
152 case ISurfaceComposer::eRotate180:
153 return ui::Transform::ROT_180;
154 case ISurfaceComposer::eRotate270:
155 return ui::Transform::ROT_270;
156 }
157 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
158 return ui::Transform::ROT_0;
159}
160
Peiyong Linfca547f2018-07-09 13:03:33 -0700161#pragma clang diagnostic pop
162
Steven Thomasb02664d2017-07-26 18:48:28 -0700163class ConditionalLock {
164public:
165 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
166 if (lock) {
167 mMutex.lock();
168 }
169 }
170 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
171private:
172 Mutex& mMutex;
173 bool mLocked;
174};
Peiyong Linfca547f2018-07-09 13:03:33 -0700175
Steven Thomasb02664d2017-07-26 18:48:28 -0700176} // namespace anonymous
177
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800178// ---------------------------------------------------------------------------
179
Mathias Agopian99b49842011-06-27 16:05:52 -0700180const String16 sHardwareTest("android.permission.HARDWARE_TEST");
181const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
182const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
183const String16 sDump("android.permission.DUMP");
184
185// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800186int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
187int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700188int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700189bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800190uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800191bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800192bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800193int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800194// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600195bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700196int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700197bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700198bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700199Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
200ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
201Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
202ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700203
Kalle Raitaa099a242017-01-11 11:17:29 -0800204std::string getHwcServiceName() {
205 char value[PROPERTY_VALUE_MAX] = {};
206 property_get("debug.sf.hwc_service_name", value, "default");
207 ALOGI("Using HWComposer service: '%s'", value);
208 return std::string(value);
209}
210
211bool useTrebleTestingOverride() {
212 char value[PROPERTY_VALUE_MAX] = {};
213 property_get("debug.sf.treble_testing_override", value, "false");
214 ALOGI("Treble testing override: '%s'", value);
215 return std::string(value) == "true";
216}
217
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800218std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
219 switch(displayColorSetting) {
220 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700221 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800222 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700223 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800224 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700225 return std::string("Enhanced");
226 default:
227 return std::string("Unknown ") +
228 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800229 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800230}
231
David Sodmanbc815282017-11-05 18:57:52 -0800232SurfaceFlingerBE::SurfaceFlingerBE()
233 : mHwcServiceName(getHwcServiceName()),
234 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800235 mFrameBuckets(),
236 mTotalTime(0),
237 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800238 mComposerSequenceId(0) {
239}
240
Lloyd Pique90c115d2018-09-18 21:39:42 -0700241SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
242 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800243 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700244 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700245 mTransactionPending(false),
246 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700247 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700248 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800249 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700250 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800251 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800252 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800253 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800254 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800255 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700256 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700257 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700258 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700259 mDebugInTransaction(0),
260 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700261 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700262 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700263 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800264 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800265 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800266 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700267 mVrFlingerRequestsDisplay(false),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700268 mMainThreadId(std::this_thread::get_id()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800269
Lloyd Pique90c115d2018-09-18 21:39:42 -0700270SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
271 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800272 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800273
274 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
275 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
276
277 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
278 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
279
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800280 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
281 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800282
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700283 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
284 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
285
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700286 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
287 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
288
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800289 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
290 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
291
Steven Thomas050b2c82017-03-06 11:45:16 -0800292 // Vr flinger is only enabled on Daydream ready devices.
293 useVrFlinger = getBool< ISurfaceFlingerConfigs,
294 &ISurfaceFlingerConfigs::useVrFlinger>(false);
295
Fabien Sanglard1971b632017-03-10 14:50:03 -0800296 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
297 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
298
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600299 hasWideColorDisplay =
300 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700301 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700302 getBool<V1_2::ISurfaceFlingerConfigs,
303 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
304
305 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
306 if (surfaceFlingerConfigsServiceV1_2) {
307 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
Peiyong Linc6780972018-10-28 15:24:08 -0700308 [&](auto tmpDefaultDataspace, auto tmpDefaultPixelFormat,
309 auto tmpWideColorGamutDataspace, auto tmpWideColorGamutPixelFormat) {
310 defaultCompositionDataspace = tmpDefaultDataspace;
311 defaultCompositionPixelFormat = tmpDefaultPixelFormat;
312 wideColorGamutCompositionDataspace = tmpWideColorGamutDataspace;
313 wideColorGamutCompositionPixelFormat = tmpWideColorGamutPixelFormat;
314 });
Peiyong Lin0256f722018-08-31 15:45:10 -0700315 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600316
Peiyong Linb3839ad2018-09-05 15:37:19 -0700317 useContextPriority = getBool<ISurfaceFlingerConfigs,
318 &ISurfaceFlingerConfigs::useContextPriority>(true);
319
Iris Chang7501ed62018-04-30 14:45:42 +0800320 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700321 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
322 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800323 V1_1::DisplayOrientation::ORIENTATION_0);
324
325 switch (primaryDisplayOrientation) {
326 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700327 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800328 break;
329 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700330 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800331 break;
332 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700333 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800334 break;
335 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700336 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800337 break;
338 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700339 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800340
Lloyd Pique90c115d2018-09-18 21:39:42 -0700341 mPrimaryDispSync =
342 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
343 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700344
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800345 // debugging stuff...
346 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700347
Mathias Agopianb4b17302013-03-20 18:36:41 -0700348 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700349 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700350
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800351 property_get("debug.sf.showupdates", value, "0");
352 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700353
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700354 property_get("debug.sf.ddms", value, "0");
355 mDebugDDMS = atoi(value);
356 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700357 if (!startDdmConnection()) {
358 // start failed, and DDMS debugging not enabled
359 mDebugDDMS = 0;
360 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700361 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700362 ALOGI_IF(mDebugRegion, "showupdates enabled");
363 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700364
365 property_get("debug.sf.disable_backpressure", value, "0");
366 mPropagateBackpressure = !atoi(value);
367 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700368
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800369 property_get("debug.sf.enable_hwc_vds", value, "0");
370 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800371 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800372
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800373 property_get("ro.sf.disable_triple_buffer", value, "1");
374 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800375 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700376
Yiwei Zhang243b3782018-05-15 17:40:04 -0700377 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700378 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
379 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
380
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200381 property_get("debug.sf.early_phase_offset_ns", value, "-1");
382 const int earlySfOffsetNs = atoi(value);
383
384 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
385 const int earlyGlSfOffsetNs = atoi(value);
386
387 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
388 const int earlyAppOffsetNs = atoi(value);
389
390 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
391 const int earlyGlAppOffsetNs = atoi(value);
392
Ana Krulec98b5b242018-08-10 15:03:23 -0700393 property_get("debug.sf.use_scheduler", value, "0");
394 mUseScheduler = atoi(value);
395
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200396 const VSyncModulator::Offsets earlyOffsets =
397 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
398 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
399 const VSyncModulator::Offsets earlyGlOffsets =
400 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
401 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
402 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
403 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700404
Romain Guy11d63f42017-07-20 12:47:14 -0700405 // We should be reading 'persist.sys.sf.color_saturation' here
406 // but since /data may be encrypted, we need to wait until after vold
407 // comes online to attempt to read the property. The property is
408 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800409
410 if (useTrebleTestingOverride()) {
411 // Without the override SurfaceFlinger cannot connect to HIDL
412 // services that are not listed in the manifests. Considered
413 // deriving the setting from the set service name, but it
414 // would be brittle if the name that's not 'default' is used
415 // for production purposes later on.
416 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
417 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800418}
419
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800420void SurfaceFlinger::onFirstRef()
421{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800422 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800423}
424
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800425SurfaceFlinger::~SurfaceFlinger()
426{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800427}
428
Dan Stozac7014012014-02-14 15:03:43 -0800429void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800430{
431 // the window manager died on us. prepare its eulogy.
432
Andy McFadden13a082e2012-08-24 10:16:42 -0700433 // restore initial conditions (default device unblank, etc)
434 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800435
436 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700437 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800438}
439
Robert Carr1db73f62016-12-21 12:58:51 -0800440static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700441 status_t err = client->initCheck();
442 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800443 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800444 }
Robert Carr1db73f62016-12-21 12:58:51 -0800445 return nullptr;
446}
447
448sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
449 return initClient(new Client(this));
450}
451
452sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
453 const sp<IGraphicBufferProducer>& gbp) {
454 if (authenticateSurfaceTexture(gbp) == false) {
455 return nullptr;
456 }
457 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
458 if (layer == nullptr) {
459 return nullptr;
460 }
461
462 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800463}
464
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700465sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
466 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700467{
468 class DisplayToken : public BBinder {
469 sp<SurfaceFlinger> flinger;
470 virtual ~DisplayToken() {
471 // no more references, this display must be terminated
472 Mutex::Autolock _l(flinger->mStateLock);
473 flinger->mCurrentState.displays.removeItem(this);
474 flinger->setTransactionFlags(eDisplayTransactionNeeded);
475 }
476 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700477 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700478 : flinger(flinger) {
479 }
480 };
481
482 sp<BBinder> token = new DisplayToken(this);
483
484 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700485 DisplayDeviceState info;
486 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700487 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700488 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700489 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800490 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700491 return token;
492}
493
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700494void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700495 Mutex::Autolock _l(mStateLock);
496
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700497 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700498 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700499 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700500 return;
501 }
502
503 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700504 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700505 ALOGE("destroyDisplay called for non-virtual display");
506 return;
507 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700508 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700509 mCurrentState.displays.removeItemsAt(idx);
510 setTransactionFlags(eDisplayTransactionNeeded);
511}
512
Mathias Agopiane57f2922012-08-09 16:29:12 -0700513sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700514 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700515 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800516 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700517 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700518 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700519}
520
Ady Abraham37965d42018-11-01 13:43:32 -0700521status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
522 if (!outGetColorManagement) {
523 return BAD_VALUE;
524 }
525 *outGetColorManagement = useColorManagement;
526 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700527}
528
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800529void SurfaceFlinger::bootFinished()
530{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700531 if (mStartPropertySetThread->join() != NO_ERROR) {
532 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800533 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800534 const nsecs_t now = systemTime();
535 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000536 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700537
538 // wait patiently for the window manager death
539 const String16 name("window");
540 sp<IBinder> window(defaultServiceManager()->getService(name));
541 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700542 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700543 }
544
Steven Thomas050b2c82017-03-06 11:45:16 -0800545 if (mVrFlinger) {
546 mVrFlinger->OnBootFinished();
547 }
548
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700549 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700550 // formerly we would just kill the process, but we now ask it to exit so it
551 // can choose where to stop the animation.
552 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700553
554 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
555 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
556 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700557
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800558 postMessageAsync(new LambdaMessage([this] {
559 readPersistentProperties();
560 mBootStage = BootStage::FINISHED;
561 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800562}
563
Dan Stoza436ccf32018-06-21 12:10:12 -0700564uint32_t SurfaceFlinger::getNewTexture() {
565 {
566 std::lock_guard lock(mTexturePoolMutex);
567 if (!mTexturePool.empty()) {
568 uint32_t name = mTexturePool.back();
569 mTexturePool.pop_back();
570 ATRACE_INT("TexturePoolSize", mTexturePool.size());
571 return name;
572 }
573
574 // The pool was too small, so increase it for the future
575 ++mTexturePoolSize;
576 }
577
578 // The pool was empty, so we need to get a new texture name directly using a
579 // blocking call to the main thread
580 uint32_t name = 0;
581 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
582 return name;
583}
584
Mathias Agopian3f844832013-08-07 21:24:32 -0700585void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700586 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700587}
588
Wei Wangf9b05ee2017-07-19 20:59:39 -0700589// Do not call property_set on main thread which will be blocked by init
590// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700591void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700592 ALOGI( "SurfaceFlinger's main thread ready to run. "
593 "Initializing graphics H/W...");
594
Thierry Strudel2924d012017-08-14 15:19:37 -0700595 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900596
Steven Thomasb02664d2017-07-26 18:48:28 -0700597 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800598
Steven Thomasb02664d2017-07-26 18:48:28 -0700599 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700600 if (mUseScheduler) {
Lloyd Pique90c115d2018-09-18 21:39:42 -0700601 mScheduler = getFactory().createScheduler(
Ana Krulece588e312018-09-18 12:32:24 -0700602 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Ana Krulec98b5b242018-08-10 15:03:23 -0700603 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700604 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700605 [this] { resyncWithRateLimit(); },
606 impl::EventThread::InterceptVSyncsCallback());
607 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700608 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700609 [this] { resyncWithRateLimit(); },
610 [this](nsecs_t timestamp) {
611 mInterceptor->saveVSyncEvent(timestamp);
612 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800613
Ana Krulec98b5b242018-08-10 15:03:23 -0700614 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700615 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
616 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700617 } else {
618 mEventThreadSource =
619 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
620 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
621 mEventThread =
622 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
623 [this] { resyncWithRateLimit(); },
624 impl::EventThread::InterceptVSyncsCallback(),
625 "appEventThread");
626 mSfEventThreadSource =
627 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
628 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
629
630 mSFEventThread =
631 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
632 [this] { resyncWithRateLimit(); },
633 [this](nsecs_t timestamp) {
634 mInterceptor->saveVSyncEvent(timestamp);
635 },
636 "sfEventThread");
637 mEventQueue->setEventThread(mSFEventThread.get());
638 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
639 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800640
Steven Thomasb02664d2017-07-26 18:48:28 -0700641 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700642 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700643 renderEngineFeature |= (useColorManagement ?
644 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700645 renderEngineFeature |= (useContextPriority ?
646 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700647
648 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
649 getBE().mRenderEngine =
Peiyong Linc6780972018-10-28 15:24:08 -0700650 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
651 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800652 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700653
654 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
655 "Starting with vr flinger active is not currently supported.");
Lloyd Pique90c115d2018-09-18 21:39:42 -0700656 getBE().mHwc = getFactory().createHWComposer(getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -0700657 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800658 // Process any initial hotplug and resulting display changes.
659 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700660 const auto display = getDefaultDisplayDeviceLocked();
661 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
662 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
663 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800664
Lloyd Piquefcd86612017-12-14 17:15:36 -0800665 // make the default display GLContext current so that we can create textures
666 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700667 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800668
Steven Thomas050b2c82017-03-06 11:45:16 -0800669 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700670 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700671 // This callback is called from the vr flinger dispatch thread. We
672 // need to call signalTransaction(), which requires holding
673 // mStateLock when we're not on the main thread. Acquiring
674 // mStateLock from the vr flinger dispatch thread might trigger a
675 // deadlock in surface flinger (see b/66916578), so post a message
676 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700677 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700678 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
679 mVrFlingerRequestsDisplay = requestDisplay;
680 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700681 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800682 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700683 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
684 getHwComposer()
685 .getHwcDisplayId(display->getId())
686 .value_or(0),
687 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800688 if (!mVrFlinger) {
689 ALOGE("Failed to start vrflinger");
690 }
691 }
692
Lloyd Pique90c115d2018-09-18 21:39:42 -0700693 mEventControlThread = getFactory().createEventControlThread(
Lloyd Pique379adc12018-01-22 17:31:47 -0800694 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700695
Mathias Agopian92a979a2012-08-02 18:32:23 -0700696 // initialize our drawing state
697 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700698
Andy McFadden13a082e2012-08-24 10:16:42 -0700699 // set initial conditions (e.g. unblank default device)
700 initializeDisplays();
701
David Sodmanbc815282017-11-05 18:57:52 -0800702 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700703
Wei Wangf9b05ee2017-07-19 20:59:39 -0700704 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700705
706 const bool presentFenceReliable =
707 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
708 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700709
710 if (mStartPropertySetThread->Start() != NO_ERROR) {
711 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800712 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800713
Chia-I Wud49d6692018-06-27 07:17:41 +0800714 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
715 // is used to saturate legacy sRGB content. However, to make sure the same color under
716 // Display P3 will be saturated to the same color, we intentionally break the API spec
717 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
718 // such saturation matrix on Display P3 is understood fully, the API should always return
719 // identify matrix.
720 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
721 Dataspace::SRGB_LINEAR);
722
723 // we will apply this on Display P3.
724 if (mEnhancedSaturationMatrix != mat4()) {
725 ColorSpace srgb(ColorSpace::sRGB());
726 ColorSpace displayP3(ColorSpace::DisplayP3());
727 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
728 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
729 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
730 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800731
Dan Stoza9e56aa02015-11-02 13:00:03 -0800732 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700733}
734
Romain Guy11d63f42017-07-20 12:47:14 -0700735void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700736 Mutex::Autolock _l(mStateLock);
737
Romain Guy11d63f42017-07-20 12:47:14 -0700738 char value[PROPERTY_VALUE_MAX];
739
740 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800741 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700742 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800743 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100744
745 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700746 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700747}
748
Mathias Agopiana67e4182012-06-19 17:26:12 -0700749void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800750 // Start boot animation service by setting a property mailbox
751 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700752 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800753 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700754 if (mStartPropertySetThread->join() != NO_ERROR) {
755 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800756 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700757}
758
Mathias Agopian875d8e12013-06-07 15:35:48 -0700759size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800760 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700761}
762
Mathias Agopian875d8e12013-06-07 15:35:48 -0700763size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800764 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700765}
766
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800767// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800768
Jamie Gennis582270d2011-08-17 18:19:00 -0700769bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800770 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800771 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800772 return authenticateSurfaceTextureLocked(bufferProducer);
773}
774
775bool SurfaceFlinger::authenticateSurfaceTextureLocked(
776 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800777 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800778 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800779}
780
Brian Anderson6b376712017-04-04 10:51:39 -0700781status_t SurfaceFlinger::getSupportedFrameTimestamps(
782 std::vector<FrameEvent>* outSupported) const {
783 *outSupported = {
784 FrameEvent::REQUESTED_PRESENT,
785 FrameEvent::ACQUIRE,
786 FrameEvent::LATCH,
787 FrameEvent::FIRST_REFRESH_START,
788 FrameEvent::LAST_REFRESH_START,
789 FrameEvent::GPU_COMPOSITION_DONE,
790 FrameEvent::DEQUEUE_READY,
791 FrameEvent::RELEASE,
792 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700793 ConditionalLock _l(mStateLock,
794 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700795 if (!getHwComposer().hasCapability(
796 HWC2::Capability::PresentFenceIsNotReliable)) {
797 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
798 }
799 return NO_ERROR;
800}
801
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700802status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
803 Vector<DisplayInfo>* configs) {
804 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700805 return BAD_VALUE;
806 }
807
Jesse Hall692c7232012-11-08 15:41:56 -0800808 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700809 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
810 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700811 type = i;
812 break;
813 }
814 }
815
816 if (type < 0) {
817 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700818 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700819
Mathias Agopian8b736f12012-08-13 17:54:26 -0700820 // TODO: Not sure if display density should handled by SF any longer
821 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700822 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700823 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700824 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800825 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700826 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700827 }
828 return density;
829 }
830 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700831 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700832 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700833 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700834 return getDensityFromProperty("ro.sf.lcd_density"); }
835 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700836
Dan Stoza7f7da322014-05-02 15:26:25 -0700837 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700838
Steven Thomas6d8110b2017-08-31 18:24:21 -0700839 ConditionalLock _l(mStateLock,
840 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800841 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700842 DisplayInfo info = DisplayInfo();
843
Dan Stoza9e56aa02015-11-02 13:00:03 -0800844 float xdpi = hwConfig->getDpiX();
845 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700846
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700847 info.w = hwConfig->getWidth();
848 info.h = hwConfig->getHeight();
849 // Default display viewport to display width and height
850 info.viewportW = info.w;
851 info.viewportH = info.h;
852
Dan Stoza7f7da322014-05-02 15:26:25 -0700853 if (type == DisplayDevice::DISPLAY_PRIMARY) {
854 // The density of the device is provided by a build property
855 float density = Density::getBuildDensity() / 160.0f;
856 if (density == 0) {
857 // the build doesn't provide a density -- this is wrong!
858 // use xdpi instead
859 ALOGE("ro.sf.lcd_density must be defined as a build property");
860 density = xdpi / 160.0f;
861 }
862 if (Density::getEmuDensity()) {
863 // if "qemu.sf.lcd_density" is specified, it overrides everything
864 xdpi = ydpi = density = Density::getEmuDensity();
865 density /= 160.0f;
866 }
867 info.density = density;
868
869 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700870 const auto display = getDefaultDisplayDeviceLocked();
871 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700872
873 // This is for screenrecord
874 const Rect viewport = display->getViewport();
875 if (viewport.isValid()) {
876 info.viewportW = uint32_t(viewport.getWidth());
877 info.viewportH = uint32_t(viewport.getHeight());
878 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700879 } else {
880 // TODO: where should this value come from?
881 static const int TV_DENSITY = 213;
882 info.density = TV_DENSITY / 160.0f;
883 info.orientation = 0;
884 }
885
Dan Stoza7f7da322014-05-02 15:26:25 -0700886 info.xdpi = xdpi;
887 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800888 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900889 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800890
Andy McFadden91b2ca82014-06-13 14:04:23 -0700891 // This is how far in advance a buffer must be queued for
892 // presentation at a given time. If you want a buffer to appear
893 // on the screen at time N, you must submit the buffer before
894 // (N - presentationDeadline).
895 //
896 // Normally it's one full refresh period (to give SF a chance to
897 // latch the buffer), but this can be reduced by configuring a
898 // DispSync offset. Any additional delays introduced by the hardware
899 // composer or panel must be accounted for here.
900 //
901 // We add an additional 1ms to allow for processing time and
902 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800903 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800904 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700905
906 // All non-virtual displays are currently considered secure.
907 info.secure = true;
908
Iris Chang7501ed62018-04-30 14:45:42 +0800909 if (type == DisplayDevice::DISPLAY_PRIMARY &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700910 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800911 std::swap(info.w, info.h);
912 }
913
Michael Wright28f24d02016-07-12 13:30:53 -0700914 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700915 }
916
Dan Stoza7f7da322014-05-02 15:26:25 -0700917 return NO_ERROR;
918}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700919
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700920status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
921 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700922 return BAD_VALUE;
923 }
924
Ana Krulece588e312018-09-18 12:32:24 -0700925 // FIXME for now we always return stats for the primary display.
926 if (mUseScheduler) {
927 mScheduler->getDisplayStatInfo(stats);
928 } else {
929 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
930 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
931 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700932 return NO_ERROR;
933}
934
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700935int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
936 const auto display = getDisplayDevice(displayToken);
937 if (!display) {
938 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800939 return BAD_VALUE;
940 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700941
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700942 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700943}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700944
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700945void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
946 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700947 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700948 return;
949 }
950
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700951 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700952 ALOGW("Trying to set config for virtual display");
953 return;
954 }
955
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700956 display->setActiveConfig(mode);
957 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700958}
959
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700960status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700961 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700962 Vector<DisplayInfo> configs;
963 getDisplayConfigs(displayToken, &configs);
964 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
965 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
966 configs.size());
967 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700968 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700969 const auto display = getDisplayDevice(displayToken);
970 if (!display) {
971 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
972 displayToken.get());
973 } else if (display->isVirtual()) {
974 ALOGW("Attempt to set active config %d for virtual display", mode);
975 } else {
976 setActiveConfigInternal(display, mode);
977 }
978 }));
979
Mathias Agopian888c8222012-08-04 21:10:38 -0700980 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700981}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700982status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
983 Vector<ColorMode>* outColorModes) {
984 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700985 return BAD_VALUE;
986 }
987
Michael Wright28f24d02016-07-12 13:30:53 -0700988 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700989 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
990 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700991 type = i;
992 break;
993 }
994 }
995
996 if (type < 0) {
997 return type;
998 }
999
Peiyong Lina52f0292018-03-14 17:26:31 -07001000 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001001 {
1002 ConditionalLock _l(mStateLock,
1003 std::this_thread::get_id() != mMainThreadId);
1004 modes = getHwComposer().getColorModes(type);
1005 }
Michael Wright28f24d02016-07-12 13:30:53 -07001006 outColorModes->clear();
1007 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1008
1009 return NO_ERROR;
1010}
1011
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001012ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1013 if (const auto display = getDisplayDevice(displayToken)) {
1014 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001015 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001016 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001017}
1018
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001019void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1020 Dataspace dataSpace, RenderIntent renderIntent) {
1021 ColorMode currentMode = display->getActiveColorMode();
1022 Dataspace currentDataSpace = display->getCompositionDataSpace();
1023 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001024
Peiyong Lin38e9a562018-04-10 16:24:20 -07001025 if (mode == currentMode && dataSpace == currentDataSpace &&
1026 renderIntent == currentRenderIntent) {
1027 return;
1028 }
1029
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001030 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001031 ALOGW("Trying to set config for virtual display");
1032 return;
1033 }
1034
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001035 display->setActiveColorMode(mode);
1036 display->setCompositionDataSpace(dataSpace);
1037 display->setActiveRenderIntent(renderIntent);
1038 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001039
1040 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001041 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1042 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001043}
1044
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001045status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001046 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001047 Vector<ColorMode> modes;
1048 getDisplayColorModes(displayToken, &modes);
1049 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1050 if (mode < ColorMode::NATIVE || !exists) {
1051 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1052 decodeColorMode(mode).c_str(), mode, displayToken.get());
1053 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001054 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001055 const auto display = getDisplayDevice(displayToken);
1056 if (!display) {
1057 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1058 decodeColorMode(mode).c_str(), mode, displayToken.get());
1059 } else if (display->isVirtual()) {
1060 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1061 decodeColorMode(mode).c_str(), mode);
1062 } else {
1063 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1064 RenderIntent::COLORIMETRIC);
1065 }
1066 }));
1067
Michael Wright28f24d02016-07-12 13:30:53 -07001068 return NO_ERROR;
1069}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001070
Svetoslavd85084b2014-03-20 10:28:31 -07001071status_t SurfaceFlinger::clearAnimationFrameStats() {
1072 Mutex::Autolock _l(mStateLock);
1073 mAnimFrameTracker.clearStats();
1074 return NO_ERROR;
1075}
1076
1077status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1078 Mutex::Autolock _l(mStateLock);
1079 mAnimFrameTracker.getStats(outStats);
1080 return NO_ERROR;
1081}
1082
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001083status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1084 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001085 Mutex::Autolock _l(mStateLock);
1086
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001087 const auto display = getDisplayDeviceLocked(displayToken);
1088 if (!display) {
1089 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001090 return BAD_VALUE;
1091 }
1092
Peiyong Linfb069302018-04-25 14:34:31 -07001093 // At this point the DisplayDeivce should already be set up,
1094 // meaning the luminance information is already queried from
1095 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001096 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001097 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1098 capabilities.getDesiredMaxLuminance(),
1099 capabilities.getDesiredMaxAverageLuminance(),
1100 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001101
1102 return NO_ERROR;
1103}
1104
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001105status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001106 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001107 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001108
Chia-I Wu90f669f2017-10-05 14:24:41 -07001109 if (mInjectVSyncs == enable) {
1110 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001111 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001112
Ana Krulec98b5b242018-08-10 15:03:23 -07001113 // TODO(akrulec): Part of the Injector should be refactored, so that it
1114 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001115 if (enable) {
1116 ALOGV("VSync Injections enabled");
1117 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001118 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001119 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001120 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001121 impl::EventThread::InterceptVSyncsCallback(),
1122 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001123 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001124 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001125 } else {
1126 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001127 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001128 }
1129
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001130 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001131 }));
1132
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001133 return NO_ERROR;
1134}
1135
1136status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001137 Mutex::Autolock _l(mStateLock);
1138
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001139 if (!mInjectVSyncs) {
1140 ALOGE("VSync Injections not enabled");
1141 return BAD_VALUE;
1142 }
1143 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1144 ALOGV("Injecting VSync inside SurfaceFlinger");
1145 mVSyncInjector->onInjectSyncEvent(when);
1146 }
1147 return NO_ERROR;
1148}
1149
Lloyd Pique755e3192018-01-31 16:46:15 -08001150status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1151 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001152 // Try to acquire a lock for 1s, fail gracefully
1153 const status_t err = mStateLock.timedLock(s2ns(1));
1154 const bool locked = (err == NO_ERROR);
1155 if (!locked) {
1156 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1157 return TIMED_OUT;
1158 }
1159
1160 outLayers->clear();
1161 mCurrentState.traverseInZOrder([&](Layer* layer) {
1162 outLayers->push_back(layer->getLayerDebugInfo());
1163 });
1164
1165 mStateLock.unlock();
1166 return NO_ERROR;
1167}
1168
Peiyong Linc6780972018-10-28 15:24:08 -07001169status_t SurfaceFlinger::getCompositionPreference(
1170 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1171 Dataspace* outWideColorGamutDataspace,
1172 ui::PixelFormat* outWideColorGamutPixelFormat) const {
1173 *outDataspace = defaultCompositionDataspace;
1174 *outPixelFormat = defaultCompositionPixelFormat;
1175 *outWideColorGamutDataspace = wideColorGamutCompositionDataspace;
1176 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001177 return NO_ERROR;
1178}
1179
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001180// ----------------------------------------------------------------------------
1181
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001182sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1183 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001184 if (mUseScheduler) {
1185 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1186 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1187 } else {
1188 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1189 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001190 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001191 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1192 return mSFEventThread->createEventConnection();
1193 } else {
1194 return mEventThread->createEventConnection();
1195 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001196 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001197}
1198
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001199// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001200
1201void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001202 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001203}
1204
1205void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001206 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001207}
1208
1209void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001210 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001211}
1212
1213void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001214 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001215 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001216}
1217
1218status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001219 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001220 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001221}
1222
1223status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001224 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001225 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001226 if (res == NO_ERROR) {
1227 msg->wait();
1228 }
1229 return res;
1230}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001231
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001232void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001233 do {
1234 waitForEvent();
1235 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001236}
1237
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001238void SurfaceFlinger::enableHardwareVsync() {
1239 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001240 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001241 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001242 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001243 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001244 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001245}
1246
Jesse Hall948fe0c2013-10-14 12:56:09 -07001247void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001248 Mutex::Autolock _l(mHWVsyncLock);
1249
Jesse Hall948fe0c2013-10-14 12:56:09 -07001250 if (makeAvailable) {
1251 mHWVsyncAvailable = true;
1252 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001253 // Hardware vsync is not currently available, so abort the resync
1254 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001255 return;
1256 }
1257
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001258 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1259 if (!getHwComposer().isConnected(displayId)) {
1260 return;
1261 }
1262
1263 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001264 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001265
Ana Krulece588e312018-09-18 12:32:24 -07001266 if (mUseScheduler) {
1267 mScheduler->setVsyncPeriod(period);
1268 } else {
1269 mPrimaryDispSync->reset();
1270 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001271
Ana Krulece588e312018-09-18 12:32:24 -07001272 if (!mPrimaryHWVsyncEnabled) {
1273 mPrimaryDispSync->beginResync();
1274 mEventControlThread->setVsyncEnabled(true);
1275 mPrimaryHWVsyncEnabled = true;
1276 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001277 }
1278}
1279
Jesse Hall948fe0c2013-10-14 12:56:09 -07001280void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001281 Mutex::Autolock _l(mHWVsyncLock);
1282 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001283 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001284 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001285 mPrimaryHWVsyncEnabled = false;
1286 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001287 if (makeUnavailable) {
1288 mHWVsyncAvailable = false;
1289 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001290}
1291
Tim Murray4a4e4a22016-04-19 16:29:23 +00001292void SurfaceFlinger::resyncWithRateLimit() {
1293 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001294
1295 // No explicit locking is needed here since EventThread holds a lock while calling this method
1296 static nsecs_t sLastResyncAttempted = 0;
1297 const nsecs_t now = systemTime();
1298 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001299 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001300 }
Dan Stoza57164302017-05-08 14:03:54 -07001301 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001302}
1303
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001304void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1305 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001306 ATRACE_NAME("SF onVsync");
1307
Steven Thomas3cfac282017-02-06 12:29:30 -08001308 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001309 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001310 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001311 return;
1312 }
1313
1314 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001315 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001316 return;
1317 }
1318
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001319 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1320 // For now, we don't do anything with external display vsyncs.
1321 return;
1322 }
1323
Ana Krulece588e312018-09-18 12:32:24 -07001324 if (mUseScheduler) {
1325 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001326 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001327 bool needsHwVsync = false;
1328 { // Scope for the lock
1329 Mutex::Autolock _l(mHWVsyncLock);
1330 if (mPrimaryHWVsyncEnabled) {
1331 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1332 }
1333 }
1334
1335 if (needsHwVsync) {
1336 enableHardwareVsync();
1337 } else {
1338 disableHardwareVsync(false);
1339 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001340 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001341}
1342
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001343void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001344 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1345 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001346}
1347
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001348void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001349 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001350 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001351 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001352
Lloyd Piqueba04e622017-12-14 17:11:26 -08001353 // Ignore events that do not have the right sequenceId.
1354 if (sequenceId != getBE().mComposerSequenceId) {
1355 return;
1356 }
1357
Steven Thomasb02664d2017-07-26 18:48:28 -07001358 // Only lock if we're not on the main thread. This function is normally
1359 // called on a hwbinder thread, but for the primary display it's called on
1360 // the main thread with the state lock already held, so don't attempt to
1361 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001362 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001363
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001364 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001365
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001366 if (std::this_thread::get_id() == mMainThreadId) {
1367 // Process all pending hot plug events immediately if we are on the main thread.
1368 processDisplayHotplugEventsLocked();
1369 }
1370
Lloyd Piqueba04e622017-12-14 17:11:26 -08001371 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001372}
1373
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001374void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001375 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001376 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001377 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001378 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001379 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001380}
1381
Dan Stoza9e56aa02015-11-02 13:00:03 -08001382void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001383 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001384 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001385 getHwComposer().setVsyncEnabled(disp,
1386 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001387}
1388
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001389// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001390void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001391 if (mUseScheduler) {
1392 mScheduler->disableHardwareVsync(true);
1393 } else {
1394 disableHardwareVsync(true);
1395 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001396 // Clear the drawing state so that the logic inside of
1397 // handleTransactionLocked will fire. It will determine the delta between
1398 // mCurrentState and mDrawingState and re-apply all changes when we make the
1399 // transition.
1400 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001401 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001402 mDisplays.clear();
1403}
1404
Steven Thomas050b2c82017-03-06 11:45:16 -08001405void SurfaceFlinger::updateVrFlinger() {
1406 if (!mVrFlinger)
1407 return;
1408 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001409 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001410 return;
1411 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001412
David Sodman105b7dc2017-11-04 20:28:14 -07001413 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001414 ALOGE("Vr flinger is only supported for remote hardware composer"
1415 " service connections. Ignoring request to transition to vr"
1416 " flinger.");
1417 mVrFlingerRequestsDisplay = false;
1418 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001419 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001420
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001421 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001422
Steven Thomas0123ac62018-07-12 11:32:34 -07001423 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001424 LOG_ALWAYS_FATAL_IF(!display);
1425 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001426 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1427 // called below. Clear the reference now so we don't accidentally use it
1428 // later.
1429 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001430
Steven Thomasb02664d2017-07-26 18:48:28 -07001431 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001432 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001433 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001434
Steven Thomasb02664d2017-07-26 18:48:28 -07001435 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001436 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Pique90c115d2018-09-18 21:39:42 -07001437 getBE().mHwc = getFactory().createHWComposer(
1438 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -07001439 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001440
David Sodman105b7dc2017-11-04 20:28:14 -07001441 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1442 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001443
1444 if (vrFlingerRequestsDisplay) {
1445 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001446 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001447
1448 mVisibleRegionsDirty = true;
1449 invalidateHwcGeometry();
1450
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001451 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001452 display = getDefaultDisplayDeviceLocked();
1453 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001454 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001455
Steven Thomasb02664d2017-07-26 18:48:28 -07001456 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001457 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001458 const nsecs_t period = activeConfig->getVsyncPeriod();
1459 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001460
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001461 // The present fences returned from vr_hwc are not an accurate
1462 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001463 if (mUseScheduler) {
1464 mScheduler->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() || !hasSyncFramework);
1465 } else {
1466 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1467 !hasSyncFramework);
1468 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001469
Steven Thomasb02664d2017-07-26 18:48:28 -07001470 // Use phase of 0 since phase is not known.
1471 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001472 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1473 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001474
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001475 resyncToHardwareVsync(false);
1476
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001477 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001478 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001479}
1480
Mathias Agopian4fec8732012-06-29 14:12:52 -07001481void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001482 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001483 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001484 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001485 bool frameMissed = !mHadClientComposition &&
1486 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001487 (mPreviousPresentFence->getSignalTime() ==
1488 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001489 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001490 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001491 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001492 mTimeStats.incrementMissedFrames();
1493 if (mPropagateBackpressure) {
1494 signalLayerUpdate();
1495 break;
1496 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001497 }
Dan Stoza50182882016-07-08 12:02:20 -07001498
Steven Thomas050b2c82017-03-06 11:45:16 -08001499 // Now that we're going to make it to the handleMessageTransaction()
1500 // call below it's safe to call updateVrFlinger(), which will
1501 // potentially trigger a display handoff.
1502 updateVrFlinger();
1503
Dan Stoza6b9454d2014-11-07 16:00:59 -08001504 bool refreshNeeded = handleMessageTransaction();
1505 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001506 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001507 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001508 // Signal a refresh if a transaction modified the window state,
1509 // a new buffer was latched, or if HWC has requested a full
1510 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001511 signalRefresh();
1512 }
1513 break;
1514 }
1515 case MessageQueue::REFRESH: {
1516 handleMessageRefresh();
1517 break;
1518 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001519 }
1520}
1521
Dan Stoza6b9454d2014-11-07 16:00:59 -08001522bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001523 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001524 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001525 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001526 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001527 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001528 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001529}
1530
Mathias Agopian4fec8732012-06-29 14:12:52 -07001531void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001532 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001533
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001534 mRefreshPending = false;
1535
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001536 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001537 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001538 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001539 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001540 for (const auto& [token, display] : mDisplays) {
1541 beginFrame(display);
1542 prepareFrame(display);
1543 doDebugFlashRegions(display, repaintEverything);
1544 doComposition(display, repaintEverything);
1545 }
1546
Adrian Roos1e1a1282017-11-01 19:05:31 +01001547 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001548 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001549
1550 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001551 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001552
Dan Stozabfbffeb2016-07-21 14:49:33 -07001553 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001554 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001555 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001556 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001557 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001558
Alec Mouri86770e52018-09-24 22:40:58 +00001559 // Setup RenderEngine sync fences if native sync is supported.
1560 if (getBE().mRenderEngine->useNativeFenceSync()) {
1561 if (mHadClientComposition) {
1562 base::unique_fd flushFence(getRenderEngine().flush());
1563 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1564 getBE().flushFence = new Fence(std::move(flushFence));
1565 } else {
1566 // Cleanup for hygiene.
1567 getBE().flushFence = Fence::NO_FENCE;
1568 }
1569 }
1570
Jorim Jaggi90535212018-05-23 23:44:06 +02001571 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001572
David Sodman7e4ae112018-02-09 15:02:28 -08001573 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001574 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001575 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001576 compositionInfo.hwc.hwcLayer = nullptr;
1577 }
David Sodmanba340492018-08-05 21:51:33 -07001578 }
David Sodman7e4ae112018-02-09 15:02:28 -08001579
1580 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001581}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001582
David Sodmanfa9b2af2017-12-24 13:28:59 -08001583
1584bool SurfaceFlinger::handleMessageInvalidate() {
1585 ATRACE_CALL();
1586 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001587}
1588
David Sodman79bba0e2018-08-05 18:07:49 -07001589void SurfaceFlinger::calculateWorkingSet() {
1590 ATRACE_CALL();
1591 ALOGV(__FUNCTION__);
1592
David Sodman79bba0e2018-08-05 18:07:49 -07001593 // build the h/w work list
1594 if (CC_UNLIKELY(mGeometryInvalid)) {
1595 mGeometryInvalid = false;
1596 for (const auto& [token, display] : mDisplays) {
1597 const auto displayId = display->getId();
1598 if (displayId >= 0) {
1599 const Vector<sp<Layer>>& currentLayers(
1600 display->getVisibleLayersSortedByZ());
1601 for (size_t i = 0; i < currentLayers.size(); i++) {
1602 const auto& layer = currentLayers[i];
1603
1604 if (!layer->hasHwcLayer(displayId)) {
1605 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1606 layer->forceClientComposition(displayId);
1607 continue;
1608 }
1609 }
1610
1611 layer->setGeometry(display, i);
1612 if (mDebugDisableHWC || mDebugRegion) {
1613 layer->forceClientComposition(displayId);
1614 }
1615 }
1616 }
1617 }
1618 }
1619
1620 // Set the per-frame data
1621 for (const auto& [token, display] : mDisplays) {
1622 const auto displayId = display->getId();
1623 if (displayId < 0) {
1624 continue;
1625 }
1626
1627 if (mDrawingState.colorMatrixChanged) {
1628 display->setColorTransform(mDrawingState.colorMatrix);
1629 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1630 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1631 "display %d: %d", displayId, result);
1632 }
1633 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1634 if (layer->isHdrY410()) {
1635 layer->forceClientComposition(displayId);
1636 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1637 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1638 !display->hasHDR10Support()) {
1639 layer->forceClientComposition(displayId);
1640 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1641 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1642 !display->hasHLGSupport()) {
1643 layer->forceClientComposition(displayId);
1644 }
1645
Peiyong Lind3788632018-09-18 16:01:31 -07001646 // TODO(b/111562338) remove when composer 2.3 is shipped.
1647 if (layer->hasColorTransform()) {
1648 layer->forceClientComposition(displayId);
1649 }
1650
David Sodman79bba0e2018-08-05 18:07:49 -07001651 if (layer->getForceClientComposition(displayId)) {
1652 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1653 layer->setCompositionType(displayId, HWC2::Composition::Client);
1654 continue;
1655 }
1656
1657 layer->setPerFrameData(display);
1658 }
1659
Peiyong Lin13effd12018-07-24 17:01:47 -07001660 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001661 ColorMode colorMode;
1662 Dataspace dataSpace;
1663 RenderIntent renderIntent;
1664 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1665 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1666 }
1667 }
1668
1669 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001670
1671 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001672 getBE().mCompositionInfo[token].clear();
1673
David Sodmanba340492018-08-05 21:51:33 -07001674 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001675 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001676 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1677 if (!layer->setHwcLayer(displayId)) {
1678 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1679 }
David Sodman15fb96e2018-01-07 10:23:24 -08001680 layer->getBE().compositionInfo.hwc.displayId = displayId;
Dominik Laskowski05275f12018-11-01 15:03:24 -07001681 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001682 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1683 }
1684 }
David Sodman79bba0e2018-08-05 18:07:49 -07001685}
1686
David Sodmanfa9b2af2017-12-24 13:28:59 -08001687void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001688{
1689 // is debugging enabled
1690 if (CC_LIKELY(!mDebugRegion))
1691 return;
1692
David Sodmanfa9b2af2017-12-24 13:28:59 -08001693 if (display->isPoweredOn()) {
1694 // transform the dirty region into this screen's coordinate space
1695 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1696 if (!dirtyRegion.isEmpty()) {
1697 // redraw the whole screen
1698 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001699
David Sodmanfa9b2af2017-12-24 13:28:59 -08001700 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001701 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001702 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001703
David Sodmanfa9b2af2017-12-24 13:28:59 -08001704 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001705 }
1706 }
1707
David Sodmanfa9b2af2017-12-24 13:28:59 -08001708 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001709
1710 if (mDebugRegion > 1) {
1711 usleep(mDebugRegion * 1000);
1712 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001713
Dominik Laskowski05275f12018-11-01 15:03:24 -07001714 prepareFrame(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001715}
1716
Adrian Roos1e1a1282017-11-01 19:05:31 +01001717void SurfaceFlinger::doTracing(const char* where) {
1718 ATRACE_CALL();
1719 ATRACE_NAME(where);
1720 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001721 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001722 }
1723}
1724
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001725void SurfaceFlinger::logLayerStats() {
1726 ATRACE_CALL();
1727 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001728 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001729 if (display->isPrimary()) {
1730 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001731 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001732 }
1733 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001734
1735 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001736 }
1737}
1738
David Sodman2b406362017-12-15 13:33:47 -08001739void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001740{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001741 ATRACE_CALL();
1742 ALOGV("preComposition");
1743
David Sodman2b406362017-12-15 13:33:47 -08001744 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1745
Mathias Agopiancd60f992012-08-16 16:28:27 -07001746 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001747 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001748 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001749 needExtraInvalidate = true;
1750 }
Robert Carr2047fae2016-11-28 14:09:09 -08001751 });
1752
Mathias Agopiancd60f992012-08-16 16:28:27 -07001753 if (needExtraInvalidate) {
1754 signalLayerUpdate();
1755 }
1756}
1757
Ana Krulece588e312018-09-18 12:32:24 -07001758void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1759 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001760 // Update queue of past composite+present times and determine the
1761 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001762 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001763 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001764 while (!getBE().mCompositePresentTimes.empty()) {
1765 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001766 // Cached values should have been updated before calling this method,
1767 // which helps avoid duplicate syscalls.
1768 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1769 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1770 break;
1771 }
1772 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001773 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001774 }
1775
1776 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001777 while (getBE().mCompositePresentTimes.size() > 16) {
1778 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001779 }
1780
Ana Krulece588e312018-09-18 12:32:24 -07001781 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001782}
1783
Ana Krulece588e312018-09-18 12:32:24 -07001784void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1785 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001786 // Integer division and modulo round toward 0 not -inf, so we need to
1787 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001788 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1789 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1790 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001791
Brian Andersond0010582017-03-07 13:20:31 -08001792 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1793 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001794 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001795 }
1796
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001797 // Snap the latency to a value that removes scheduling jitter from the
1798 // composition and present times, which often have >1ms of jitter.
1799 // Reducing jitter is important if an app attempts to extrapolate
1800 // something (such as user input) to an accurate diasplay time.
1801 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1802 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001803 nsecs_t bias = stats.vsyncPeriod / 2;
1804 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1805 nsecs_t snappedCompositeToPresentLatency =
1806 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001807
David Sodman99974d22017-11-28 12:04:33 -08001808 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001809 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1810 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001811 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001812}
1813
David Sodman2b406362017-12-15 13:33:47 -08001814void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001815{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001816 ATRACE_CALL();
1817 ALOGV("postComposition");
1818
Brian Anderson3546a3f2016-07-14 11:51:14 -07001819 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001820 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001821 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001822 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001823 }
1824
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001825 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001826 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001827
David Sodman73beded2017-11-15 11:56:06 -08001828 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001829 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001830 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001831 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001832 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001833 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001834 } else {
1835 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1836 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001837
David Sodman73beded2017-11-15 11:56:06 -08001838 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001839 mPreviousPresentFence =
1840 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1841 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001842 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001843
Ana Krulece588e312018-09-18 12:32:24 -07001844 DisplayStatInfo stats;
1845 if (mUseScheduler) {
1846 mScheduler->getDisplayStatInfo(&stats);
1847 } else {
1848 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1849 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
1850 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001851
David Sodman2b406362017-12-15 13:33:47 -08001852 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001853 // when we started doing work for this frame, but that should be okay
1854 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07001855 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001856 CompositorTiming compositorTiming;
1857 {
David Sodman99974d22017-11-28 12:04:33 -08001858 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1859 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001860 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001861
Robert Carr2047fae2016-11-28 14:09:09 -08001862 mDrawingState.traverseInZOrder([&](Layer* layer) {
1863 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001864 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001865 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001866 recordBufferingStats(layer->getName().string(),
1867 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001868 }
Robert Carr2047fae2016-11-28 14:09:09 -08001869 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001870
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001871 if (presentFenceTime->isValid()) {
Ana Krulece588e312018-09-18 12:32:24 -07001872 if (mUseScheduler) {
1873 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001874 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001875 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
1876 enableHardwareVsync();
1877 } else {
1878 disableHardwareVsync(false);
1879 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001880 }
1881 }
1882
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001883 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001884 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07001885 if (mUseScheduler) {
1886 mScheduler->enableHardwareVsync();
1887 } else {
1888 enableHardwareVsync();
1889 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001890 }
1891 }
1892
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001893 if (mAnimCompositionPending) {
1894 mAnimCompositionPending = false;
1895
Brian Anderson4e606e32017-03-16 15:34:57 -07001896 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001897 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001898 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001899 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001900 // The HWC doesn't support present fences, so use the refresh
1901 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001902 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001903 mAnimFrameTracker.setActualPresentTime(presentTime);
1904 }
1905 mAnimFrameTracker.advanceFrame();
1906 }
Dan Stozab90cf072015-03-05 11:05:59 -08001907
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001908 mTimeStats.incrementTotalFrames();
1909 if (mHadClientComposition) {
1910 mTimeStats.incrementClientCompositionFrames();
1911 }
1912
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001913 mTimeStats.setPresentFenceGlobal(presentFenceTime);
1914
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001915 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001916 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001917 return;
1918 }
1919
1920 nsecs_t currentTime = systemTime();
1921 if (mHasPoweredOff) {
1922 mHasPoweredOff = false;
1923 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001924 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001925 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001926 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1927 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001928 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001929 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001930 }
David Sodman4a36e932017-11-07 14:29:47 -08001931 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001932 }
David Sodman4a36e932017-11-07 14:29:47 -08001933 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001934
1935 {
1936 std::lock_guard lock(mTexturePoolMutex);
1937 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1938 if (refillCount > 0) {
1939 const size_t offset = mTexturePool.size();
1940 mTexturePool.resize(mTexturePoolSize);
1941 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1942 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1943 }
1944 }
Marissa Walle2ffb422018-10-12 11:33:52 -07001945
Marissa Wallfda30bb2018-10-12 11:34:28 -07001946 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07001947 mTransactionCompletedThread.sendCallbacks();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001948}
1949
1950void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001951 ATRACE_CALL();
1952 ALOGV("rebuildLayerStacks");
1953
Mathias Agopiancd60f992012-08-16 16:28:27 -07001954 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001955 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001956 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001957 mVisibleRegionsDirty = false;
1958 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001959
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001960 for (const auto& pair : mDisplays) {
1961 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001962 Region opaqueRegion;
1963 Region dirtyRegion;
1964 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001965 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001966 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001967 const Rect bounds = display->getBounds();
1968 if (display->isPoweredOn()) {
1969 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001970
Jeff Sharkey76488112017-02-27 14:15:18 -07001971 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001972 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001973 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001974 Region drawRegion(tr.transform(
1975 layer->visibleNonTransparentRegion));
1976 drawRegion.andSelf(bounds);
1977 if (!drawRegion.isEmpty()) {
1978 layersSortedByZ.add(layer);
1979 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001980 // Clear out the HWC layer if this layer was
1981 // previously visible, but no longer is
1982 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001983 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001984 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001985 // WM changes display->layerStack upon sleep/awake.
1986 // Here we make sure we delete the HWC layers even if
1987 // WM changed their layer stack.
1988 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001989 }
1990
1991 // If a layer is not going to get a release fence because
1992 // it is invisible, but it is also going to release its
1993 // old buffer, add it to the list of layers needing
1994 // fences.
1995 if (hwcLayerDestroyed) {
1996 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1997 mLayersWithQueuedFrames.cend(), layer);
1998 if (found != mLayersWithQueuedFrames.cend()) {
1999 layersNeedingFences.add(layer);
2000 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002001 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002002 });
2003 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002004 display->setVisibleLayersSortedByZ(layersSortedByZ);
2005 display->setLayersNeedingFences(layersNeedingFences);
2006 display->undefinedRegion.set(bounds);
2007 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2008 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002009 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002010 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002011}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002012
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002013// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002014// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002015// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002016// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002017// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002018// The returned HDR data space is one of
2019// - Dataspace::UNKNOWN
2020// - Dataspace::BT2020_HLG
2021// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002022Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2023 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07002024 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002025 *outHdrDataSpace = Dataspace::UNKNOWN;
2026
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002027 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002028 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002029 case Dataspace::V0_SCRGB:
2030 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002031 case Dataspace::BT2020:
2032 case Dataspace::BT2020_ITU:
2033 case Dataspace::BT2020_LINEAR:
2034 case Dataspace::DISPLAY_BT2020:
2035 bestDataSpace = Dataspace::DISPLAY_BT2020;
2036 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002037 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002038 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002039 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002040 case Dataspace::BT2020_PQ:
2041 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002042 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002043 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002044 case Dataspace::BT2020_HLG:
2045 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002046 // When there's mixed PQ content and HLG content, we set the HDR
2047 // data space to be BT2020_PQ and convert HLG to PQ.
2048 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2049 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002050 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002051 break;
2052 default:
2053 break;
2054 }
Romain Guy54f154a2017-10-24 21:40:32 +01002055 }
2056
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002057 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002058}
2059
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002060// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002061void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2062 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002063 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2064 *outMode = ColorMode::NATIVE;
2065 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002066 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002067 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002068 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002069
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002070 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002071 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002072
Peiyong Lindfde5112018-06-05 10:58:41 -07002073 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002074 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002075 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002076 if (isHdr) {
2077 bestDataSpace = hdrDataSpace;
2078 }
2079
Chia-I Wu0d711262018-05-21 15:19:35 -07002080 RenderIntent intent;
2081 switch (mDisplayColorSetting) {
2082 case DisplayColorSetting::MANAGED:
2083 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002084 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002085 break;
2086 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002087 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002088 break;
2089 default: // vendor display color setting
2090 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2091 break;
2092 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002093
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002094 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002095}
2096
David Sodmanfa9b2af2017-12-24 13:28:59 -08002097void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002098{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002099 bool dirty = !display->getDirtyRegion(false).isEmpty();
2100 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2101 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002102
David Sodmanfa9b2af2017-12-24 13:28:59 -08002103 // If nothing has changed (!dirty), don't recompose.
2104 // If something changed, but we don't currently have any visible layers,
2105 // and didn't when we last did a composition, then skip it this time.
2106 // The second rule does two things:
2107 // - When all layers are removed from a display, we'll emit one black
2108 // frame, then nothing more until we get new layers.
2109 // - When a display is created with a private layer stack, we won't
2110 // emit any black frames until a layer is added to the layer stack.
2111 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002112
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002113 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2114 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002115 mustRecompose ? "doing" : "skipping",
2116 dirty ? "+" : "-",
2117 empty ? "+" : "-",
2118 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002119
David Sodmanfa9b2af2017-12-24 13:28:59 -08002120 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002121
David Sodmanfa9b2af2017-12-24 13:28:59 -08002122 if (mustRecompose) {
2123 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002124 }
2125}
2126
David Sodmanfa9b2af2017-12-24 13:28:59 -08002127void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002128{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002129 if (!display->isPoweredOn()) {
2130 return;
David Sodman2b406362017-12-15 13:33:47 -08002131 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002132
Dominik Laskowski05275f12018-11-01 15:03:24 -07002133 status_t result = display->prepareFrame(getHwComposer(),
2134 getBE().mCompositionInfo[display->getDisplayToken()]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08002135 ALOGE_IF(result != NO_ERROR,
2136 "prepareFrame for display %d failed:"
2137 " %d (%s)",
2138 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002139}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002140
David Sodmanfa9b2af2017-12-24 13:28:59 -08002141void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002142 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002143 ALOGV("doComposition");
2144
David Sodmanfa9b2af2017-12-24 13:28:59 -08002145 if (display->isPoweredOn()) {
2146 // transform the dirty region into this screen's coordinate space
2147 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002148
David Sodmanfa9b2af2017-12-24 13:28:59 -08002149 // repaint the framebuffer (if needed)
2150 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002151
David Sodmanfa9b2af2017-12-24 13:28:59 -08002152 display->dirtyRegion.clear();
2153 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002154 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002155 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002156}
2157
David Sodmanfa9b2af2017-12-24 13:28:59 -08002158void SurfaceFlinger::postFrame()
2159{
2160 // |mStateLock| not needed as we are on the main thread
2161 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2162 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2163 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2164 logFrameStats();
2165 }
2166 }
2167}
2168
2169void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002170{
Mathias Agopian841cde52012-03-01 15:44:37 -08002171 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002172 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002173
David Sodmanfa9b2af2017-12-24 13:28:59 -08002174 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002175
David Sodmanfa9b2af2017-12-24 13:28:59 -08002176 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002177 const auto displayId = display->getId();
2178 if (displayId >= 0) {
2179 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002180 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002181 display->onSwapBuffersCompleted();
2182 display->makeCurrent();
David Sodman15094112018-10-11 09:39:37 -07002183 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002184 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002185
Chia-I Wu7b549592017-11-15 09:14:57 -08002186 // The layer buffer from the previous frame (if any) is released
2187 // by HWC only when the release fence from this frame (if any) is
2188 // signaled. Always get the release fence from HWC first.
David Sodman15094112018-10-11 09:39:37 -07002189 auto hwcLayer = layer->getHwcLayer(displayId);
2190 if (displayId >= 0) {
2191 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002192 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002193
2194 // If the layer was client composited in the previous frame, we
2195 // need to merge with the previous client target acquire fence.
2196 // Since we do not track that, always merge with the current
2197 // client target acquire fence when it is available, even though
2198 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002199 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002200 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002201 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002202 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002203
David Sodman15094112018-10-11 09:39:37 -07002204 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002205 }
Chia-I Wu83806892017-11-16 10:50:20 -08002206
2207 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002208 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002209 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002210 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002211 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002212 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002213 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002214 }
2215 }
2216
Dominik Laskowski7e045462018-05-30 13:02:02 -07002217 if (displayId >= 0) {
2218 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002219 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002220 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002221}
2222
Mathias Agopian87baae12012-07-31 12:38:26 -07002223void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002224{
Mathias Agopian841cde52012-03-01 15:44:37 -08002225 ATRACE_CALL();
2226
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002227 // here we keep a copy of the drawing state (that is the state that's
2228 // going to be overwritten by handleTransactionLocked()) outside of
2229 // mStateLock so that the side-effects of the State assignment
2230 // don't happen with mStateLock held (which can cause deadlocks).
2231 State drawingState(mDrawingState);
2232
Mathias Agopianca4d3602011-05-19 15:38:14 -07002233 Mutex::Autolock _l(mStateLock);
2234 const nsecs_t now = systemTime();
2235 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002236
Mathias Agopianca4d3602011-05-19 15:38:14 -07002237 // Here we're guaranteed that some transaction flags are set
2238 // so we can call handleTransactionLocked() unconditionally.
2239 // We call getTransactionFlags(), which will also clear the flags,
2240 // with mStateLock held to guarantee that mCurrentState won't change
2241 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002242
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002243 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002244 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002245 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002246
Mathias Agopianca4d3602011-05-19 15:38:14 -07002247 mLastTransactionTime = systemTime() - now;
2248 mDebugInTransaction = 0;
2249 invalidateHwcGeometry();
2250 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002251}
2252
Dominik Laskowski7e045462018-05-30 13:02:02 -07002253DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002254 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002255 // Figure out whether the event is for the primary display or an
2256 // external display by matching the Hwc display id against one for a
2257 // connected display. If we did not find a match, we then check what
2258 // displays are not already connected to determine the type. If we don't
2259 // have a connected primary display, we assume the new display is meant to
2260 // be the primary display, and then if we don't have an external display,
2261 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002262 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2263 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002264 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002265 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002266 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002267 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002268 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002269 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002270 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002271 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002272 return DisplayDevice::DISPLAY_EXTERNAL;
2273 }
2274
2275 return DisplayDevice::DISPLAY_ID_INVALID;
2276}
2277
Lloyd Piqueba04e622017-12-14 17:11:26 -08002278void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2279 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002280 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002281 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002282 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002283 continue;
2284 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002285
2286 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2287 ALOGE("External displays are not supported by the vr hardware composer.");
2288 continue;
2289 }
2290
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002291 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002292 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002293 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002294 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002295 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002296
2297 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002298 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002299 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002300 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002301 DisplayDeviceState info;
2302 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002303 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2304 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002305 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002306 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002307 mInterceptor->saveDisplayCreation(info);
2308 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002309 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002310 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002311
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002312 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002313 if (idx >= 0) {
2314 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002315 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002316 mCurrentState.displays.removeItemsAt(idx);
2317 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002318 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002319 }
2320
2321 processDisplayChangesLocked();
2322 }
2323
2324 mPendingHotplugEvents.clear();
2325}
2326
Lloyd Pique99d3da52018-01-22 17:48:03 -08002327sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002328 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002329 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002330 DisplayDeviceCreationArgs creationArgs(this, displayToken, state.type, displayId);
2331 creationArgs.isSecure = state.isSecure;
2332 creationArgs.displaySurface = dispSurface;
2333 creationArgs.hasWideColorGamut = false;
2334 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002335
Peiyong Lin13effd12018-07-24 17:01:47 -07002336 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002337 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002338 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002339 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002340 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002341 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002342
Dominik Laskowski7e045462018-05-30 13:02:02 -07002343 std::vector<RenderIntent> renderIntents =
2344 getHwComposer().getRenderIntents(displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002345 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002346 }
tangrobin6753a022018-08-10 10:58:54 +08002347 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002348
tangrobin6753a022018-08-10 10:58:54 +08002349 if (displayId >= 0) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002350 getHwComposer().getHdrCapabilities(displayId, &creationArgs.hdrCapabilities);
2351 creationArgs.supportedPerFrameMetadata =
2352 getHwComposer().getSupportedPerFrameMetadata(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002353 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002354
Lloyd Pique90c115d2018-09-18 21:39:42 -07002355 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002356 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002357 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002358
2359 /*
2360 * Create our display's surface
2361 */
Peiyong Lin833074a2018-08-28 11:53:54 -07002362 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002363 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002364 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002365 renderSurface->setNativeWindow(nativeWindow.get());
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002366 creationArgs.displayWidth = renderSurface->getWidth();
2367 creationArgs.displayHeight = renderSurface->getHeight();
2368 creationArgs.renderSurface = std::move(renderSurface);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002369
2370 // Make sure that composition can never be stalled by a virtual display
2371 // consumer that isn't processing buffers fast enough. We have to do this
2372 // in two places:
2373 // * Here, in case the display is composed entirely by HWC.
2374 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2375 // window's swap interval in eglMakeCurrent, so they'll override the
2376 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002377 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002378 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2379 }
2380
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002381 creationArgs.displayInstallOrientation = state.type == DisplayDevice::DISPLAY_PRIMARY
2382 ? primaryDisplayOrientation
2383 : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002384
Lloyd Pique99d3da52018-01-22 17:48:03 -08002385 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002386 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002387
Lloyd Pique90c115d2018-09-18 21:39:42 -07002388 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002389
2390 if (maxFrameBufferAcquiredBuffers >= 3) {
2391 nativeWindowSurface->preallocateBuffers();
2392 }
2393
2394 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002395 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002396 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002397 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002398 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002399 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002400 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002401 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002402 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002403 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002404 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002405 display->setLayerStack(state.layerStack);
2406 display->setProjection(state.orientation, state.viewport, state.frame);
2407 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002408
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002409 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002410}
2411
Lloyd Pique347200f2017-12-14 17:00:15 -08002412void SurfaceFlinger::processDisplayChangesLocked() {
2413 // here we take advantage of Vector's copy-on-write semantics to
2414 // improve performance by skipping the transaction entirely when
2415 // know that the lists are identical
2416 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2417 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2418 if (!curr.isIdenticalTo(draw)) {
2419 mVisibleRegionsDirty = true;
2420 const size_t cc = curr.size();
2421 size_t dc = draw.size();
2422
2423 // find the displays that were removed
2424 // (ie: in drawing state but not in current state)
2425 // also handle displays that changed
2426 // (ie: displays that are in both lists)
2427 for (size_t i = 0; i < dc;) {
2428 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2429 if (j < 0) {
2430 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002431 // Call makeCurrent() on the primary display so we can
2432 // be sure that nothing associated with this display
2433 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002434 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2435 defaultDisplay->makeCurrent();
2436 }
2437 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2438 display->disconnect(getHwComposer());
2439 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002440 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002441 if (mUseScheduler) {
2442 mScheduler->hotplugReceived(mAppConnectionHandle,
2443 EventThread::DisplayType::Primary, false);
2444 } else {
2445 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2446 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002447 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002448 if (mUseScheduler) {
2449 mScheduler->hotplugReceived(mAppConnectionHandle,
2450 EventThread::DisplayType::External, false);
2451 } else {
2452 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2453 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002454 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002455 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002456 } else {
2457 // this display is in both lists. see if something changed.
2458 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002459 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002460 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2461 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2462 if (state_binder != draw_binder) {
2463 // changing the surface is like destroying and
2464 // recreating the DisplayDevice, so we just remove it
2465 // from the drawing state, so that it get re-added
2466 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002467 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2468 display->disconnect(getHwComposer());
2469 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002470 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002471 mDrawingState.displays.removeItemsAt(i);
2472 dc--;
2473 // at this point we must loop to the next item
2474 continue;
2475 }
2476
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002477 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002478 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002479 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002480 }
2481 if ((state.orientation != draw[i].orientation) ||
2482 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002483 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002484 }
2485 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002486 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002487 }
2488 }
2489 }
2490 ++i;
2491 }
2492
2493 // find displays that were added
2494 // (ie: in current state but not in drawing state)
2495 for (size_t i = 0; i < cc; i++) {
2496 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2497 const DisplayDeviceState& state(curr[i]);
2498
2499 sp<DisplaySurface> dispSurface;
2500 sp<IGraphicBufferProducer> producer;
2501 sp<IGraphicBufferProducer> bqProducer;
2502 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002503 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002504
Dominik Laskowski7e045462018-05-30 13:02:02 -07002505 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002506 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002507 // Virtual displays without a surface are dormant:
2508 // they have external state (layer stack, projection,
2509 // etc.) but no internal state (i.e. a DisplayDevice).
2510 if (state.surface != nullptr) {
2511 // Allow VR composer to use virtual displays.
2512 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2513 int width = 0;
2514 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2515 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2516 int height = 0;
2517 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2518 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2519 int intFormat = 0;
2520 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2521 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002522 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002523
Dominik Laskowski7e045462018-05-30 13:02:02 -07002524 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2525 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002526 }
2527
2528 // TODO: Plumb requested format back up to consumer
2529
2530 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002531 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002532 bqProducer, bqConsumer,
2533 state.displayName);
2534
2535 dispSurface = vds;
2536 producer = vds;
2537 }
2538 } else {
2539 ALOGE_IF(state.surface != nullptr,
2540 "adding a supported display, but rendering "
2541 "surface is provided (%p), ignoring it",
2542 state.surface.get());
2543
Dominik Laskowski7e045462018-05-30 13:02:02 -07002544 displayId = state.type;
2545 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002546 producer = bqProducer;
2547 }
2548
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002549 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002550 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002551 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002552 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002553 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002554 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002555 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002556 if (mUseScheduler) {
2557 mScheduler->hotplugReceived(mAppConnectionHandle,
2558 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002559 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002560 } else {
2561 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2562 true);
2563 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002564 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002565 if (mUseScheduler) {
2566 mScheduler->hotplugReceived(mAppConnectionHandle,
2567 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002568 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002569 } else {
2570 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2571 true);
2572 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002573 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002574 }
2575 }
2576 }
2577 }
2578 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002579
2580 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002581}
2582
Mathias Agopian87baae12012-07-31 12:38:26 -07002583void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002584{
Dan Stoza7dde5992015-05-22 09:51:44 -07002585 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002586 mCurrentState.traverseInZOrder([](Layer* layer) {
2587 layer->notifyAvailableFrames();
2588 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002589
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002590 /*
2591 * Traversal of the children
2592 * (perform the transaction for each of them if needed)
2593 */
2594
Mathias Agopian3559b072012-08-15 13:46:03 -07002595 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002596 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002597 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002598 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002599
2600 const uint32_t flags = layer->doTransaction(0);
2601 if (flags & Layer::eVisibleRegion)
2602 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002603 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002604 }
2605
2606 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002607 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002608 */
2609
Mathias Agopiane57f2922012-08-09 16:29:12 -07002610 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002611 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002612 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002613 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002614
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002615 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002616 // The transform hint might have changed for some layers
2617 // (either because a display has changed, or because a layer
2618 // as changed).
2619 //
2620 // Walk through all the layers in currentLayers,
2621 // and update their transform hint.
2622 //
2623 // If a layer is visible only on a single display, then that
2624 // display is used to calculate the hint, otherwise we use the
2625 // default display.
2626 //
2627 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2628 // the hint is set before we acquire a buffer from the surface texture.
2629 //
2630 // NOTE: layer transactions have taken place already, so we use their
2631 // drawing state. However, SurfaceFlinger's own transaction has not
2632 // happened yet, so we must use the current state layer list
2633 // (soon to become the drawing state list).
2634 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002635 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002636 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002637 bool first = true;
2638 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002639 // NOTE: we rely on the fact that layers are sorted by
2640 // layerStack first (so we don't have to traverse the list
2641 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002642 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002643 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002644 currentlayerStack = layerStack;
2645 // figure out if this layerstack is mirrored
2646 // (more than one display) if so, pick the default display,
2647 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002648 hintDisplay = nullptr;
2649 for (const auto& [token, display] : mDisplays) {
2650 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2651 if (hintDisplay) {
2652 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002653 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002654 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002655 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002656 }
2657 }
2658 }
2659 }
Chet Haase91d25932013-04-11 15:24:55 -07002660
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002661 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002662 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2663 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002664
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002665 // could be null when this layer is using a layerStack
2666 // that is not visible on any display. Also can occur at
2667 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002668 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002669 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002670
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002671 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002672 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002673 if (hintDisplay) {
2674 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002675 }
Robert Carr2047fae2016-11-28 14:09:09 -08002676
2677 first = false;
2678 });
Mathias Agopian84300952012-11-21 16:02:13 -08002679 }
2680
2681
Mathias Agopian3559b072012-08-15 13:46:03 -07002682 /*
2683 * Perform our own transaction if needed
2684 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002685
2686 if (mLayersAdded) {
2687 mLayersAdded = false;
2688 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002689 mVisibleRegionsDirty = true;
2690 }
2691
2692 // some layers might have been removed, so
2693 // we need to update the regions they're exposing.
2694 if (mLayersRemoved) {
2695 mLayersRemoved = false;
2696 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002697 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002698 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002699 // this layer is not visible anymore
2700 // TODO: we could traverse the tree from front to back and
2701 // compute the actual visible region
2702 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002703 Region visibleReg;
2704 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002705 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002706 }
Robert Carr2047fae2016-11-28 14:09:09 -08002707 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002708 }
2709
2710 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002711
2712 updateCursorAsync();
2713}
2714
2715void SurfaceFlinger::updateCursorAsync()
2716{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002717 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002718 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002719 continue;
2720 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002721
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002722 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2723 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002724 }
2725 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002726}
2727
2728void SurfaceFlinger::commitTransaction()
2729{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002730 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002731 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002732 for (const auto& l : mLayersPendingRemoval) {
2733 recordBufferingStats(l->getName().string(),
2734 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002735
2736 // We need to release the HWC layers when the Layer is removed
2737 // from the current state otherwise the HWC layer just continues
2738 // showing at its last configured state until we eventually
2739 // abandon the buffer queue.
2740 if (l->isRemovedFromCurrentState()) {
2741 l->destroyAllHwcLayers();
2742 l->releasePendingBuffer(systemTime());
2743 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002744 }
2745 mLayersPendingRemoval.clear();
2746 }
2747
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002748 // If this transaction is part of a window animation then the next frame
2749 // we composite should be considered an animation as well.
2750 mAnimCompositionPending = mAnimTransactionPending;
2751
Mathias Agopian4fec8732012-06-29 14:12:52 -07002752 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002753 // clear the "changed" flags in current state
2754 mCurrentState.colorMatrixChanged = false;
2755
Robert Carr1f0a16a2016-10-24 16:27:39 -07002756 mDrawingState.traverseInZOrder([](Layer* layer) {
2757 layer->commitChildList();
2758 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002759 mTransactionPending = false;
2760 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002761 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002762}
2763
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002764void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2765 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002766 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002767 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002768
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002769 Region aboveOpaqueLayers;
2770 Region aboveCoveredLayers;
2771 Region dirty;
2772
Mathias Agopian87baae12012-07-31 12:38:26 -07002773 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002774
Robert Carr2047fae2016-11-28 14:09:09 -08002775 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002776 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002777 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002778
Jesse Hall01e29052013-02-19 16:13:35 -08002779 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002780 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002781 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002782 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002783
Mathias Agopianab028732010-03-16 16:41:46 -07002784 /*
2785 * opaqueRegion: area of a surface that is fully opaque.
2786 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002787 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002788
2789 /*
2790 * visibleRegion: area of a surface that is visible on screen
2791 * and not fully transparent. This is essentially the layer's
2792 * footprint minus the opaque regions above it.
2793 * Areas covered by a translucent surface are considered visible.
2794 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002795 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002796
2797 /*
2798 * coveredRegion: area of a surface that is covered by all
2799 * visible regions above it (which includes the translucent areas).
2800 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002801 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002802
Jesse Halla8026d22012-09-25 13:25:04 -07002803 /*
2804 * transparentRegion: area of a surface that is hinted to be completely
2805 * transparent. This is only used to tell when the layer has no visible
2806 * non-transparent regions and can be removed from the layer list. It
2807 * does not affect the visibleRegion of this layer or any layers
2808 * beneath it. The hint may not be correct if apps don't respect the
2809 * SurfaceView restrictions (which, sadly, some don't).
2810 */
2811 Region transparentRegion;
2812
Mathias Agopianab028732010-03-16 16:41:46 -07002813
2814 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002815 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002816 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002817 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002818 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002819 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002820 if (!visibleRegion.isEmpty()) {
2821 // Remove the transparent area from the visible region
2822 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002823 if (tr.preserveRects()) {
2824 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002825 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002826 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002827 // transformation too complex, can't do the
2828 // transparent region optimization.
2829 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002830 }
Mathias Agopianab028732010-03-16 16:41:46 -07002831 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002832
Mathias Agopianab028732010-03-16 16:41:46 -07002833 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002834 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002835 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002836 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002837 // the opaque region is the layer's footprint
2838 opaqueRegion = visibleRegion;
2839 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002840 }
2841 }
2842
Robert Carre5f4f692018-01-12 13:12:28 -08002843 if (visibleRegion.isEmpty()) {
2844 layer->clearVisibilityRegions();
2845 return;
2846 }
2847
Mathias Agopianab028732010-03-16 16:41:46 -07002848 // Clip the covered region to the visible region
2849 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2850
2851 // Update aboveCoveredLayers for next (lower) layer
2852 aboveCoveredLayers.orSelf(visibleRegion);
2853
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002854 // subtract the opaque region covered by the layers above us
2855 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002856
2857 // compute this layer's dirty region
2858 if (layer->contentDirty) {
2859 // we need to invalidate the whole region
2860 dirty = visibleRegion;
2861 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002862 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002863 layer->contentDirty = false;
2864 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002865 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002866 * the exposed region consists of two components:
2867 * 1) what's VISIBLE now and was COVERED before
2868 * 2) what's EXPOSED now less what was EXPOSED before
2869 *
2870 * note that (1) is conservative, we start with the whole
2871 * visible region but only keep what used to be covered by
2872 * something -- which mean it may have been exposed.
2873 *
2874 * (2) handles areas that were not covered by anything but got
2875 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002876 */
Mathias Agopianab028732010-03-16 16:41:46 -07002877 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002878 const Region oldVisibleRegion = layer->visibleRegion;
2879 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002880 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2881 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002882 }
2883 dirty.subtractSelf(aboveOpaqueLayers);
2884
2885 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002886 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002887
Mathias Agopianab028732010-03-16 16:41:46 -07002888 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002889 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002890
Jesse Halla8026d22012-09-25 13:25:04 -07002891 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002892 layer->setVisibleRegion(visibleRegion);
2893 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002894 layer->setVisibleNonTransparentRegion(
2895 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002896 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002897
Mathias Agopian87baae12012-07-31 12:38:26 -07002898 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002899}
2900
Chia-I Wuab0c3192017-08-01 11:29:00 -07002901void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002902 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002903 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2904 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002905 }
2906 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002907}
2908
Dan Stoza6b9454d2014-11-07 16:00:59 -08002909bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002910{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002911 ALOGV("handlePageFlip");
2912
Brian Andersond6927fb2016-07-23 23:37:30 -07002913 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002914
Mathias Agopian4fec8732012-06-29 14:12:52 -07002915 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002916 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002917 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002918
2919 // Store the set of layers that need updates. This set must not change as
2920 // buffers are being latched, as this could result in a deadlock.
2921 // Example: Two producers share the same command stream and:
2922 // 1.) Layer 0 is latched
2923 // 2.) Layer 0 gets a new frame
2924 // 2.) Layer 1 gets a new frame
2925 // 3.) Layer 1 is latched.
2926 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2927 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002928 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002929 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002930 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002931 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2932 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002933 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002934 } else {
2935 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002936 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002937 } else {
2938 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002939 }
Robert Carr2047fae2016-11-28 14:09:09 -08002940 });
2941
Dan Stoza9e56aa02015-11-02 13:00:03 -08002942 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri86770e52018-09-24 22:40:58 +00002943 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
Dan Stozaee44edd2015-03-23 15:50:23 -07002944 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002945 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002946 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002947 newDataLatched = true;
2948 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002949 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002950
Alec Mouri86770e52018-09-24 22:40:58 +00002951 // Clear the renderengine fence here...
2952 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
2953 // clear instead of sp::clear.
2954 getBE().flushFence = Fence::NO_FENCE;
2955
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002956 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002957
2958 // If we will need to wake up at some time in the future to deal with a
2959 // queued frame that shouldn't be displayed during this vsync period, wake
2960 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002961 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002962 signalLayerUpdate();
2963 }
2964
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002965 // enter boot animation on first buffer latch
2966 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2967 ALOGI("Enter boot animation");
2968 mBootStage = BootStage::BOOTANIMATION;
2969 }
2970
Dan Stoza6b9454d2014-11-07 16:00:59 -08002971 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002972 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002973}
2974
Mathias Agopianad456f92011-01-13 17:53:01 -08002975void SurfaceFlinger::invalidateHwcGeometry()
2976{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002977 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002978}
2979
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002980void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2981 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002982 // We only need to actually compose the display if:
2983 // 1) It is being handled by hardware composer, which may need this to
2984 // keep its virtual display state machine in sync, or
2985 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002986 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002987 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002988 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002989 return;
2990 }
2991
Dan Stoza9e56aa02015-11-02 13:00:03 -08002992 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002993 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002994
2995 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002996 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002997}
2998
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002999bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003000 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003001
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003002 const Region bounds(display->bounds());
3003 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003004 const auto displayId = display->getId();
3005 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003006 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003007
Peiyong Lind3788632018-09-18 16:01:31 -07003008 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003009 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003010 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003011
Dan Stoza9e56aa02015-11-02 13:00:03 -08003012 if (hasClientComposition) {
3013 ALOGV("hasClientComposition");
3014
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003015 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003016 if (display->hasWideColorGamut()) {
3017 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003018 }
3019 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003020 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003021 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003022
Dominik Laskowski7e045462018-05-30 13:02:02 -07003023 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003024 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3025 HWC2::Capability::SkipClientColorTransform);
3026
Peiyong Lind3788632018-09-18 16:01:31 -07003027 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003028 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3029 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003030 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003031 }
3032
Chia-I Wud49d6692018-06-27 07:17:41 +08003033 // The current enhanced saturation matrix is designed to enhance Display P3,
3034 // thus we only apply this matrix when the render intent is not colorimetric
3035 // and the output color space is Display P3.
3036 needsEnhancedColorMatrix =
3037 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3038 outputDataspace == Dataspace::DISPLAY_P3);
3039 if (needsEnhancedColorMatrix) {
3040 colorMatrix *= mEnhancedSaturationMatrix;
3041 }
3042
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003043 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003044 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003045 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003046 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003047
3048 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003049 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3050 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3051 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003052 }
3053 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003054 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003055
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003056 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003057 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003058 // when using overlays, we assume a fully transparent framebuffer
3059 // NOTE: we could reduce how much we need to clear, for instance
3060 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003061 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003062 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003063 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003064 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003065 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003066 // we're left with the letterbox region
3067 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003068 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003069
3070 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003071 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003072
Mathias Agopianb9494d52012-04-18 02:28:45 -07003073 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003074 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003075 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003076 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003077 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003078 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003079
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003080 const Rect& bounds = display->getBounds();
3081 const Rect& scissor = display->getScissor();
3082 if (scissor != bounds) {
3083 // scissor doesn't match the screen's dimensions, so we
3084 // need to clear everything outside of it and enable
3085 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003086
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003087 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003088 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003089 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003090 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003091
Mathias Agopian85d751c2012-08-29 16:59:24 -07003092 /*
3093 * and then, render the layers targeted at the framebuffer
3094 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003095
Dan Stoza9e56aa02015-11-02 13:00:03 -08003096 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003097 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003098 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003099 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003100 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003101 displayTransform.transform(layer->visibleRegion)));
3102 ALOGV("Layer: %s", layer->getName().string());
3103 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003104 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003105 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003106 case HWC2::Composition::Cursor:
3107 case HWC2::Composition::Device:
3108 case HWC2::Composition::Sideband:
3109 case HWC2::Composition::SolidColor: {
David Sodmanc1498e62018-09-12 14:36:26 -07003110 const Layer::State& state(layer->getDrawingState());
3111 if (layer->getClearClientTarget(displayId) && !firstLayer &&
3112 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3113 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003114 // never clear the very first layer since we're
3115 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003116 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003117 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003118 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003119 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003120 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003121 if (layer->hasColorTransform()) {
3122 mat4 tmpMatrix;
3123 if (applyColorMatrix) {
3124 tmpMatrix = mDrawingState.colorMatrix;
3125 }
3126 tmpMatrix *= layer->getColorTransform();
3127 if (needsEnhancedColorMatrix) {
3128 tmpMatrix *= mEnhancedSaturationMatrix;
3129 }
3130 getRenderEngine().setColorTransform(tmpMatrix);
3131 } else {
3132 getRenderEngine().setColorTransform(colorMatrix);
3133 }
David Sodmanc1498e62018-09-12 14:36:26 -07003134 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003135 break;
3136 }
3137 default:
3138 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003139 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003140 } else {
3141 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003142 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003143 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003144 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003145
Peiyong Lind3788632018-09-18 16:01:31 -07003146 // Clear color transform matrix at the end of the frame.
3147 getRenderEngine().setColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003148
Mathias Agopianf45c5102012-10-24 16:29:17 -07003149 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003150 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003151 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003152}
3153
Chia-I Wu28e3a252018-09-07 12:05:02 -07003154void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003155 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003156 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003157}
3158
Dan Stoza7d89d062015-04-30 13:29:25 -07003159status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003160 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003161 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003162 const sp<Layer>& lbc,
3163 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003164{
Dan Stoza7d89d062015-04-30 13:29:25 -07003165 // add this layer to the current state list
3166 {
3167 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003168 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003169 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3170 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003171 return NO_MEMORY;
3172 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003173 if (parent == nullptr) {
3174 mCurrentState.layersSortedByZ.add(lbc);
3175 } else {
Robert Carr2e102c92018-10-23 12:11:15 -07003176 if (parent->isRemovedFromCurrentState()) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003177 ALOGE("addClientLayer called with a removed parent");
3178 return NAME_NOT_FOUND;
3179 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003180 parent->addChild(lbc);
3181 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003182
Yiwei Zhang243b3782018-05-15 17:40:04 -07003183 if (gbc != nullptr) {
3184 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3185 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3186 mMaxGraphicBufferProducerListSize,
3187 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3188 mGraphicBufferProducerList.size(),
3189 mMaxGraphicBufferProducerListSize, mNumLayers);
3190 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003191 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003192 }
3193
Mathias Agopian96f08192010-06-02 23:28:45 -07003194 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003195 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003196
Dan Stoza7d89d062015-04-30 13:29:25 -07003197 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003198}
3199
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003200status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003201 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003202 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3203}
Robert Carr7f9b8992017-03-10 11:08:39 -08003204
Robert Carr2e102c92018-10-23 12:11:15 -07003205status_t SurfaceFlinger::removeLayerLocked(const Mutex& lock, const sp<Layer>& layer,
chaviwca27f252018-02-06 16:46:39 -08003206 bool topLevelOnly) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003207 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003208 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003209 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003210 if (topLevelOnly) {
3211 return NO_ERROR;
3212 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003213 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003214 } else {
3215 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003216 }
3217
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003218 layer->onRemovedFromCurrentState();
Robert Carr2e102c92018-10-23 12:11:15 -07003219
3220 markLayerPendingRemovalLocked(lock, layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003221 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003222}
3223
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003224uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003225 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003226}
3227
Mathias Agopian3f844832013-08-07 21:24:32 -07003228uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003229 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003230}
3231
Mathias Agopian3f844832013-08-07 21:24:32 -07003232uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003233 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003234}
3235
3236uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003237 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003238 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003239 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003240 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003241 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003242 }
3243 return old;
3244}
3245
chaviwca27f252018-02-06 16:46:39 -08003246bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3247 for (const ComposerState& state : states) {
3248 // Here we need to check that the interface we're given is indeed
3249 // one of our own. A malicious client could give us a nullptr
3250 // IInterface, or one of its own or even one of our own but a
3251 // different type. All these situations would cause us to crash.
3252 if (state.client == nullptr) {
3253 return true;
3254 }
3255
3256 sp<IBinder> binder = IInterface::asBinder(state.client);
3257 if (binder == nullptr) {
3258 return true;
3259 }
3260
3261 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3262 return true;
3263 }
3264 }
3265 return false;
3266}
3267
Mathias Agopian8b33f032012-07-24 20:43:54 -07003268void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003269 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003270 const Vector<DisplayState>& displays,
3271 uint32_t flags)
3272{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003273 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003274 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003275 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003276
chaviwca27f252018-02-06 16:46:39 -08003277 if (containsAnyInvalidClientState(states)) {
3278 return;
3279 }
3280
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003281 if (flags & eAnimation) {
3282 // For window updates that are part of an animation we must wait for
3283 // previous animation "frames" to be handled.
3284 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003285 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003286 if (CC_UNLIKELY(err != NO_ERROR)) {
3287 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003288 // caller after a few seconds.
3289 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3290 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003291 mAnimTransactionPending = false;
3292 break;
3293 }
3294 }
3295 }
3296
chaviwca27f252018-02-06 16:46:39 -08003297 for (const DisplayState& display : displays) {
3298 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003299 }
3300
Marissa Walle2ffb422018-10-12 11:33:52 -07003301 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003302 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003303 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003304 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003305 // If the state doesn't require a traversal and there are callbacks, send them now
3306 if (!(clientStateFlags & eTraversalNeeded)) {
3307 mTransactionCompletedThread.sendCallbacks();
3308 }
3309 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003310
3311 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3312 // as destroyed should only occur after setting all other states. This is to allow for a
3313 // child re-parent to happen before marking its original parent as destroyed (which would
3314 // then mark the child as destroyed).
3315 for (const ComposerState& state : states) {
3316 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003317 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003318
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003319 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3320 // anyway. This can be used as a flush mechanism for previous async transactions.
3321 // Empty animation transaction can be used to simulate back-pressure, so also force a
3322 // transaction for empty animation transactions.
3323 if (transactionFlags == 0 &&
3324 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003325 transactionFlags = eTransactionNeeded;
3326 }
3327
Mathias Agopian386aa982011-11-07 21:58:03 -08003328 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003329 if (mInterceptor->isEnabled()) {
3330 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003331 }
Irvel468051e2016-06-13 16:44:44 -07003332
Mathias Agopian386aa982011-11-07 21:58:03 -08003333 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003334 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3335 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003336 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003337
3338 // if this is a synchronous transaction, wait for it to take effect
3339 // before returning.
3340 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003341 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003342 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003343 if (flags & eAnimation) {
3344 mAnimTransactionPending = true;
3345 }
3346 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003347 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3348 if (CC_UNLIKELY(err != NO_ERROR)) {
3349 // just in case something goes wrong in SF, return to the
3350 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003351 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3352 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003353 break;
3354 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003355 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003356 }
3357}
3358
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003359uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3360 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3361 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003362
Mathias Agopiane57f2922012-08-09 16:29:12 -07003363 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003364 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3365
3366 const uint32_t what = s.what;
3367 if (what & DisplayState::eSurfaceChanged) {
3368 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3369 state.surface = s.surface;
3370 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003371 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003372 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003373 if (what & DisplayState::eLayerStackChanged) {
3374 if (state.layerStack != s.layerStack) {
3375 state.layerStack = s.layerStack;
3376 flags |= eDisplayTransactionNeeded;
3377 }
3378 }
3379 if (what & DisplayState::eDisplayProjectionChanged) {
3380 if (state.orientation != s.orientation) {
3381 state.orientation = s.orientation;
3382 flags |= eDisplayTransactionNeeded;
3383 }
3384 if (state.frame != s.frame) {
3385 state.frame = s.frame;
3386 flags |= eDisplayTransactionNeeded;
3387 }
3388 if (state.viewport != s.viewport) {
3389 state.viewport = s.viewport;
3390 flags |= eDisplayTransactionNeeded;
3391 }
3392 }
3393 if (what & DisplayState::eDisplaySizeChanged) {
3394 if (state.width != s.width) {
3395 state.width = s.width;
3396 flags |= eDisplayTransactionNeeded;
3397 }
3398 if (state.height != s.height) {
3399 state.height = s.height;
3400 flags |= eDisplayTransactionNeeded;
3401 }
3402 }
3403
Mathias Agopiane57f2922012-08-09 16:29:12 -07003404 return flags;
3405}
3406
Robert Carrd4ae7f32018-06-07 16:10:57 -07003407bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3408 IPCThreadState* ipc = IPCThreadState::self();
3409 const int pid = ipc->getCallingPid();
3410 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003411 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003412 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003413 return false;
3414 }
3415 return true;
3416}
3417
chaviwca27f252018-02-06 16:46:39 -08003418uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3419 const layer_state_t& s = composerState.state;
3420 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3421
Mathias Agopian13127d82013-03-05 17:47:11 -08003422 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003423 if (layer == nullptr) {
3424 return 0;
3425 }
3426
chaviw8b3871a2017-11-01 17:41:01 -07003427 uint32_t flags = 0;
3428
3429 const uint32_t what = s.what;
3430 bool geometryAppliesWithResize =
3431 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003432
3433 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3434 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003435 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003436 layer->pushPendingState();
3437 }
3438
chaviw8b3871a2017-11-01 17:41:01 -07003439 if (what & layer_state_t::ePositionChanged) {
3440 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3441 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003442 }
chaviw8b3871a2017-11-01 17:41:01 -07003443 }
3444 if (what & layer_state_t::eLayerChanged) {
3445 // NOTE: index needs to be calculated before we update the state
3446 const auto& p = layer->getParent();
3447 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003448 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003449 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003450 mCurrentState.layersSortedByZ.removeAt(idx);
3451 mCurrentState.layersSortedByZ.add(layer);
3452 // we need traversal (state changed)
3453 // AND transaction (list changed)
3454 flags |= eTransactionNeeded|eTraversalNeeded;
3455 }
chaviw8b3871a2017-11-01 17:41:01 -07003456 } else {
3457 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003458 flags |= eTransactionNeeded|eTraversalNeeded;
3459 }
3460 }
chaviw8b3871a2017-11-01 17:41:01 -07003461 }
3462 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003463 // NOTE: index needs to be calculated before we update the state
3464 const auto& p = layer->getParent();
3465 if (p == nullptr) {
3466 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3467 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3468 mCurrentState.layersSortedByZ.removeAt(idx);
3469 mCurrentState.layersSortedByZ.add(layer);
3470 // we need traversal (state changed)
3471 // AND transaction (list changed)
3472 flags |= eTransactionNeeded|eTraversalNeeded;
3473 }
3474 } else {
3475 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3476 flags |= eTransactionNeeded|eTraversalNeeded;
3477 }
chaviw8b3871a2017-11-01 17:41:01 -07003478 }
3479 }
3480 if (what & layer_state_t::eSizeChanged) {
3481 if (layer->setSize(s.w, s.h)) {
3482 flags |= eTraversalNeeded;
3483 }
3484 }
3485 if (what & layer_state_t::eAlphaChanged) {
3486 if (layer->setAlpha(s.alpha))
3487 flags |= eTraversalNeeded;
3488 }
3489 if (what & layer_state_t::eColorChanged) {
3490 if (layer->setColor(s.color))
3491 flags |= eTraversalNeeded;
3492 }
Peiyong Lind3788632018-09-18 16:01:31 -07003493 if (what & layer_state_t::eColorTransformChanged) {
3494 if (layer->setColorTransform(s.colorTransform)) {
3495 flags |= eTraversalNeeded;
3496 }
3497 }
chaviw8b3871a2017-11-01 17:41:01 -07003498 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003499 // TODO: b/109894387
3500 //
3501 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3502 // rotation. To see the problem observe that if we have a square parent, and a child
3503 // of the same size, then we rotate the child 45 degrees around it's center, the child
3504 // must now be cropped to a non rectangular 8 sided region.
3505 //
3506 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3507 // private API, and the WindowManager only uses rotation in one case, which is on a top
3508 // level layer in which cropping is not an issue.
3509 //
3510 // However given that abuse of rotation matrices could lead to surfaces extending outside
3511 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3512 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3513 // transformations.
3514 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003515 flags |= eTraversalNeeded;
3516 }
3517 if (what & layer_state_t::eTransparentRegionChanged) {
3518 if (layer->setTransparentRegionHint(s.transparentRegion))
3519 flags |= eTraversalNeeded;
3520 }
3521 if (what & layer_state_t::eFlagsChanged) {
3522 if (layer->setFlags(s.flags, s.mask))
3523 flags |= eTraversalNeeded;
3524 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003525 if (what & layer_state_t::eCropChanged_legacy) {
3526 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003527 flags |= eTraversalNeeded;
3528 }
chaviw8b3871a2017-11-01 17:41:01 -07003529 if (what & layer_state_t::eLayerStackChanged) {
3530 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3531 // We only allow setting layer stacks for top level layers,
3532 // everything else inherits layer stack from its parent.
3533 if (layer->hasParent()) {
3534 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3535 layer->getName().string());
3536 } else if (idx < 0) {
3537 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3538 "that also does not appear in the top level layer list. Something"
3539 " has gone wrong.", layer->getName().string());
3540 } else if (layer->setLayerStack(s.layerStack)) {
3541 mCurrentState.layersSortedByZ.removeAt(idx);
3542 mCurrentState.layersSortedByZ.add(layer);
3543 // we need traversal (state changed)
3544 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003545 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003546 }
3547 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003548 if (what & layer_state_t::eDeferTransaction_legacy) {
3549 if (s.barrierHandle_legacy != nullptr) {
3550 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3551 } else if (s.barrierGbp_legacy != nullptr) {
3552 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003553 if (authenticateSurfaceTextureLocked(gbp)) {
3554 const auto& otherLayer =
3555 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003556 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003557 } else {
3558 ALOGE("Attempt to defer transaction to to an"
3559 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003560 }
3561 }
chaviw8b3871a2017-11-01 17:41:01 -07003562 // We don't trigger a traversal here because if no other state is
3563 // changed, we don't want this to cause any more work
3564 }
3565 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003566 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003567 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003568 if (!hadParent) {
3569 mCurrentState.layersSortedByZ.remove(layer);
3570 }
chaviw8b3871a2017-11-01 17:41:01 -07003571 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003572 }
chaviw8b3871a2017-11-01 17:41:01 -07003573 }
3574 if (what & layer_state_t::eReparentChildren) {
3575 if (layer->reparentChildren(s.reparentHandle)) {
3576 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003577 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003578 }
chaviw8b3871a2017-11-01 17:41:01 -07003579 if (what & layer_state_t::eDetachChildren) {
3580 layer->detachChildren();
3581 }
3582 if (what & layer_state_t::eOverrideScalingModeChanged) {
3583 layer->setOverrideScalingMode(s.overrideScalingMode);
3584 // We don't trigger a traversal here because if no other state is
3585 // changed, we don't want this to cause any more work
3586 }
Marissa Wall61c58622018-07-18 10:12:20 -07003587 if (what & layer_state_t::eTransformChanged) {
3588 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3589 }
3590 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3591 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3592 flags |= eTraversalNeeded;
3593 }
3594 if (what & layer_state_t::eCropChanged) {
3595 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3596 }
3597 if (what & layer_state_t::eBufferChanged) {
3598 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3599 }
3600 if (what & layer_state_t::eAcquireFenceChanged) {
3601 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3602 }
3603 if (what & layer_state_t::eDataspaceChanged) {
3604 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3605 }
3606 if (what & layer_state_t::eHdrMetadataChanged) {
3607 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3608 }
3609 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3610 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3611 }
3612 if (what & layer_state_t::eApiChanged) {
3613 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3614 }
3615 if (what & layer_state_t::eSidebandStreamChanged) {
3616 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3617 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003618
3619 std::vector<sp<CallbackHandle>> callbackHandles;
3620 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3621 mTransactionCompletedThread.run();
3622 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3623 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3624 }
3625 }
3626 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3627 // Do not put anything that updates layer state or modifies flags after
3628 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003629 return flags;
3630}
3631
chaviwca27f252018-02-06 16:46:39 -08003632void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3633 const layer_state_t& state = composerState.state;
3634 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3635
3636 sp<Layer> layer(client->getLayerUser(state.surface));
3637 if (layer == nullptr) {
3638 return;
3639 }
3640
chaviwca27f252018-02-06 16:46:39 -08003641 if (state.what & layer_state_t::eDestroySurface) {
3642 removeLayerLocked(mStateLock, layer);
3643 }
3644}
3645
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003646status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003647 const String8& name,
3648 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003649 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003650 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003651 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003652{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003653 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003654 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003655 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003656 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003657 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003658
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003659 status_t result = NO_ERROR;
3660
3661 sp<Layer> layer;
3662
Cody Northropbc755282017-03-31 12:00:08 -06003663 String8 uniqueName = getUniqueLayerName(name);
3664
Mathias Agopian3165cc22012-08-08 19:42:09 -07003665 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003666 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003667 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3668 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003669
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003670 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003671 case ISurfaceComposerClient::eFXSurfaceBufferState:
3672 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3673 break;
chaviw13fdc492017-06-27 12:40:18 -07003674 case ISurfaceComposerClient::eFXSurfaceColor:
3675 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003676 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003677 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003678 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003679 case ISurfaceComposerClient::eFXSurfaceContainer:
3680 result = createContainerLayer(client,
3681 uniqueName, w, h, flags,
3682 handle, &layer);
3683 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003684 default:
3685 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003686 break;
3687 }
3688
Dan Stoza7d89d062015-04-30 13:29:25 -07003689 if (result != NO_ERROR) {
3690 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003691 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003692
Chia-I Wuab0c3192017-08-01 11:29:00 -07003693 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3694 // TODO b/64227542
3695 if (windowType == 441731) {
3696 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3697 layer->setPrimaryDisplayOnly();
3698 }
3699
Albert Chaulk479c60c2017-01-27 14:21:34 -05003700 layer->setInfo(windowType, ownerUid);
3701
Robert Carr1f0a16a2016-10-24 16:27:39 -07003702 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003703 if (result != NO_ERROR) {
3704 return result;
3705 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003706 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003707
3708 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003709 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003710}
3711
Cody Northropbc755282017-03-31 12:00:08 -06003712String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3713{
3714 bool matchFound = true;
3715 uint32_t dupeCounter = 0;
3716
3717 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3718 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3719
Dan Stoza436ccf32018-06-21 12:10:12 -07003720 // Grab the state lock since we're accessing mCurrentState
3721 Mutex::Autolock lock(mStateLock);
3722
Cody Northropbc755282017-03-31 12:00:08 -06003723 // Loop over layers until we're sure there is no matching name
3724 while (matchFound) {
3725 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003726 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003727 if (layer->getName() == uniqueName) {
3728 matchFound = true;
3729 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3730 }
3731 });
3732 }
3733
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003734 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3735 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003736
3737 return uniqueName;
3738}
3739
Marissa Wallfd668622018-05-10 10:21:13 -07003740status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3741 uint32_t w, uint32_t h, uint32_t flags,
3742 PixelFormat& format, sp<IBinder>* handle,
3743 sp<IGraphicBufferProducer>* gbp,
3744 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003745 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003746 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003747 case PIXEL_FORMAT_TRANSPARENT:
3748 case PIXEL_FORMAT_TRANSLUCENT:
3749 format = PIXEL_FORMAT_RGBA_8888;
3750 break;
3751 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003752 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003753 break;
3754 }
3755
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003756 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003757 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003758 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003759 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003760 *handle = layer->getHandle();
3761 *gbp = layer->getProducer();
3762 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003763 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003764
Marissa Wallfd668622018-05-10 10:21:13 -07003765 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003766 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003767}
3768
Marissa Wall61c58622018-07-18 10:12:20 -07003769status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3770 uint32_t w, uint32_t h, uint32_t flags,
3771 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003772 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003773 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003774 *handle = layer->getHandle();
3775 *outLayer = layer;
3776
3777 return NO_ERROR;
3778}
3779
chaviw13fdc492017-06-27 12:40:18 -07003780status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003781 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003782 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003783{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003784 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003785 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003786 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003787}
3788
Robert Carr6b3f6c52018-08-13 13:05:17 -07003789status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3790 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3791 sp<IBinder>* handle, sp<Layer>* outLayer)
3792{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003793 *outLayer =
3794 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003795 *handle = (*outLayer)->getHandle();
3796 return NO_ERROR;
3797}
3798
3799
Mathias Agopianac9fa422013-02-11 16:40:36 -08003800status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003801{
Robert Carr9524cb32017-02-13 11:32:32 -08003802 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003803 status_t err = NO_ERROR;
3804 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003805 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003806 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003807 err = removeLayer(l);
3808 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3809 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003810 }
3811 return err;
3812}
3813
Robert Carr2e102c92018-10-23 12:11:15 -07003814void SurfaceFlinger::markLayerPendingRemovalLocked(const Mutex&, const sp<Layer>& layer) {
3815 mLayersPendingRemoval.add(layer);
3816 mLayersRemoved = true;
3817 setTransactionFlags(eTransactionNeeded);
3818}
3819
3820void SurfaceFlinger::onHandleDestroyed(const sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003821{
Robert Carr2e102c92018-10-23 12:11:15 -07003822 Mutex::Autolock lock(mStateLock);
3823 markLayerPendingRemovalLocked(mStateLock, layer);
Rob Carr4bba3702018-10-08 21:53:30 +00003824}
3825
Mathias Agopianb60314a2012-04-10 22:09:54 -07003826// ---------------------------------------------------------------------------
3827
Andy McFadden13a082e2012-08-24 10:16:42 -07003828void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003829 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3830 if (!displayToken) return;
3831
Jesse Hall01e29052013-02-19 16:13:35 -08003832 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003833 Vector<ComposerState> state;
3834 Vector<DisplayState> displays;
3835 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003836 d.what = DisplayState::eDisplayProjectionChanged |
3837 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003838 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003839 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003840 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003841 d.frame.makeInvalid();
3842 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003843 d.width = 0;
3844 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003845 displays.add(d);
3846 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003847
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003848 const auto display = getDisplayDevice(displayToken);
3849 if (!display) return;
3850
3851 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3852
3853 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003854 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003855 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003856
Brian Andersond0010582017-03-07 13:20:31 -08003857 // Use phase of 0 since phase is not known.
3858 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07003859 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
3860 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003861}
3862
3863void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003864 // Async since we may be called from the main thread.
3865 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003866}
3867
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003868void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3869 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003870 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003871 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003872
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003873 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003874 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003875 return;
3876 }
3877
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003878 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003879 ALOGW("Trying to set power mode for virtual display");
3880 return;
3881 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003882
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003883 display->setPowerMode(mode);
3884
Lloyd Pique4dccc412018-01-22 17:21:36 -08003885 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003886 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003887 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003888 if (idx < 0) {
3889 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3890 return;
3891 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003892 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003893 }
3894
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003895 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003896 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003897 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003898 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003899 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003900 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003901 if (mUseScheduler) {
3902 mScheduler->onScreenAcquired(mAppConnectionHandle);
3903 } else {
3904 mEventThread->onScreenAcquired();
3905 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07003906 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003907 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003908
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003909 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003910 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003911 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003912
3913 struct sched_param param = {0};
3914 param.sched_priority = 1;
3915 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3916 ALOGW("Couldn't set SCHED_FIFO on display on");
3917 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003918 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003919 // Turn off the display
3920 struct sched_param param = {0};
3921 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3922 ALOGW("Couldn't set SCHED_OTHER on display off");
3923 }
3924
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003925 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07003926 if (mUseScheduler) {
3927 mScheduler->disableHardwareVsync(true);
3928 } else {
3929 disableHardwareVsync(true); // also cancels any in-progress resync
3930 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07003931 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003932 if (mUseScheduler) {
3933 mScheduler->onScreenReleased(mAppConnectionHandle);
3934 } else {
3935 mEventThread->onScreenReleased();
3936 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07003937 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003938
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003939 getHwComposer().setPowerMode(type, mode);
3940 mVisibleRegionsDirty = true;
3941 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003942 } else if (mode == HWC_POWER_MODE_DOZE ||
3943 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003944 // Update display while dozing
3945 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003946 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003947 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003948 if (mUseScheduler) {
3949 mScheduler->onScreenAcquired(mAppConnectionHandle);
3950 } else {
3951 mEventThread->onScreenAcquired();
3952 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003953 resyncToHardwareVsync(true);
3954 }
3955 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3956 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003957 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07003958 if (mUseScheduler) {
3959 mScheduler->disableHardwareVsync(true);
3960 } else {
3961 disableHardwareVsync(true); // also cancels any in-progress resync
3962 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003963 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003964 if (mUseScheduler) {
3965 mScheduler->onScreenReleased(mAppConnectionHandle);
3966 } else {
3967 mEventThread->onScreenReleased();
3968 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003969 }
3970 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003971 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003972 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003973 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003974 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003975
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003976 if (display->isPrimary()) {
3977 mTimeStats.setPowerMode(mode);
3978 }
3979
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003980 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003981}
3982
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003983void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003984 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003985 const auto display = getDisplayDevice(displayToken);
3986 if (!display) {
3987 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3988 displayToken.get());
3989 } else if (display->isVirtual()) {
3990 ALOGW("Attempt to set power mode %d for virtual display", mode);
3991 } else {
3992 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003993 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003994 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003995}
3996
3997// ---------------------------------------------------------------------------
3998
Lloyd Pique755e3192018-01-31 16:46:15 -08003999status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4000 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004001 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004002
Mathias Agopianbd115332013-04-18 16:41:04 -07004003 IPCThreadState* ipc = IPCThreadState::self();
4004 const int pid = ipc->getCallingPid();
4005 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004006
Mathias Agopianbd115332013-04-18 16:41:04 -07004007 if ((uid != AID_SHELL) &&
4008 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004009 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004010 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004011 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004012 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004013 // (this would indicate SF is stuck, but we want to be able to
4014 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004015 status_t err = mStateLock.timedLock(s2ns(1));
4016 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004017 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004018 result.appendFormat(
4019 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4020 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004021 }
4022
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004023 bool dumpAll = true;
4024 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004025 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004026
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004027 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004028 if ((index < numArgs) &&
4029 (args[index] == String16("--list"))) {
4030 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004031 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004032 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004033 }
4034
4035 if ((index < numArgs) &&
4036 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004037 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004038 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004039 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004040 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004041
4042 if ((index < numArgs) &&
4043 (args[index] == String16("--latency-clear"))) {
4044 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004045 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004046 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004047 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004048
4049 if ((index < numArgs) &&
4050 (args[index] == String16("--dispsync"))) {
4051 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004052 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004053 dumpAll = false;
4054 }
Dan Stozab90cf072015-03-05 11:05:59 -08004055
4056 if ((index < numArgs) &&
4057 (args[index] == String16("--static-screen"))) {
4058 index++;
4059 dumpStaticScreenStats(result);
4060 dumpAll = false;
4061 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004062
4063 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004064 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004065 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004066 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004067 dumpAll = false;
4068 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004069
4070 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4071 index++;
4072 dumpWideColorInfo(result);
4073 dumpAll = false;
4074 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004075
4076 if ((index < numArgs) &&
4077 (args[index] == String16("--enable-layer-stats"))) {
4078 index++;
4079 mLayerStats.enable();
4080 dumpAll = false;
4081 }
4082
4083 if ((index < numArgs) &&
4084 (args[index] == String16("--disable-layer-stats"))) {
4085 index++;
4086 mLayerStats.disable();
4087 dumpAll = false;
4088 }
4089
4090 if ((index < numArgs) &&
4091 (args[index] == String16("--clear-layer-stats"))) {
4092 index++;
4093 mLayerStats.clear();
4094 dumpAll = false;
4095 }
4096
4097 if ((index < numArgs) &&
4098 (args[index] == String16("--dump-layer-stats"))) {
4099 index++;
4100 mLayerStats.dump(result);
4101 dumpAll = false;
4102 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004103
4104 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004105 (args[index] == String16("--frame-composition"))) {
4106 index++;
4107 dumpFrameCompositionInfo(result);
4108 dumpAll = false;
4109 }
4110
4111 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004112 (args[index] == String16("--display-identification"))) {
4113 index++;
4114 dumpDisplayIdentificationData(result);
4115 dumpAll = false;
4116 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004117
4118 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4119 index++;
4120 mTimeStats.parseArgs(asProto, args, index, result);
4121 dumpAll = false;
4122 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004123 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004124
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004125 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004126 if (asProto) {
4127 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4128 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4129 } else {
4130 dumpAllLocked(args, index, result);
4131 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004132 }
4133
Mathias Agopian9795c422009-08-26 16:36:26 -07004134 if (locked) {
4135 mStateLock.unlock();
4136 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004137 }
4138 write(fd, result.string(), result.size());
4139 return NO_ERROR;
4140}
4141
Dan Stozac7014012014-02-14 15:03:43 -08004142void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4143 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004144{
Robert Carr2047fae2016-11-28 14:09:09 -08004145 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004146 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004147 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004148}
4149
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004150void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004151 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004152{
4153 String8 name;
4154 if (index < args.size()) {
4155 name = String8(args[index]);
4156 index++;
4157 }
4158
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004159 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4160 getHwComposer().isConnected(displayId)) {
4161 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4162 const nsecs_t period = activeConfig->getVsyncPeriod();
4163 result.appendFormat("%" PRId64 "\n", period);
4164 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004165
4166 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004167 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004168 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004169 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004170 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004171 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004172 }
Robert Carr2047fae2016-11-28 14:09:09 -08004173 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004174 }
4175}
4176
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004177void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004178 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004179{
4180 String8 name;
4181 if (index < args.size()) {
4182 name = String8(args[index]);
4183 index++;
4184 }
4185
Robert Carr2047fae2016-11-28 14:09:09 -08004186 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004187 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004188 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004189 }
Robert Carr2047fae2016-11-28 14:09:09 -08004190 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004191
Svetoslavd85084b2014-03-20 10:28:31 -07004192 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004193}
4194
Jamie Gennis6547ff42013-07-16 20:12:42 -07004195// This should only be called from the main thread. Otherwise it would need
4196// the lock and should use mCurrentState rather than mDrawingState.
4197void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004198 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004199 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004200 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004201
4202 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4203}
4204
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004205void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004206{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004207 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004208
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004209 if (isLayerTripleBufferingDisabled())
4210 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004211
4212 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004213 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004214 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004215 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004216 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4217 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004218 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004219}
4220
Dan Stozab90cf072015-03-05 11:05:59 -08004221void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4222{
4223 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004224 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4225 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004226 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004227 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004228 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4229 b + 1, bucketTimeSec, percent);
4230 }
David Sodman4a36e932017-11-07 14:29:47 -08004231 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004232 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004233 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004234 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004235 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004236}
4237
Dan Stozae77c7662016-05-13 11:37:28 -07004238void SurfaceFlinger::recordBufferingStats(const char* layerName,
4239 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004240 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4241 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004242 for (const auto& segment : history) {
4243 if (!segment.usedThirdBuffer) {
4244 stats.twoBufferTime += segment.totalTime;
4245 }
4246 if (segment.occupancyAverage < 1.0f) {
4247 stats.doubleBufferedTime += segment.totalTime;
4248 } else if (segment.occupancyAverage < 2.0f) {
4249 stats.tripleBufferedTime += segment.totalTime;
4250 }
4251 ++stats.numSegments;
4252 stats.totalTime += segment.totalTime;
4253 }
4254}
4255
Brian Andersond6927fb2016-07-23 23:37:30 -07004256void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4257 result.appendFormat("Layer frame timestamps:\n");
4258
4259 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4260 const size_t count = currentLayers.size();
4261 for (size_t i=0 ; i<count ; i++) {
4262 currentLayers[i]->dumpFrameEvents(result);
4263 }
4264}
4265
Dan Stozae77c7662016-05-13 11:37:28 -07004266void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4267 result.append("Buffering stats:\n");
4268 result.append(" [Layer name] <Active time> <Two buffer> "
4269 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004270 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004271 typedef std::tuple<std::string, float, float, float> BufferTuple;
4272 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004273 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004274 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004275 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004276 if (stats.numSegments == 0) {
4277 continue;
4278 }
4279 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4280 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4281 stats.totalTime;
4282 float doubleBufferRatio = static_cast<float>(
4283 stats.doubleBufferedTime) / stats.totalTime;
4284 float tripleBufferRatio = static_cast<float>(
4285 stats.tripleBufferedTime) / stats.totalTime;
4286 sorted.insert({activeTime, {name, twoBufferRatio,
4287 doubleBufferRatio, tripleBufferRatio}});
4288 }
4289 for (const auto& sortedPair : sorted) {
4290 float activeTime = sortedPair.first;
4291 const BufferTuple& values = sortedPair.second;
4292 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4293 std::get<0>(values).c_str(), activeTime,
4294 std::get<1>(values), std::get<2>(values),
4295 std::get<3>(values));
4296 }
4297 result.append("\n");
4298}
4299
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004300void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004301 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004302 const int32_t displayId = display->getId();
4303 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4304 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004305 continue;
4306 }
4307
Dominik Laskowski7e045462018-05-30 13:02:02 -07004308 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004309 uint8_t port;
4310 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004311 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004312 result.append("no identification data\n");
4313 continue;
4314 }
4315
4316 if (!isEdid(data)) {
4317 result.append("unknown identification data: ");
4318 for (uint8_t byte : data) {
4319 result.appendFormat("%x ", byte);
4320 }
4321 result.append("\n");
4322 continue;
4323 }
4324
4325 const auto edid = parseEdid(data);
4326 if (!edid) {
4327 result.append("invalid EDID: ");
4328 for (uint8_t byte : data) {
4329 result.appendFormat("%x ", byte);
4330 }
4331 result.append("\n");
4332 continue;
4333 }
4334
4335 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4336 result.append(edid->displayName.data(), edid->displayName.length());
4337 result.append("\"\n");
4338 }
4339 result.append("\n");
4340}
4341
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004342void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004343 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4344 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004345 result.appendFormat("DisplayColorSetting: %s\n",
4346 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004347
4348 // TODO: print out if wide-color mode is active or not
4349
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004350 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004351 const int32_t displayId = display->getId();
4352 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004353 continue;
4354 }
4355
Dominik Laskowski7e045462018-05-30 13:02:02 -07004356 result.appendFormat("Display %d color modes:\n", displayId);
4357 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004358 for (auto&& mode : modes) {
4359 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4360 }
4361
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004362 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004363 result.appendFormat(" Current color mode: %s (%d)\n",
4364 decodeColorMode(currentMode).c_str(), currentMode);
4365 }
4366 result.append("\n");
4367}
4368
David Sodman7e4ae112018-02-09 15:02:28 -08004369void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4370 std::string stringResult;
4371
4372 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004373 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4374 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004375 continue;
4376 }
4377
Dominik Laskowski05275f12018-11-01 15:03:24 -07004378 const auto& compositionInfoList = it->second;
4379 stringResult += base::StringPrintf("%s\n", display->getDebugName().c_str());
David Sodman7e4ae112018-02-09 15:02:28 -08004380 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4381 for (const auto& compositionInfo : compositionInfoList) {
4382 compositionInfo.dump(stringResult, nullptr);
4383 stringResult += base::StringPrintf("\n");
4384 }
4385 }
4386
4387 result.append(stringResult.c_str());
4388}
4389
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004390LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004391 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004392 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4393 const State& state = useDrawing ? mDrawingState : mCurrentState;
4394 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004395 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004396 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004397 });
4398
4399 return layersProto;
4400}
4401
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004402LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004403 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004404
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004405 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004406 resolution->set_w(display.getWidth());
4407 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004408
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004409 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4410 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4411 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004412
Dominik Laskowski7e045462018-05-30 13:02:02 -07004413 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004414 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004415 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004416 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004417 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004418 }
4419 });
4420
4421 return layersProto;
4422}
4423
Mathias Agopian74d211a2013-04-22 16:55:35 +02004424void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4425 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004426{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004427 bool colorize = false;
4428 if (index < args.size()
4429 && (args[index] == String16("--color"))) {
4430 colorize = true;
4431 index++;
4432 }
4433
4434 Colorizer colorizer(colorize);
4435
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004436 // figure out if we're stuck somewhere
4437 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004438 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004439 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4440
4441 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004442 * Dump library configuration.
4443 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004444
4445 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004446 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004447 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004448 appendSfConfigString(result);
4449 appendUiConfigString(result);
4450 appendGuiConfigString(result);
4451 result.append("\n");
4452
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004453 result.append("\nDisplay identification data:\n");
4454 dumpDisplayIdentificationData(result);
4455
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004456 result.append("\nWide-Color information:\n");
4457 dumpWideColorInfo(result);
4458
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004459 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004460 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004461 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004462 result.append(SyncFeatures::getInstance().toString());
4463 result.append("\n");
4464
Andy McFadden41d67d72014-04-25 16:58:34 -07004465 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004466 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004467 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004468
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004469 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4470 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004471 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4472 getHwComposer().isConnected(displayId)) {
4473 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004474 result.appendFormat("Display %d: "
4475 "app phase %" PRId64 " ns, "
4476 "sf phase %" PRId64 " ns, "
4477 "early app phase %" PRId64 " ns, "
4478 "early sf phase %" PRId64 " ns, "
4479 "early app gl phase %" PRId64 " ns, "
4480 "early sf gl phase %" PRId64 " ns, "
4481 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4482 displayId,
4483 vsyncPhaseOffsetNs,
4484 sfVsyncPhaseOffsetNs,
4485 appEarlyOffset,
4486 sfEarlyOffset,
4487 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004488 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004489 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004490 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004491 result.append("\n");
4492
Dan Stozab90cf072015-03-05 11:05:59 -08004493 // Dump static screen stats
4494 result.append("\n");
4495 dumpStaticScreenStats(result);
4496 result.append("\n");
4497
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004498 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4499
Dan Stozae77c7662016-05-13 11:37:28 -07004500 dumpBufferingStats(result);
4501
Andy McFadden4803b742012-09-24 19:07:20 -07004502 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004503 * Dump the visible layer list
4504 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004505 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004506 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004507 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4508 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004509 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004510
Chia-I Wu2f884132018-09-13 15:17:58 -07004511 {
4512 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4513 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4514 result.append(LayerProtoParser::layerTreeToString(layerTree).c_str());
4515 result.append("\n");
4516 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004517
David Sodman7e4ae112018-02-09 15:02:28 -08004518 result.append("\nFrame-Composition information:\n");
4519 dumpFrameCompositionInfo(result);
4520 result.append("\n");
4521
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004522 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004523 * Dump Display state
4524 */
4525
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004526 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004527 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004528 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004529 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004530 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004531 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004532 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004533
4534 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004535 * Dump SurfaceFlinger global state
4536 */
4537
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004538 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004539 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004540 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004541
Mathias Agopian888c8222012-08-04 21:10:38 -07004542 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004543 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004544
David Sodmanbc815282017-11-05 18:57:52 -08004545 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004546
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004547 if (display) {
4548 display->undefinedRegion.dump(result, "undefinedRegion");
4549 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4550 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004551 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004552 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004553 " gpu_to_cpu_unsupported : %d\n",
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004554 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004555
4556 if (display) {
4557 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4558 result.appendFormat(" refresh-rate : %f fps\n"
4559 " x-dpi : %f\n"
4560 " y-dpi : %f\n",
4561 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4562 activeConfig->getDpiY());
4563 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004564
Mathias Agopian74d211a2013-04-22 16:55:35 +02004565 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004566 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004567
Ana Krulec98b5b242018-08-10 15:03:23 -07004568 result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004569 /*
4570 * VSYNC state
4571 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004572 if (mUseScheduler) {
4573 mScheduler->dump(mAppConnectionHandle, result);
4574 } else {
4575 mEventThread->dump(result);
4576 }
Dan Stozae22aec72016-08-01 13:20:59 -07004577 result.append("\n");
4578
4579 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004580 * Tracing state
4581 */
4582 mTracing.dump(result);
4583 result.append("\n");
4584
4585 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004586 * HWC layer minidump
4587 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004588 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004589 const int32_t displayId = display->getId();
4590 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004591 continue;
4592 }
4593
Dominik Laskowski7e045462018-05-30 13:02:02 -07004594 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004595 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004596 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004597 result.append("\n");
4598 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004599
4600 /*
4601 * Dump HWComposer state
4602 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004603 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004604 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004605 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004606 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004607 result.appendFormat(" h/w composer %s\n",
4608 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004609 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004610
4611 /*
4612 * Dump gralloc state
4613 */
4614 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4615 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004616
4617 /*
4618 * Dump VrFlinger state if in use.
4619 */
4620 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4621 result.append("VrFlinger state:\n");
4622 result.append(mVrFlinger->Dump().c_str());
4623 result.append("\n");
4624 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004625}
4626
Dominik Laskowski7e045462018-05-30 13:02:02 -07004627const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004628 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004629 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004630 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004631 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004632 }
4633 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004634
4635 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4636 static const Vector<sp<Layer>> empty;
4637 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004638}
4639
Keun young Park63f165f2012-08-31 10:53:36 -07004640bool SurfaceFlinger::startDdmConnection()
4641{
4642 void* libddmconnection_dso =
4643 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4644 if (!libddmconnection_dso) {
4645 return false;
4646 }
4647 void (*DdmConnection_start)(const char* name);
4648 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004649 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004650 if (!DdmConnection_start) {
4651 dlclose(libddmconnection_dso);
4652 return false;
4653 }
4654 (*DdmConnection_start)(getServiceName());
4655 return true;
4656}
4657
Chia-I Wu28f320b2018-05-03 11:02:56 -07004658void SurfaceFlinger::updateColorMatrixLocked() {
4659 mat4 colorMatrix;
4660 if (mGlobalSaturationFactor != 1.0f) {
4661 // Rec.709 luma coefficients
4662 float3 luminance{0.213f, 0.715f, 0.072f};
4663 luminance *= 1.0f - mGlobalSaturationFactor;
4664 mat4 saturationMatrix = mat4(
4665 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4666 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4667 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4668 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4669 );
4670 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4671 } else {
4672 colorMatrix = mClientColorMatrix * mDaltonizer();
4673 }
4674
4675 if (mCurrentState.colorMatrix != colorMatrix) {
4676 mCurrentState.colorMatrix = colorMatrix;
4677 mCurrentState.colorMatrixChanged = true;
4678 setTransactionFlags(eTransactionNeeded);
4679 }
4680}
4681
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004682status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004683#pragma clang diagnostic push
4684#pragma clang diagnostic error "-Wswitch-enum"
4685 switch (static_cast<ISurfaceComposerTag>(code)) {
4686 // These methods should at minimum make sure that the client requested
4687 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004688 case BOOT_FINISHED:
4689 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004690 case CREATE_CONNECTION:
4691 case CREATE_DISPLAY:
4692 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004693 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004694 case GET_ACTIVE_COLOR_MODE:
4695 case GET_ANIMATION_FRAME_STATS:
4696 case GET_HDR_CAPABILITIES:
4697 case SET_ACTIVE_CONFIG:
4698 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004699 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004700 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004701 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4702 IPCThreadState* ipc = IPCThreadState::self();
4703 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4704 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004705 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004706 }
Robert Carr1db73f62016-12-21 12:58:51 -08004707 return OK;
4708 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004709 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004710 IPCThreadState* ipc = IPCThreadState::self();
4711 const int pid = ipc->getCallingPid();
4712 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004713 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4714 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004715 return PERMISSION_DENIED;
4716 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004717 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004718 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004719 // Used by apps to hook Choreographer to SurfaceFlinger.
4720 case CREATE_DISPLAY_EVENT_CONNECTION:
4721 // The following calls are currently used by clients that do not
4722 // request necessary permissions. However, they do not expose any secret
4723 // information, so it is OK to pass them.
4724 case AUTHENTICATE_SURFACE:
4725 case GET_ACTIVE_CONFIG:
4726 case GET_BUILT_IN_DISPLAY:
4727 case GET_DISPLAY_COLOR_MODES:
4728 case GET_DISPLAY_CONFIGS:
4729 case GET_DISPLAY_STATS:
4730 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4731 // Calling setTransactionState is safe, because you need to have been
4732 // granted a reference to Client* and Handle* to do anything with it.
4733 case SET_TRANSACTION_STATE:
4734 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004735 case CREATE_SCOPED_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004736 case GET_COLOR_MANAGEMENT:
Peiyong Lin0256f722018-08-31 15:45:10 -07004737 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004738 return OK;
4739 }
4740 case CAPTURE_LAYERS:
4741 case CAPTURE_SCREEN: {
4742 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004743 IPCThreadState* ipc = IPCThreadState::self();
4744 const int pid = ipc->getCallingPid();
4745 const int uid = ipc->getCallingUid();
4746 if ((uid != AID_GRAPHICS) &&
4747 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4748 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4749 return PERMISSION_DENIED;
4750 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004751 return OK;
4752 }
4753 // The following codes are deprecated and should never be allowed to access SF.
4754 case CONNECT_DISPLAY_UNUSED:
4755 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4756 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4757 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004758 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004759 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004760
4761 // These codes are used for the IBinder protocol to either interrogate the recipient
4762 // side of the transaction for its canonical interface descriptor or to dump its state.
4763 // We let them pass by default.
4764 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4765 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4766 code == IBinder::SYSPROPS_TRANSACTION) {
4767 return OK;
4768 }
Peiyong Lin3b44a032018-10-24 18:18:12 -07004769 // Numbers from 1000 to 1030 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004770 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin3b44a032018-10-24 18:18:12 -07004771 if (code >= 1000 && code <= 1030) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004772 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4773 return OK;
4774 }
4775 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4776 return PERMISSION_DENIED;
4777#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004778}
4779
Ana Krulec13be8ad2018-08-21 02:43:56 +00004780status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4781 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004782 status_t credentialCheck = CheckTransactCodeCredentials(code);
4783 if (credentialCheck != OK) {
4784 return credentialCheck;
4785 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004786
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004787 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4788 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004789 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004790 IPCThreadState* ipc = IPCThreadState::self();
4791 const int uid = ipc->getCallingUid();
4792 if (CC_UNLIKELY(uid != AID_SYSTEM
4793 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004794 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004795 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004796 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004797 return PERMISSION_DENIED;
4798 }
4799 int n;
4800 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004801 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004802 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004803 return NO_ERROR;
4804 case 1002: // SHOW_UPDATES
4805 n = data.readInt32();
4806 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004807 invalidateHwcGeometry();
4808 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004809 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004810 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004811 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004812 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004813 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004814 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004815 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004816 setTransactionFlags(
4817 eTransactionNeeded|
4818 eDisplayTransactionNeeded|
4819 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004820 return NO_ERROR;
4821 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004822 case 1006:{ // send empty update
4823 signalRefresh();
4824 return NO_ERROR;
4825 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004826 case 1008: // toggle use of hw composer
4827 n = data.readInt32();
4828 mDebugDisableHWC = n ? 1 : 0;
4829 invalidateHwcGeometry();
4830 repaintEverything();
4831 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004832 case 1009: // toggle use of transform hint
4833 n = data.readInt32();
4834 mDebugDisableTransformHint = n ? 1 : 0;
4835 invalidateHwcGeometry();
4836 repaintEverything();
4837 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004838 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004839 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004840 reply->writeInt32(0);
4841 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004842 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004843 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004844 return NO_ERROR;
4845 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004846 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004847 if (!display) {
4848 return NAME_NOT_FOUND;
4849 }
4850
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004851 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004852 return NO_ERROR;
4853 }
4854 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004855 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004856 // daltonize
4857 n = data.readInt32();
4858 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004859 case 1:
4860 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4861 break;
4862 case 2:
4863 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4864 break;
4865 case 3:
4866 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4867 break;
4868 default:
4869 mDaltonizer.setType(ColorBlindnessType::None);
4870 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004871 }
4872 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004873 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004874 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004875 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004876 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004877
4878 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004879 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004880 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004881 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004882 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004883 // apply a color matrix
4884 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004885 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004886 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004887 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004888 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004889 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004890 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004891 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004892 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004893 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004894 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004895
4896 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4897 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004898 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004899 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4900 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4901 }
4902
Chia-I Wu28f320b2018-05-03 11:02:56 -07004903 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004904 return NO_ERROR;
4905 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004906 // This is an experimental interface
4907 // Needs to be shifted to proper binder interface when we productize
4908 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004909 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07004910 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07004911 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004912 return NO_ERROR;
4913 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004914 case 1017: {
4915 n = data.readInt32();
4916 mForceFullDamage = static_cast<bool>(n);
4917 return NO_ERROR;
4918 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004919 case 1018: { // Modify Choreographer's phase offset
4920 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004921 if (mUseScheduler) {
4922 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
4923 } else {
4924 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4925 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004926 return NO_ERROR;
4927 }
4928 case 1019: { // Modify SurfaceFlinger's phase offset
4929 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004930 if (mUseScheduler) {
4931 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
4932 } else {
4933 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4934 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004935 return NO_ERROR;
4936 }
Irvel468051e2016-06-13 16:44:44 -07004937 case 1020: { // Layer updates interceptor
4938 n = data.readInt32();
4939 if (n) {
4940 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004941 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004942 }
4943 else{
4944 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004945 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004946 }
4947 return NO_ERROR;
4948 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004949 case 1021: { // Disable HWC virtual displays
4950 n = data.readInt32();
4951 mUseHwcVirtualDisplays = !n;
4952 return NO_ERROR;
4953 }
Romain Guy0147a172017-06-01 13:53:56 -07004954 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004955 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004956 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004957
Chia-I Wu28f320b2018-05-03 11:02:56 -07004958 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004959 return NO_ERROR;
4960 }
Romain Guy54f154a2017-10-24 21:40:32 +01004961 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004962 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004963 invalidateHwcGeometry();
4964 repaintEverything();
4965 return NO_ERROR;
4966 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004967 // Deprecate, use 1030 to check whether the device is color managed.
4968 case 1024: {
4969 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004970 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004971 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004972 n = data.readInt32();
4973 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004974 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004975 mTracing.enable();
4976 doTracing("tracing.enable");
4977 reply->writeInt32(NO_ERROR);
4978 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004979 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004980 status_t err = mTracing.disable();
4981 reply->writeInt32(err);
4982 }
4983 return NO_ERROR;
4984 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004985 case 1026: { // Get layer tracing status
4986 reply->writeBool(mTracing.isEnabled());
4987 return NO_ERROR;
4988 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004989 // Is a DisplayColorSetting supported?
4990 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004991 const auto display = getDefaultDisplayDevice();
4992 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004993 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004994 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004995
4996 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4997 switch (setting) {
4998 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07004999 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005000 break;
5001 case DisplayColorSetting::UNMANAGED:
5002 reply->writeBool(true);
5003 break;
5004 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005005 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005006 break;
5007 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005008 reply->writeBool(
5009 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005010 break;
5011 }
5012 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005013 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005014 // Is VrFlinger active?
5015 case 1028: {
5016 Mutex::Autolock _l(mStateLock);
5017 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5018 return NO_ERROR;
5019 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005020 // Is device color managed?
5021 case 1030: {
5022 reply->writeBool(useColorManagement);
5023 return NO_ERROR;
5024 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005025 }
5026 }
5027 return err;
5028}
5029
Steven Thomas6d8110b2017-08-31 18:24:21 -07005030void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005031 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005032 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005033}
5034
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005035// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5036class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005037public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005038 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5039 ~WindowDisconnector() {
5040 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005041 }
5042
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005043private:
5044 ANativeWindow* mWindow;
5045 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005046};
5047
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005048status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005049 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5050 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005051 uint32_t reqWidth, uint32_t reqHeight,
5052 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005053 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005054 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005055
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005056 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005057
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005058 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5059
Chia-I Wu20261cb2018-08-23 12:55:44 -07005060 sp<DisplayDevice> display;
5061 {
5062 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005063
Chia-I Wu20261cb2018-08-23 12:55:44 -07005064 display = getDisplayDeviceLocked(displayToken);
5065 if (!display) return BAD_VALUE;
5066
Chia-I Wucb023152018-08-28 12:57:23 -07005067 // set the requested width/height to the logical display viewport size
5068 // by default
5069 if (reqWidth == 0 || reqHeight == 0) {
5070 reqWidth = uint32_t(display->getViewport().width());
5071 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005072 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005073 }
5074
Peiyong Lin0e003c92018-09-17 11:09:51 -07005075 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5076 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005077
5078 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005079 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005080 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5081 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005082}
5083
5084status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005085 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5086 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005087 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005088 ATRACE_CALL();
5089
5090 class LayerRenderArea : public RenderArea {
5091 public:
Robert Carr578038f2018-03-09 12:25:24 -08005092 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005093 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5094 bool childrenOnly)
5095 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005096 mLayer(layer),
5097 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005098 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005099 mFlinger(flinger),
5100 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005101 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005102 Rect getBounds() const override {
5103 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005104 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005105 }
Marissa Wall61c58622018-07-18 10:12:20 -07005106 int getHeight() const override {
5107 return mLayer->getActiveHeight(mLayer->getDrawingState());
5108 }
5109 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005110 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005111 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005112 Rect getSourceCrop() const override {
5113 if (mCrop.isEmpty()) {
5114 return getBounds();
5115 } else {
5116 return mCrop;
5117 }
5118 }
Robert Carr578038f2018-03-09 12:25:24 -08005119 class ReparentForDrawing {
5120 public:
5121 const sp<Layer>& oldParent;
5122 const sp<Layer>& newParent;
5123
5124 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5125 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005126 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005127 }
Robert Carr15eae092018-03-23 13:43:53 -07005128 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005129 };
5130
5131 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005132 const Rect sourceCrop = getSourceCrop();
5133 // no need to check rotation because there is none
5134 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5135 sourceCrop.height() != getReqHeight();
5136
Robert Carr578038f2018-03-09 12:25:24 -08005137 if (!mChildrenOnly) {
5138 mTransform = mLayer->getTransform().inverse();
5139 drawLayers();
5140 } else {
5141 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005142 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005143 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5144 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005145
5146 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5147 drawLayers();
5148 }
5149 }
chaviwa76b2712017-09-20 12:02:26 -07005150
chaviwa76b2712017-09-20 12:02:26 -07005151 private:
chaviw7206d492017-11-10 16:16:12 -08005152 const sp<Layer> mLayer;
5153 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005154
5155 // In the "childrenOnly" case we reparent the children to a screenshot
5156 // layer which has no properties set and which does not draw.
5157 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005158 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005159 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005160
5161 SurfaceFlinger* mFlinger;
5162 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005163 };
5164
5165 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5166 auto parent = layerHandle->owner.promote();
5167
Robert Carr2e102c92018-10-23 12:11:15 -07005168 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005169 ALOGE("captureLayers called with a removed parent");
5170 return NAME_NOT_FOUND;
5171 }
5172
Robert Carr578038f2018-03-09 12:25:24 -08005173 const int uid = IPCThreadState::self()->getCallingUid();
5174 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5175 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5176 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5177 return PERMISSION_DENIED;
5178 }
5179
chaviw7206d492017-11-10 16:16:12 -08005180 Rect crop(sourceCrop);
5181 if (sourceCrop.width() <= 0) {
5182 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005183 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005184 }
5185
5186 if (sourceCrop.height() <= 0) {
5187 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005188 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005189 }
5190
5191 int32_t reqWidth = crop.width() * frameScale;
5192 int32_t reqHeight = crop.height() * frameScale;
5193
Chia-I Wu20261cb2018-08-23 12:55:44 -07005194 // really small crop or frameScale
5195 if (reqWidth <= 0) {
5196 reqWidth = 1;
5197 }
5198 if (reqHeight <= 0) {
5199 reqHeight = 1;
5200 }
5201
Peiyong Lin0e003c92018-09-17 11:09:51 -07005202 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005203
Robert Carr578038f2018-03-09 12:25:24 -08005204 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005205 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5206 if (!layer->isVisible()) {
5207 return;
Robert Carr578038f2018-03-09 12:25:24 -08005208 } else if (childrenOnly && layer == parent.get()) {
5209 return;
chaviwa76b2712017-09-20 12:02:26 -07005210 }
5211 visitor(layer);
5212 });
5213 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005214 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005215}
5216
5217status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5218 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005219 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005220 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005221 bool useIdentityTransform) {
5222 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005223
Peiyong Lin0e003c92018-09-17 11:09:51 -07005224 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005225 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5226 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005227 *outBuffer =
5228 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5229 static_cast<android_pixel_format>(reqPixelFormat), 1,
5230 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005231
5232 // This mutex protects syncFd and captureResult for communication of the return values from the
5233 // main thread back to this Binder thread
5234 std::mutex captureMutex;
5235 std::condition_variable captureCondition;
5236 std::unique_lock<std::mutex> captureLock(captureMutex);
5237 int syncFd = -1;
5238 std::optional<status_t> captureResult;
5239
Robert Carr03480e22018-01-04 16:02:06 -08005240 const int uid = IPCThreadState::self()->getCallingUid();
5241 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5242
Dominik Laskowski8c001672018-05-30 16:52:06 -07005243 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005244 // If there is a refresh pending, bug out early and tell the binder thread to try again
5245 // after the refresh.
5246 if (mRefreshPending) {
5247 ATRACE_NAME("Skipping screenshot for now");
5248 std::unique_lock<std::mutex> captureLock(captureMutex);
5249 captureResult = std::make_optional<status_t>(EAGAIN);
5250 captureCondition.notify_one();
5251 return;
5252 }
5253
5254 status_t result = NO_ERROR;
5255 int fd = -1;
5256 {
5257 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005258 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005259 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5260 useIdentityTransform, forSystem, &fd);
5261 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005262 }
5263
5264 {
5265 std::unique_lock<std::mutex> captureLock(captureMutex);
5266 syncFd = fd;
5267 captureResult = std::make_optional<status_t>(result);
5268 captureCondition.notify_one();
5269 }
5270 });
5271
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005272 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005273 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005274 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005275 while (*captureResult == EAGAIN) {
5276 captureResult.reset();
5277 result = postMessageAsync(message);
5278 if (result != NO_ERROR) {
5279 return result;
5280 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005281 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005282 }
5283 result = *captureResult;
5284 }
5285
5286 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005287 sync_wait(syncFd, -1);
5288 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005289 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005290
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005291 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005292}
5293
chaviwa76b2712017-09-20 12:02:26 -07005294void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005295 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005296 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005297 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005298
Lloyd Pique144e1162017-12-20 16:44:52 -08005299 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005300
chaviwa76b2712017-09-20 12:02:26 -07005301 const auto reqWidth = renderArea.getReqWidth();
5302 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005303 const auto sourceCrop = renderArea.getSourceCrop();
5304 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005305
Peiyong Lin0e003c92018-09-17 11:09:51 -07005306 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005307 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005308
Mathias Agopian180f10d2013-04-10 22:55:41 -07005309 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005310 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005311
5312 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005313 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005314 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005315
chaviw50da5042018-04-09 13:49:37 -07005316 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005317 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005318 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005319
chaviwa76b2712017-09-20 12:02:26 -07005320 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005321 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005322 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005323 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005324 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005325}
5326
chaviwa76b2712017-09-20 12:02:26 -07005327status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5328 TraverseLayersFunction traverseLayers,
5329 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005330 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005331 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005332 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005333 ATRACE_CALL();
5334
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005335 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005336
5337 traverseLayers([&](Layer* layer) {
5338 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5339 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005340
Robert Carr03480e22018-01-04 16:02:06 -08005341 // We allow the system server to take screenshots of secure layers for
5342 // use in situations like the Screen-rotation animation and place
5343 // the impetus on WindowManager to not persist them.
5344 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005345 ALOGW("FB is protected: PERMISSION_DENIED");
5346 return PERMISSION_DENIED;
5347 }
5348
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005349 // this binds the given EGLImage as a framebuffer for the
5350 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005351 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005352 if (bufferBond.getStatus() != NO_ERROR) {
5353 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005354 return INVALID_OPERATION;
5355 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005356
Dan Stozaabcda352017-06-01 14:37:39 -07005357 // this will in fact render into our dequeued buffer
5358 // via an FBO, which means we didn't have to create
5359 // an EGLSurface and therefore we're not
5360 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005361 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005362
Alec Mouri492bc572018-09-11 21:40:04 +00005363 base::unique_fd syncFd = getRenderEngine().flush();
5364 if (syncFd < 0) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005365 getRenderEngine().finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005366 }
Alec Mouri492bc572018-09-11 21:40:04 +00005367 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005368
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005369 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005370}
5371
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005372// ---------------------------------------------------------------------------
5373
Dan Stoza412903f2017-04-27 13:42:17 -07005374void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5375 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005376}
5377
Dan Stoza412903f2017-04-27 13:42:17 -07005378void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5379 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005380}
5381
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005382void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005383 const LayerVector::Visitor& visitor) {
5384 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005385 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005386 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005387 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005388 continue;
5389 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005390 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005391 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005392 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005393 return;
5394 }
chaviwa76b2712017-09-20 12:02:26 -07005395 if (!layer->isVisible()) {
5396 return;
5397 }
5398 visitor(layer);
5399 });
5400 }
5401}
5402
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005403}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005404
Lloyd Pique074e8122018-07-26 12:57:23 -07005405
Mathias Agopian3f844832013-08-07 21:24:32 -07005406#if defined(__gl_h_)
5407#error "don't include gl/gl.h in this file"
5408#endif
5409
5410#if defined(__gl2_h_)
5411#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005412#endif