blob: 968fcd6acb60f4353626b350d01dcdbf7acbede0 [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) {
1575 const auto displayId = display->getId();
David Sodman7e4ae112018-02-09 15:02:28 -08001576 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[displayId]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001577 compositionInfo.hwc.hwcLayer = nullptr;
1578 }
David Sodmanba340492018-08-05 21:51:33 -07001579 }
David Sodman7e4ae112018-02-09 15:02:28 -08001580
1581 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001582}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001583
David Sodmanfa9b2af2017-12-24 13:28:59 -08001584
1585bool SurfaceFlinger::handleMessageInvalidate() {
1586 ATRACE_CALL();
1587 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001588}
1589
David Sodman79bba0e2018-08-05 18:07:49 -07001590void SurfaceFlinger::calculateWorkingSet() {
1591 ATRACE_CALL();
1592 ALOGV(__FUNCTION__);
1593
David Sodman79bba0e2018-08-05 18:07:49 -07001594 // build the h/w work list
1595 if (CC_UNLIKELY(mGeometryInvalid)) {
1596 mGeometryInvalid = false;
1597 for (const auto& [token, display] : mDisplays) {
1598 const auto displayId = display->getId();
1599 if (displayId >= 0) {
1600 const Vector<sp<Layer>>& currentLayers(
1601 display->getVisibleLayersSortedByZ());
1602 for (size_t i = 0; i < currentLayers.size(); i++) {
1603 const auto& layer = currentLayers[i];
1604
1605 if (!layer->hasHwcLayer(displayId)) {
1606 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1607 layer->forceClientComposition(displayId);
1608 continue;
1609 }
1610 }
1611
1612 layer->setGeometry(display, i);
1613 if (mDebugDisableHWC || mDebugRegion) {
1614 layer->forceClientComposition(displayId);
1615 }
1616 }
1617 }
1618 }
1619 }
1620
1621 // Set the per-frame data
1622 for (const auto& [token, display] : mDisplays) {
1623 const auto displayId = display->getId();
1624 if (displayId < 0) {
1625 continue;
1626 }
1627
1628 if (mDrawingState.colorMatrixChanged) {
1629 display->setColorTransform(mDrawingState.colorMatrix);
1630 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1631 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1632 "display %d: %d", displayId, result);
1633 }
1634 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1635 if (layer->isHdrY410()) {
1636 layer->forceClientComposition(displayId);
1637 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1638 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1639 !display->hasHDR10Support()) {
1640 layer->forceClientComposition(displayId);
1641 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1642 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1643 !display->hasHLGSupport()) {
1644 layer->forceClientComposition(displayId);
1645 }
1646
Peiyong Lind3788632018-09-18 16:01:31 -07001647 // TODO(b/111562338) remove when composer 2.3 is shipped.
1648 if (layer->hasColorTransform()) {
1649 layer->forceClientComposition(displayId);
1650 }
1651
David Sodman79bba0e2018-08-05 18:07:49 -07001652 if (layer->getForceClientComposition(displayId)) {
1653 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1654 layer->setCompositionType(displayId, HWC2::Composition::Client);
1655 continue;
1656 }
1657
1658 layer->setPerFrameData(display);
1659 }
1660
Peiyong Lin13effd12018-07-24 17:01:47 -07001661 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001662 ColorMode colorMode;
1663 Dataspace dataSpace;
1664 RenderIntent renderIntent;
1665 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1666 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1667 }
1668 }
1669
1670 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001671
1672 for (const auto& [token, display] : mDisplays) {
David Sodman15fb96e2018-01-07 10:23:24 -08001673 const auto displayId = display->getId();
1674 getBE().mCompositionInfo[displayId].clear();
David Sodmanba340492018-08-05 21:51:33 -07001675 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1676 auto displayId = display->getId();
1677 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1678 if (!layer->setHwcLayer(displayId)) {
1679 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1680 }
David Sodman15fb96e2018-01-07 10:23:24 -08001681 layer->getBE().compositionInfo.hwc.displayId = displayId;
1682 getBE().mCompositionInfo[displayId].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001683 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1684 }
1685 }
David Sodman79bba0e2018-08-05 18:07:49 -07001686}
1687
David Sodmanfa9b2af2017-12-24 13:28:59 -08001688void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001689{
David Sodmanfb95bcc2017-12-22 15:45:30 -08001690 const auto displayId = display->getId();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001691 // is debugging enabled
1692 if (CC_LIKELY(!mDebugRegion))
1693 return;
1694
David Sodmanfa9b2af2017-12-24 13:28:59 -08001695 if (display->isPoweredOn()) {
1696 // transform the dirty region into this screen's coordinate space
1697 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1698 if (!dirtyRegion.isEmpty()) {
1699 // redraw the whole screen
1700 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001701
David Sodmanfa9b2af2017-12-24 13:28:59 -08001702 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001703 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001704 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001705
David Sodmanfa9b2af2017-12-24 13:28:59 -08001706 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001707 }
1708 }
1709
David Sodmanfa9b2af2017-12-24 13:28:59 -08001710 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001711
1712 if (mDebugRegion > 1) {
1713 usleep(mDebugRegion * 1000);
1714 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001715
David Sodmanfa9b2af2017-12-24 13:28:59 -08001716 if (display->isPoweredOn()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08001717 status_t result = display->prepareFrame(
1718 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001719 ALOGE_IF(result != NO_ERROR,
1720 "prepareFrame for display %d failed:"
1721 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001722 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001723 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001724}
1725
Adrian Roos1e1a1282017-11-01 19:05:31 +01001726void SurfaceFlinger::doTracing(const char* where) {
1727 ATRACE_CALL();
1728 ATRACE_NAME(where);
1729 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001730 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001731 }
1732}
1733
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001734void SurfaceFlinger::logLayerStats() {
1735 ATRACE_CALL();
1736 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001737 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001738 if (display->isPrimary()) {
1739 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001740 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001741 }
1742 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001743
1744 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001745 }
1746}
1747
David Sodman2b406362017-12-15 13:33:47 -08001748void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001749{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001750 ATRACE_CALL();
1751 ALOGV("preComposition");
1752
David Sodman2b406362017-12-15 13:33:47 -08001753 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1754
Mathias Agopiancd60f992012-08-16 16:28:27 -07001755 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001756 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001757 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001758 needExtraInvalidate = true;
1759 }
Robert Carr2047fae2016-11-28 14:09:09 -08001760 });
1761
Mathias Agopiancd60f992012-08-16 16:28:27 -07001762 if (needExtraInvalidate) {
1763 signalLayerUpdate();
1764 }
1765}
1766
Ana Krulece588e312018-09-18 12:32:24 -07001767void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1768 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001769 // Update queue of past composite+present times and determine the
1770 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001771 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001772 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001773 while (!getBE().mCompositePresentTimes.empty()) {
1774 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001775 // Cached values should have been updated before calling this method,
1776 // which helps avoid duplicate syscalls.
1777 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1778 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1779 break;
1780 }
1781 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001782 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001783 }
1784
1785 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001786 while (getBE().mCompositePresentTimes.size() > 16) {
1787 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001788 }
1789
Ana Krulece588e312018-09-18 12:32:24 -07001790 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001791}
1792
Ana Krulece588e312018-09-18 12:32:24 -07001793void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1794 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001795 // Integer division and modulo round toward 0 not -inf, so we need to
1796 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001797 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1798 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1799 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001800
Brian Andersond0010582017-03-07 13:20:31 -08001801 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1802 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001803 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001804 }
1805
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001806 // Snap the latency to a value that removes scheduling jitter from the
1807 // composition and present times, which often have >1ms of jitter.
1808 // Reducing jitter is important if an app attempts to extrapolate
1809 // something (such as user input) to an accurate diasplay time.
1810 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1811 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001812 nsecs_t bias = stats.vsyncPeriod / 2;
1813 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1814 nsecs_t snappedCompositeToPresentLatency =
1815 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001816
David Sodman99974d22017-11-28 12:04:33 -08001817 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001818 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1819 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001820 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001821}
1822
David Sodman2b406362017-12-15 13:33:47 -08001823void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001824{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001825 ATRACE_CALL();
1826 ALOGV("postComposition");
1827
Brian Anderson3546a3f2016-07-14 11:51:14 -07001828 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001829 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001830 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001831 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001832 }
1833
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001834 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001835 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001836
David Sodman73beded2017-11-15 11:56:06 -08001837 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001838 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001839 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001840 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001841 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001842 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001843 } else {
1844 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1845 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001846
David Sodman73beded2017-11-15 11:56:06 -08001847 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001848 mPreviousPresentFence =
1849 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1850 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001851 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001852
Ana Krulece588e312018-09-18 12:32:24 -07001853 DisplayStatInfo stats;
1854 if (mUseScheduler) {
1855 mScheduler->getDisplayStatInfo(&stats);
1856 } else {
1857 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1858 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
1859 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001860
David Sodman2b406362017-12-15 13:33:47 -08001861 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001862 // when we started doing work for this frame, but that should be okay
1863 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07001864 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001865 CompositorTiming compositorTiming;
1866 {
David Sodman99974d22017-11-28 12:04:33 -08001867 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1868 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001869 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001870
Robert Carr2047fae2016-11-28 14:09:09 -08001871 mDrawingState.traverseInZOrder([&](Layer* layer) {
1872 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001873 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001874 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001875 recordBufferingStats(layer->getName().string(),
1876 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001877 }
Robert Carr2047fae2016-11-28 14:09:09 -08001878 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001879
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001880 if (presentFenceTime->isValid()) {
Ana Krulece588e312018-09-18 12:32:24 -07001881 if (mUseScheduler) {
1882 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001883 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001884 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
1885 enableHardwareVsync();
1886 } else {
1887 disableHardwareVsync(false);
1888 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001889 }
1890 }
1891
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001892 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001893 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07001894 if (mUseScheduler) {
1895 mScheduler->enableHardwareVsync();
1896 } else {
1897 enableHardwareVsync();
1898 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001899 }
1900 }
1901
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001902 if (mAnimCompositionPending) {
1903 mAnimCompositionPending = false;
1904
Brian Anderson4e606e32017-03-16 15:34:57 -07001905 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001906 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001907 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001908 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001909 // The HWC doesn't support present fences, so use the refresh
1910 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001911 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001912 mAnimFrameTracker.setActualPresentTime(presentTime);
1913 }
1914 mAnimFrameTracker.advanceFrame();
1915 }
Dan Stozab90cf072015-03-05 11:05:59 -08001916
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001917 mTimeStats.incrementTotalFrames();
1918 if (mHadClientComposition) {
1919 mTimeStats.incrementClientCompositionFrames();
1920 }
1921
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001922 mTimeStats.setPresentFenceGlobal(presentFenceTime);
1923
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001924 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001925 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001926 return;
1927 }
1928
1929 nsecs_t currentTime = systemTime();
1930 if (mHasPoweredOff) {
1931 mHasPoweredOff = false;
1932 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001933 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001934 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001935 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1936 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001937 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001938 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001939 }
David Sodman4a36e932017-11-07 14:29:47 -08001940 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001941 }
David Sodman4a36e932017-11-07 14:29:47 -08001942 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001943
1944 {
1945 std::lock_guard lock(mTexturePoolMutex);
1946 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1947 if (refillCount > 0) {
1948 const size_t offset = mTexturePool.size();
1949 mTexturePool.resize(mTexturePoolSize);
1950 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1951 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1952 }
1953 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001954}
1955
1956void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001957 ATRACE_CALL();
1958 ALOGV("rebuildLayerStacks");
1959
Mathias Agopiancd60f992012-08-16 16:28:27 -07001960 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001961 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001962 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001963 mVisibleRegionsDirty = false;
1964 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001965
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001966 for (const auto& pair : mDisplays) {
1967 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001968 Region opaqueRegion;
1969 Region dirtyRegion;
1970 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001971 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001972 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001973 const Rect bounds = display->getBounds();
1974 if (display->isPoweredOn()) {
1975 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001976
Jeff Sharkey76488112017-02-27 14:15:18 -07001977 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001978 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001979 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001980 Region drawRegion(tr.transform(
1981 layer->visibleNonTransparentRegion));
1982 drawRegion.andSelf(bounds);
1983 if (!drawRegion.isEmpty()) {
1984 layersSortedByZ.add(layer);
1985 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001986 // Clear out the HWC layer if this layer was
1987 // previously visible, but no longer is
1988 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001989 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001990 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001991 // WM changes display->layerStack upon sleep/awake.
1992 // Here we make sure we delete the HWC layers even if
1993 // WM changed their layer stack.
1994 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001995 }
1996
1997 // If a layer is not going to get a release fence because
1998 // it is invisible, but it is also going to release its
1999 // old buffer, add it to the list of layers needing
2000 // fences.
2001 if (hwcLayerDestroyed) {
2002 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2003 mLayersWithQueuedFrames.cend(), layer);
2004 if (found != mLayersWithQueuedFrames.cend()) {
2005 layersNeedingFences.add(layer);
2006 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002007 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002008 });
2009 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002010 display->setVisibleLayersSortedByZ(layersSortedByZ);
2011 display->setLayersNeedingFences(layersNeedingFences);
2012 display->undefinedRegion.set(bounds);
2013 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2014 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002015 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002016 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002017}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002018
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002019// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002020// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002021// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002022// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002023// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002024// The returned HDR data space is one of
2025// - Dataspace::UNKNOWN
2026// - Dataspace::BT2020_HLG
2027// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002028Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2029 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07002030 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002031 *outHdrDataSpace = Dataspace::UNKNOWN;
2032
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002033 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002034 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002035 case Dataspace::V0_SCRGB:
2036 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002037 case Dataspace::BT2020:
2038 case Dataspace::BT2020_ITU:
2039 case Dataspace::BT2020_LINEAR:
2040 case Dataspace::DISPLAY_BT2020:
2041 bestDataSpace = Dataspace::DISPLAY_BT2020;
2042 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002043 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002044 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002045 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002046 case Dataspace::BT2020_PQ:
2047 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002048 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002049 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002050 case Dataspace::BT2020_HLG:
2051 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002052 // When there's mixed PQ content and HLG content, we set the HDR
2053 // data space to be BT2020_PQ and convert HLG to PQ.
2054 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2055 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002056 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002057 break;
2058 default:
2059 break;
2060 }
Romain Guy54f154a2017-10-24 21:40:32 +01002061 }
2062
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002063 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002064}
2065
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002066// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002067void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2068 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002069 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2070 *outMode = ColorMode::NATIVE;
2071 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002072 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002073 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002074 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002075
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002076 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002077 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002078
Peiyong Lindfde5112018-06-05 10:58:41 -07002079 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002080 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002081 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002082 if (isHdr) {
2083 bestDataSpace = hdrDataSpace;
2084 }
2085
Chia-I Wu0d711262018-05-21 15:19:35 -07002086 RenderIntent intent;
2087 switch (mDisplayColorSetting) {
2088 case DisplayColorSetting::MANAGED:
2089 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002090 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002091 break;
2092 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002093 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002094 break;
2095 default: // vendor display color setting
2096 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2097 break;
2098 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002099
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002100 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002101}
2102
David Sodmanfa9b2af2017-12-24 13:28:59 -08002103void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002104{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002105 bool dirty = !display->getDirtyRegion(false).isEmpty();
2106 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2107 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002108
David Sodmanfa9b2af2017-12-24 13:28:59 -08002109 // If nothing has changed (!dirty), don't recompose.
2110 // If something changed, but we don't currently have any visible layers,
2111 // and didn't when we last did a composition, then skip it this time.
2112 // The second rule does two things:
2113 // - When all layers are removed from a display, we'll emit one black
2114 // frame, then nothing more until we get new layers.
2115 // - When a display is created with a private layer stack, we won't
2116 // emit any black frames until a layer is added to the layer stack.
2117 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002118
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002119 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2120 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002121 mustRecompose ? "doing" : "skipping",
2122 dirty ? "+" : "-",
2123 empty ? "+" : "-",
2124 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002125
David Sodmanfa9b2af2017-12-24 13:28:59 -08002126 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002127
David Sodmanfa9b2af2017-12-24 13:28:59 -08002128 if (mustRecompose) {
2129 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002130 }
2131}
2132
David Sodmanfa9b2af2017-12-24 13:28:59 -08002133void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002134{
David Sodmanfb95bcc2017-12-22 15:45:30 -08002135 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002136 if (!display->isPoweredOn()) {
2137 return;
David Sodman2b406362017-12-15 13:33:47 -08002138 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002139
David Sodmanfb95bcc2017-12-22 15:45:30 -08002140 status_t result = display->prepareFrame(
2141 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08002142 ALOGE_IF(result != NO_ERROR,
2143 "prepareFrame for display %d failed:"
2144 " %d (%s)",
2145 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002146}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002147
David Sodmanfa9b2af2017-12-24 13:28:59 -08002148void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002149 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002150 ALOGV("doComposition");
2151
David Sodmanfa9b2af2017-12-24 13:28:59 -08002152 if (display->isPoweredOn()) {
2153 // transform the dirty region into this screen's coordinate space
2154 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002155
David Sodmanfa9b2af2017-12-24 13:28:59 -08002156 // repaint the framebuffer (if needed)
2157 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002158
David Sodmanfa9b2af2017-12-24 13:28:59 -08002159 display->dirtyRegion.clear();
2160 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002161 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002162 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002163}
2164
David Sodmanfa9b2af2017-12-24 13:28:59 -08002165void SurfaceFlinger::postFrame()
2166{
2167 // |mStateLock| not needed as we are on the main thread
2168 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2169 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2170 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2171 logFrameStats();
2172 }
2173 }
2174}
2175
2176void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002177{
Mathias Agopian841cde52012-03-01 15:44:37 -08002178 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002179 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002180
David Sodmanfa9b2af2017-12-24 13:28:59 -08002181 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002182
David Sodmanfa9b2af2017-12-24 13:28:59 -08002183 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002184 const auto displayId = display->getId();
2185 if (displayId >= 0) {
2186 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002187 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002188 display->onSwapBuffersCompleted();
2189 display->makeCurrent();
David Sodman15094112018-10-11 09:39:37 -07002190 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002191 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002192
Chia-I Wu7b549592017-11-15 09:14:57 -08002193 // The layer buffer from the previous frame (if any) is released
2194 // by HWC only when the release fence from this frame (if any) is
2195 // signaled. Always get the release fence from HWC first.
David Sodman15094112018-10-11 09:39:37 -07002196 auto hwcLayer = layer->getHwcLayer(displayId);
2197 if (displayId >= 0) {
2198 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002199 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002200
2201 // If the layer was client composited in the previous frame, we
2202 // need to merge with the previous client target acquire fence.
2203 // Since we do not track that, always merge with the current
2204 // client target acquire fence when it is available, even though
2205 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002206 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002207 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002208 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002209 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002210
David Sodman15094112018-10-11 09:39:37 -07002211 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002212 }
Chia-I Wu83806892017-11-16 10:50:20 -08002213
2214 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002215 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002216 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002217 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002218 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002219 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002220 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002221 }
2222 }
2223
Dominik Laskowski7e045462018-05-30 13:02:02 -07002224 if (displayId >= 0) {
2225 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002226 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002227 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002228}
2229
Mathias Agopian87baae12012-07-31 12:38:26 -07002230void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002231{
Mathias Agopian841cde52012-03-01 15:44:37 -08002232 ATRACE_CALL();
2233
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002234 // here we keep a copy of the drawing state (that is the state that's
2235 // going to be overwritten by handleTransactionLocked()) outside of
2236 // mStateLock so that the side-effects of the State assignment
2237 // don't happen with mStateLock held (which can cause deadlocks).
2238 State drawingState(mDrawingState);
2239
Mathias Agopianca4d3602011-05-19 15:38:14 -07002240 Mutex::Autolock _l(mStateLock);
2241 const nsecs_t now = systemTime();
2242 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002243
Mathias Agopianca4d3602011-05-19 15:38:14 -07002244 // Here we're guaranteed that some transaction flags are set
2245 // so we can call handleTransactionLocked() unconditionally.
2246 // We call getTransactionFlags(), which will also clear the flags,
2247 // with mStateLock held to guarantee that mCurrentState won't change
2248 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002249
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002250 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002251 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002252 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002253
Mathias Agopianca4d3602011-05-19 15:38:14 -07002254 mLastTransactionTime = systemTime() - now;
2255 mDebugInTransaction = 0;
2256 invalidateHwcGeometry();
2257 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002258}
2259
Dominik Laskowski7e045462018-05-30 13:02:02 -07002260DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002261 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002262 // Figure out whether the event is for the primary display or an
2263 // external display by matching the Hwc display id against one for a
2264 // connected display. If we did not find a match, we then check what
2265 // displays are not already connected to determine the type. If we don't
2266 // have a connected primary display, we assume the new display is meant to
2267 // be the primary display, and then if we don't have an external display,
2268 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002269 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2270 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002271 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002272 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002273 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002274 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002275 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002276 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002277 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002278 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002279 return DisplayDevice::DISPLAY_EXTERNAL;
2280 }
2281
2282 return DisplayDevice::DISPLAY_ID_INVALID;
2283}
2284
Lloyd Piqueba04e622017-12-14 17:11:26 -08002285void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2286 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002287 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002288 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002289 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002290 continue;
2291 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002292
2293 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2294 ALOGE("External displays are not supported by the vr hardware composer.");
2295 continue;
2296 }
2297
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002298 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002299 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002300 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002301 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002302 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002303
2304 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002305 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002306 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002307 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002308 DisplayDeviceState info;
2309 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002310 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2311 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002312 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002313 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002314 mInterceptor->saveDisplayCreation(info);
2315 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002316 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002317 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002318
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002319 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002320 if (idx >= 0) {
2321 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002322 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002323 mCurrentState.displays.removeItemsAt(idx);
2324 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002325 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002326 }
2327
2328 processDisplayChangesLocked();
2329 }
2330
2331 mPendingHotplugEvents.clear();
2332}
2333
Lloyd Pique99d3da52018-01-22 17:48:03 -08002334sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002335 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002336 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002337 DisplayDeviceCreationArgs creationArgs(this, displayToken, state.type, displayId);
2338 creationArgs.isSecure = state.isSecure;
2339 creationArgs.displaySurface = dispSurface;
2340 creationArgs.hasWideColorGamut = false;
2341 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002342
Peiyong Lin13effd12018-07-24 17:01:47 -07002343 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002344 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002345 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002346 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002347 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002348 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002349
Dominik Laskowski7e045462018-05-30 13:02:02 -07002350 std::vector<RenderIntent> renderIntents =
2351 getHwComposer().getRenderIntents(displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002352 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002353 }
tangrobin6753a022018-08-10 10:58:54 +08002354 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002355
tangrobin6753a022018-08-10 10:58:54 +08002356 if (displayId >= 0) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002357 getHwComposer().getHdrCapabilities(displayId, &creationArgs.hdrCapabilities);
2358 creationArgs.supportedPerFrameMetadata =
2359 getHwComposer().getSupportedPerFrameMetadata(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002360 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002361
Lloyd Pique90c115d2018-09-18 21:39:42 -07002362 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002363 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002364 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002365
2366 /*
2367 * Create our display's surface
2368 */
Peiyong Lin833074a2018-08-28 11:53:54 -07002369 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002370 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002371 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002372 renderSurface->setNativeWindow(nativeWindow.get());
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002373 creationArgs.displayWidth = renderSurface->getWidth();
2374 creationArgs.displayHeight = renderSurface->getHeight();
2375 creationArgs.renderSurface = std::move(renderSurface);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002376
2377 // Make sure that composition can never be stalled by a virtual display
2378 // consumer that isn't processing buffers fast enough. We have to do this
2379 // in two places:
2380 // * Here, in case the display is composed entirely by HWC.
2381 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2382 // window's swap interval in eglMakeCurrent, so they'll override the
2383 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002384 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002385 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2386 }
2387
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002388 creationArgs.displayInstallOrientation = state.type == DisplayDevice::DISPLAY_PRIMARY
2389 ? primaryDisplayOrientation
2390 : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002391
Lloyd Pique99d3da52018-01-22 17:48:03 -08002392 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002393 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002394
Lloyd Pique90c115d2018-09-18 21:39:42 -07002395 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002396
2397 if (maxFrameBufferAcquiredBuffers >= 3) {
2398 nativeWindowSurface->preallocateBuffers();
2399 }
2400
2401 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002402 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002403 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002404 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002405 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002406 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002407 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002408 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002409 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002410 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002411 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002412 display->setLayerStack(state.layerStack);
2413 display->setProjection(state.orientation, state.viewport, state.frame);
2414 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002415
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002416 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002417}
2418
Lloyd Pique347200f2017-12-14 17:00:15 -08002419void SurfaceFlinger::processDisplayChangesLocked() {
2420 // here we take advantage of Vector's copy-on-write semantics to
2421 // improve performance by skipping the transaction entirely when
2422 // know that the lists are identical
2423 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2424 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2425 if (!curr.isIdenticalTo(draw)) {
2426 mVisibleRegionsDirty = true;
2427 const size_t cc = curr.size();
2428 size_t dc = draw.size();
2429
2430 // find the displays that were removed
2431 // (ie: in drawing state but not in current state)
2432 // also handle displays that changed
2433 // (ie: displays that are in both lists)
2434 for (size_t i = 0; i < dc;) {
2435 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2436 if (j < 0) {
2437 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002438 // Call makeCurrent() on the primary display so we can
2439 // be sure that nothing associated with this display
2440 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002441 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2442 defaultDisplay->makeCurrent();
2443 }
2444 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2445 display->disconnect(getHwComposer());
2446 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002447 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002448 if (mUseScheduler) {
2449 mScheduler->hotplugReceived(mAppConnectionHandle,
2450 EventThread::DisplayType::Primary, false);
2451 } else {
2452 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2453 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002454 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002455 if (mUseScheduler) {
2456 mScheduler->hotplugReceived(mAppConnectionHandle,
2457 EventThread::DisplayType::External, false);
2458 } else {
2459 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2460 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002461 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002462 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002463 } else {
2464 // this display is in both lists. see if something changed.
2465 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002466 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002467 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2468 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2469 if (state_binder != draw_binder) {
2470 // changing the surface is like destroying and
2471 // recreating the DisplayDevice, so we just remove it
2472 // from the drawing state, so that it get re-added
2473 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002474 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2475 display->disconnect(getHwComposer());
2476 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002477 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002478 mDrawingState.displays.removeItemsAt(i);
2479 dc--;
2480 // at this point we must loop to the next item
2481 continue;
2482 }
2483
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002484 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002485 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002486 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002487 }
2488 if ((state.orientation != draw[i].orientation) ||
2489 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002490 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002491 }
2492 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002493 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002494 }
2495 }
2496 }
2497 ++i;
2498 }
2499
2500 // find displays that were added
2501 // (ie: in current state but not in drawing state)
2502 for (size_t i = 0; i < cc; i++) {
2503 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2504 const DisplayDeviceState& state(curr[i]);
2505
2506 sp<DisplaySurface> dispSurface;
2507 sp<IGraphicBufferProducer> producer;
2508 sp<IGraphicBufferProducer> bqProducer;
2509 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002510 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002511
Dominik Laskowski7e045462018-05-30 13:02:02 -07002512 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002513 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002514 // Virtual displays without a surface are dormant:
2515 // they have external state (layer stack, projection,
2516 // etc.) but no internal state (i.e. a DisplayDevice).
2517 if (state.surface != nullptr) {
2518 // Allow VR composer to use virtual displays.
2519 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2520 int width = 0;
2521 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2522 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2523 int height = 0;
2524 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2525 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2526 int intFormat = 0;
2527 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2528 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002529 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002530
Dominik Laskowski7e045462018-05-30 13:02:02 -07002531 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2532 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002533 }
2534
2535 // TODO: Plumb requested format back up to consumer
2536
2537 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002538 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002539 bqProducer, bqConsumer,
2540 state.displayName);
2541
2542 dispSurface = vds;
2543 producer = vds;
2544 }
2545 } else {
2546 ALOGE_IF(state.surface != nullptr,
2547 "adding a supported display, but rendering "
2548 "surface is provided (%p), ignoring it",
2549 state.surface.get());
2550
Dominik Laskowski7e045462018-05-30 13:02:02 -07002551 displayId = state.type;
2552 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002553 producer = bqProducer;
2554 }
2555
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002556 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002557 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002558 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002559 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002560 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002561 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002562 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002563 if (mUseScheduler) {
2564 mScheduler->hotplugReceived(mAppConnectionHandle,
2565 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002566 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002567 } else {
2568 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2569 true);
2570 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002571 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002572 if (mUseScheduler) {
2573 mScheduler->hotplugReceived(mAppConnectionHandle,
2574 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002575 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002576 } else {
2577 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2578 true);
2579 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002580 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002581 }
2582 }
2583 }
2584 }
2585 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002586
2587 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002588}
2589
Mathias Agopian87baae12012-07-31 12:38:26 -07002590void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002591{
Dan Stoza7dde5992015-05-22 09:51:44 -07002592 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002593 mCurrentState.traverseInZOrder([](Layer* layer) {
2594 layer->notifyAvailableFrames();
2595 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002596
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002597 /*
2598 * Traversal of the children
2599 * (perform the transaction for each of them if needed)
2600 */
2601
Mathias Agopian3559b072012-08-15 13:46:03 -07002602 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002603 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002604 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002605 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002606
2607 const uint32_t flags = layer->doTransaction(0);
2608 if (flags & Layer::eVisibleRegion)
2609 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002610 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002611 }
2612
2613 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002614 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002615 */
2616
Mathias Agopiane57f2922012-08-09 16:29:12 -07002617 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002618 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002619 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002620 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002621
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002622 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002623 // The transform hint might have changed for some layers
2624 // (either because a display has changed, or because a layer
2625 // as changed).
2626 //
2627 // Walk through all the layers in currentLayers,
2628 // and update their transform hint.
2629 //
2630 // If a layer is visible only on a single display, then that
2631 // display is used to calculate the hint, otherwise we use the
2632 // default display.
2633 //
2634 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2635 // the hint is set before we acquire a buffer from the surface texture.
2636 //
2637 // NOTE: layer transactions have taken place already, so we use their
2638 // drawing state. However, SurfaceFlinger's own transaction has not
2639 // happened yet, so we must use the current state layer list
2640 // (soon to become the drawing state list).
2641 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002642 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002643 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002644 bool first = true;
2645 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002646 // NOTE: we rely on the fact that layers are sorted by
2647 // layerStack first (so we don't have to traverse the list
2648 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002649 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002650 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002651 currentlayerStack = layerStack;
2652 // figure out if this layerstack is mirrored
2653 // (more than one display) if so, pick the default display,
2654 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002655 hintDisplay = nullptr;
2656 for (const auto& [token, display] : mDisplays) {
2657 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2658 if (hintDisplay) {
2659 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002660 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002661 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002662 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002663 }
2664 }
2665 }
2666 }
Chet Haase91d25932013-04-11 15:24:55 -07002667
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002668 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002669 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2670 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002671
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002672 // could be null when this layer is using a layerStack
2673 // that is not visible on any display. Also can occur at
2674 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002675 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002676 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002677
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002678 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002679 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002680 if (hintDisplay) {
2681 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002682 }
Robert Carr2047fae2016-11-28 14:09:09 -08002683
2684 first = false;
2685 });
Mathias Agopian84300952012-11-21 16:02:13 -08002686 }
2687
2688
Mathias Agopian3559b072012-08-15 13:46:03 -07002689 /*
2690 * Perform our own transaction if needed
2691 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002692
2693 if (mLayersAdded) {
2694 mLayersAdded = false;
2695 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002696 mVisibleRegionsDirty = true;
2697 }
2698
2699 // some layers might have been removed, so
2700 // we need to update the regions they're exposing.
2701 if (mLayersRemoved) {
2702 mLayersRemoved = false;
2703 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002704 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002705 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002706 // this layer is not visible anymore
2707 // TODO: we could traverse the tree from front to back and
2708 // compute the actual visible region
2709 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002710 Region visibleReg;
2711 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002712 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002713 }
Robert Carr2047fae2016-11-28 14:09:09 -08002714 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002715 }
2716
2717 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002718
2719 updateCursorAsync();
2720}
2721
2722void SurfaceFlinger::updateCursorAsync()
2723{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002724 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002725 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002726 continue;
2727 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002728
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002729 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2730 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002731 }
2732 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002733}
2734
2735void SurfaceFlinger::commitTransaction()
2736{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002737 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002738 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002739 for (const auto& l : mLayersPendingRemoval) {
2740 recordBufferingStats(l->getName().string(),
2741 l->getOccupancyHistory(true));
Jorim Jaggi10c985e2018-10-23 11:17:45 +00002742 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002743 }
2744 mLayersPendingRemoval.clear();
2745 }
2746
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002747 // If this transaction is part of a window animation then the next frame
2748 // we composite should be considered an animation as well.
2749 mAnimCompositionPending = mAnimTransactionPending;
2750
Mathias Agopian4fec8732012-06-29 14:12:52 -07002751 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002752 // clear the "changed" flags in current state
2753 mCurrentState.colorMatrixChanged = false;
2754
Robert Carr1f0a16a2016-10-24 16:27:39 -07002755 mDrawingState.traverseInZOrder([](Layer* layer) {
2756 layer->commitChildList();
2757 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002758 mTransactionPending = false;
2759 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002760 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002761}
2762
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002763void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2764 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002765 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002766 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002767
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002768 Region aboveOpaqueLayers;
2769 Region aboveCoveredLayers;
2770 Region dirty;
2771
Mathias Agopian87baae12012-07-31 12:38:26 -07002772 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002773
Robert Carr2047fae2016-11-28 14:09:09 -08002774 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002775 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002776 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002777
Jesse Hall01e29052013-02-19 16:13:35 -08002778 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002779 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002780 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002781 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002782
Mathias Agopianab028732010-03-16 16:41:46 -07002783 /*
2784 * opaqueRegion: area of a surface that is fully opaque.
2785 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002786 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002787
2788 /*
2789 * visibleRegion: area of a surface that is visible on screen
2790 * and not fully transparent. This is essentially the layer's
2791 * footprint minus the opaque regions above it.
2792 * Areas covered by a translucent surface are considered visible.
2793 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002794 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002795
2796 /*
2797 * coveredRegion: area of a surface that is covered by all
2798 * visible regions above it (which includes the translucent areas).
2799 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002800 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002801
Jesse Halla8026d22012-09-25 13:25:04 -07002802 /*
2803 * transparentRegion: area of a surface that is hinted to be completely
2804 * transparent. This is only used to tell when the layer has no visible
2805 * non-transparent regions and can be removed from the layer list. It
2806 * does not affect the visibleRegion of this layer or any layers
2807 * beneath it. The hint may not be correct if apps don't respect the
2808 * SurfaceView restrictions (which, sadly, some don't).
2809 */
2810 Region transparentRegion;
2811
Mathias Agopianab028732010-03-16 16:41:46 -07002812
2813 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002814 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002815 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002816 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002817 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002818 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002819 if (!visibleRegion.isEmpty()) {
2820 // Remove the transparent area from the visible region
2821 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002822 if (tr.preserveRects()) {
2823 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002824 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002825 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002826 // transformation too complex, can't do the
2827 // transparent region optimization.
2828 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002829 }
Mathias Agopianab028732010-03-16 16:41:46 -07002830 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002831
Mathias Agopianab028732010-03-16 16:41:46 -07002832 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002833 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002834 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002835 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002836 // the opaque region is the layer's footprint
2837 opaqueRegion = visibleRegion;
2838 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002839 }
2840 }
2841
Robert Carre5f4f692018-01-12 13:12:28 -08002842 if (visibleRegion.isEmpty()) {
2843 layer->clearVisibilityRegions();
2844 return;
2845 }
2846
Mathias Agopianab028732010-03-16 16:41:46 -07002847 // Clip the covered region to the visible region
2848 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2849
2850 // Update aboveCoveredLayers for next (lower) layer
2851 aboveCoveredLayers.orSelf(visibleRegion);
2852
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002853 // subtract the opaque region covered by the layers above us
2854 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002855
2856 // compute this layer's dirty region
2857 if (layer->contentDirty) {
2858 // we need to invalidate the whole region
2859 dirty = visibleRegion;
2860 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002861 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002862 layer->contentDirty = false;
2863 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002864 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002865 * the exposed region consists of two components:
2866 * 1) what's VISIBLE now and was COVERED before
2867 * 2) what's EXPOSED now less what was EXPOSED before
2868 *
2869 * note that (1) is conservative, we start with the whole
2870 * visible region but only keep what used to be covered by
2871 * something -- which mean it may have been exposed.
2872 *
2873 * (2) handles areas that were not covered by anything but got
2874 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002875 */
Mathias Agopianab028732010-03-16 16:41:46 -07002876 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002877 const Region oldVisibleRegion = layer->visibleRegion;
2878 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002879 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2880 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002881 }
2882 dirty.subtractSelf(aboveOpaqueLayers);
2883
2884 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002885 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002886
Mathias Agopianab028732010-03-16 16:41:46 -07002887 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002888 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002889
Jesse Halla8026d22012-09-25 13:25:04 -07002890 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002891 layer->setVisibleRegion(visibleRegion);
2892 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002893 layer->setVisibleNonTransparentRegion(
2894 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002895 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002896
Mathias Agopian87baae12012-07-31 12:38:26 -07002897 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002898}
2899
Chia-I Wuab0c3192017-08-01 11:29:00 -07002900void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002901 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002902 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2903 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002904 }
2905 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002906}
2907
Dan Stoza6b9454d2014-11-07 16:00:59 -08002908bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002909{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002910 ALOGV("handlePageFlip");
2911
Brian Andersond6927fb2016-07-23 23:37:30 -07002912 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002913
Mathias Agopian4fec8732012-06-29 14:12:52 -07002914 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002915 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002916 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002917
2918 // Store the set of layers that need updates. This set must not change as
2919 // buffers are being latched, as this could result in a deadlock.
2920 // Example: Two producers share the same command stream and:
2921 // 1.) Layer 0 is latched
2922 // 2.) Layer 0 gets a new frame
2923 // 2.) Layer 1 gets a new frame
2924 // 3.) Layer 1 is latched.
2925 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2926 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002927 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002928 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002929 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002930 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2931 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002932 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002933 } else {
2934 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002935 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002936 } else {
2937 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002938 }
Robert Carr2047fae2016-11-28 14:09:09 -08002939 });
2940
Dan Stoza9e56aa02015-11-02 13:00:03 -08002941 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri86770e52018-09-24 22:40:58 +00002942 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
Dan Stozaee44edd2015-03-23 15:50:23 -07002943 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002944 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002945 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002946 newDataLatched = true;
2947 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002948 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002949
Alec Mouri86770e52018-09-24 22:40:58 +00002950 // Clear the renderengine fence here...
2951 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
2952 // clear instead of sp::clear.
2953 getBE().flushFence = Fence::NO_FENCE;
2954
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002955 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002956
2957 // If we will need to wake up at some time in the future to deal with a
2958 // queued frame that shouldn't be displayed during this vsync period, wake
2959 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002960 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002961 signalLayerUpdate();
2962 }
2963
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002964 // enter boot animation on first buffer latch
2965 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2966 ALOGI("Enter boot animation");
2967 mBootStage = BootStage::BOOTANIMATION;
2968 }
2969
Dan Stoza6b9454d2014-11-07 16:00:59 -08002970 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002971 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002972}
2973
Mathias Agopianad456f92011-01-13 17:53:01 -08002974void SurfaceFlinger::invalidateHwcGeometry()
2975{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002976 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002977}
2978
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002979void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2980 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002981 // We only need to actually compose the display if:
2982 // 1) It is being handled by hardware composer, which may need this to
2983 // keep its virtual display state machine in sync, or
2984 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002985 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002986 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002987 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002988 return;
2989 }
2990
Dan Stoza9e56aa02015-11-02 13:00:03 -08002991 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002992 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002993
2994 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002995 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002996}
2997
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002998bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002999 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003000
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003001 const Region bounds(display->bounds());
3002 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003003 const auto displayId = display->getId();
3004 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003005 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003006
Peiyong Lind3788632018-09-18 16:01:31 -07003007 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003008 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003009 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003010
Dan Stoza9e56aa02015-11-02 13:00:03 -08003011 if (hasClientComposition) {
3012 ALOGV("hasClientComposition");
3013
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003014 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003015 if (display->hasWideColorGamut()) {
3016 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003017 }
3018 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003019 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003020 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003021
Dominik Laskowski7e045462018-05-30 13:02:02 -07003022 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003023 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3024 HWC2::Capability::SkipClientColorTransform);
3025
Peiyong Lind3788632018-09-18 16:01:31 -07003026 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003027 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3028 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003029 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003030 }
3031
Chia-I Wud49d6692018-06-27 07:17:41 +08003032 // The current enhanced saturation matrix is designed to enhance Display P3,
3033 // thus we only apply this matrix when the render intent is not colorimetric
3034 // and the output color space is Display P3.
3035 needsEnhancedColorMatrix =
3036 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3037 outputDataspace == Dataspace::DISPLAY_P3);
3038 if (needsEnhancedColorMatrix) {
3039 colorMatrix *= mEnhancedSaturationMatrix;
3040 }
3041
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003042 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003043 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003044 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003045 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003046
3047 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003048 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3049 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3050 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003051 }
3052 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003053 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003054
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003055 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003056 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003057 // when using overlays, we assume a fully transparent framebuffer
3058 // NOTE: we could reduce how much we need to clear, for instance
3059 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003060 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003061 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003062 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003063 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003064 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003065 // we're left with the letterbox region
3066 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003067 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003068
3069 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003070 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003071
Mathias Agopianb9494d52012-04-18 02:28:45 -07003072 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003073 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003074 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003075 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003076 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003077 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003078
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003079 const Rect& bounds = display->getBounds();
3080 const Rect& scissor = display->getScissor();
3081 if (scissor != bounds) {
3082 // scissor doesn't match the screen's dimensions, so we
3083 // need to clear everything outside of it and enable
3084 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003085
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003086 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003087 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003088 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003089 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003090
Mathias Agopian85d751c2012-08-29 16:59:24 -07003091 /*
3092 * and then, render the layers targeted at the framebuffer
3093 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003094
Dan Stoza9e56aa02015-11-02 13:00:03 -08003095 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003096 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003097 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003098 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003099 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003100 displayTransform.transform(layer->visibleRegion)));
3101 ALOGV("Layer: %s", layer->getName().string());
3102 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003103 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003104 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003105 case HWC2::Composition::Cursor:
3106 case HWC2::Composition::Device:
3107 case HWC2::Composition::Sideband:
3108 case HWC2::Composition::SolidColor: {
David Sodmanc1498e62018-09-12 14:36:26 -07003109 const Layer::State& state(layer->getDrawingState());
3110 if (layer->getClearClientTarget(displayId) && !firstLayer &&
3111 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3112 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003113 // never clear the very first layer since we're
3114 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003115 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003116 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003117 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003118 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003119 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003120 if (layer->hasColorTransform()) {
3121 mat4 tmpMatrix;
3122 if (applyColorMatrix) {
3123 tmpMatrix = mDrawingState.colorMatrix;
3124 }
3125 tmpMatrix *= layer->getColorTransform();
3126 if (needsEnhancedColorMatrix) {
3127 tmpMatrix *= mEnhancedSaturationMatrix;
3128 }
3129 getRenderEngine().setColorTransform(tmpMatrix);
3130 } else {
3131 getRenderEngine().setColorTransform(colorMatrix);
3132 }
David Sodmanc1498e62018-09-12 14:36:26 -07003133 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003134 break;
3135 }
3136 default:
3137 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003138 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003139 } else {
3140 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003141 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003142 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003143 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003144
Peiyong Lind3788632018-09-18 16:01:31 -07003145 // Clear color transform matrix at the end of the frame.
3146 getRenderEngine().setColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003147
Mathias Agopianf45c5102012-10-24 16:29:17 -07003148 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003149 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003150 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003151}
3152
Chia-I Wu28e3a252018-09-07 12:05:02 -07003153void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003154 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003155 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003156}
3157
Dan Stoza7d89d062015-04-30 13:29:25 -07003158status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003159 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003160 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003161 const sp<Layer>& lbc,
3162 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003163{
Dan Stoza7d89d062015-04-30 13:29:25 -07003164 // add this layer to the current state list
3165 {
3166 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003167 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003168 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3169 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003170 return NO_MEMORY;
3171 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003172 if (parent == nullptr) {
3173 mCurrentState.layersSortedByZ.add(lbc);
3174 } else {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003175 if (parent->isPendingRemoval()) {
3176 ALOGE("addClientLayer called with a removed parent");
3177 return NAME_NOT_FOUND;
3178 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003179 parent->addChild(lbc);
3180 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003181
Yiwei Zhang243b3782018-05-15 17:40:04 -07003182 if (gbc != nullptr) {
3183 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3184 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3185 mMaxGraphicBufferProducerListSize,
3186 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3187 mGraphicBufferProducerList.size(),
3188 mMaxGraphicBufferProducerListSize, mNumLayers);
3189 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003190 mLayersAdded = true;
3191 mNumLayers++;
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
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003205status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
chaviwca27f252018-02-06 16:46:39 -08003206 bool topLevelOnly) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003207 if (layer->isPendingRemoval()) {
3208 return NO_ERROR;
3209 }
3210
Robert Carr1f0a16a2016-10-24 16:27:39 -07003211 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003212 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003213 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003214 if (topLevelOnly) {
3215 return NO_ERROR;
3216 }
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003217
3218 sp<Layer> ancestor = p;
3219 while (ancestor->getParent() != nullptr) {
3220 ancestor = ancestor->getParent();
3221 }
3222 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3223 ALOGE("removeLayer called with a layer whose parent has been removed");
3224 return NAME_NOT_FOUND;
3225 }
3226
Chia-I Wufae51c42017-06-15 12:53:59 -07003227 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003228 } else {
3229 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003230 }
3231
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003232 // As a matter of normal operation, the LayerCleaner will produce a second
3233 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3234 // so we will succeed in promoting it, but it's already been removed
3235 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3236 // otherwise something has gone wrong and we are leaking the layer.
3237 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
3238 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3239 layer->getName().string(),
3240 (p != nullptr) ? p->getName().string() : "no-parent");
3241 return BAD_VALUE;
3242 } else if (index < 0) {
3243 return NO_ERROR;
3244 }
Robert Carrf478f9f2018-10-15 12:43:33 -07003245
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003246 layer->onRemovedFromCurrentState();
3247 mLayersPendingRemoval.add(layer);
3248 mLayersRemoved = true;
3249 mNumLayers -= 1 + layer->getChildrenCount();
3250 setTransactionFlags(eTransactionNeeded);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003251 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003252}
3253
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003254uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003255 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003256}
3257
Mathias Agopian3f844832013-08-07 21:24:32 -07003258uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003259 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003260}
3261
Mathias Agopian3f844832013-08-07 21:24:32 -07003262uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003263 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003264}
3265
3266uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003267 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003268 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003269 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003270 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003271 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003272 }
3273 return old;
3274}
3275
chaviwca27f252018-02-06 16:46:39 -08003276bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3277 for (const ComposerState& state : states) {
3278 // Here we need to check that the interface we're given is indeed
3279 // one of our own. A malicious client could give us a nullptr
3280 // IInterface, or one of its own or even one of our own but a
3281 // different type. All these situations would cause us to crash.
3282 if (state.client == nullptr) {
3283 return true;
3284 }
3285
3286 sp<IBinder> binder = IInterface::asBinder(state.client);
3287 if (binder == nullptr) {
3288 return true;
3289 }
3290
3291 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3292 return true;
3293 }
3294 }
3295 return false;
3296}
3297
Mathias Agopian8b33f032012-07-24 20:43:54 -07003298void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003299 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003300 const Vector<DisplayState>& displays,
3301 uint32_t flags)
3302{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003303 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003304 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003305 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003306
chaviwca27f252018-02-06 16:46:39 -08003307 if (containsAnyInvalidClientState(states)) {
3308 return;
3309 }
3310
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003311 if (flags & eAnimation) {
3312 // For window updates that are part of an animation we must wait for
3313 // previous animation "frames" to be handled.
3314 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003315 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003316 if (CC_UNLIKELY(err != NO_ERROR)) {
3317 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003318 // caller after a few seconds.
3319 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3320 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003321 mAnimTransactionPending = false;
3322 break;
3323 }
3324 }
3325 }
3326
chaviwca27f252018-02-06 16:46:39 -08003327 for (const DisplayState& display : displays) {
3328 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003329 }
3330
chaviwca27f252018-02-06 16:46:39 -08003331 for (const ComposerState& state : states) {
3332 transactionFlags |= setClientStateLocked(state);
3333 }
3334
3335 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3336 // as destroyed should only occur after setting all other states. This is to allow for a
3337 // child re-parent to happen before marking its original parent as destroyed (which would
3338 // then mark the child as destroyed).
3339 for (const ComposerState& state : states) {
3340 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003341 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003342
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003343 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3344 // anyway. This can be used as a flush mechanism for previous async transactions.
3345 // Empty animation transaction can be used to simulate back-pressure, so also force a
3346 // transaction for empty animation transactions.
3347 if (transactionFlags == 0 &&
3348 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003349 transactionFlags = eTransactionNeeded;
3350 }
3351
Mathias Agopian386aa982011-11-07 21:58:03 -08003352 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003353 if (mInterceptor->isEnabled()) {
3354 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003355 }
Irvel468051e2016-06-13 16:44:44 -07003356
Mathias Agopian386aa982011-11-07 21:58:03 -08003357 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003358 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3359 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003360 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003361
3362 // if this is a synchronous transaction, wait for it to take effect
3363 // before returning.
3364 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003365 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003366 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003367 if (flags & eAnimation) {
3368 mAnimTransactionPending = true;
3369 }
3370 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003371 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3372 if (CC_UNLIKELY(err != NO_ERROR)) {
3373 // just in case something goes wrong in SF, return to the
3374 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003375 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3376 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003377 break;
3378 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003379 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003380 }
3381}
3382
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003383uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3384 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3385 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003386
Mathias Agopiane57f2922012-08-09 16:29:12 -07003387 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003388 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3389
3390 const uint32_t what = s.what;
3391 if (what & DisplayState::eSurfaceChanged) {
3392 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3393 state.surface = s.surface;
3394 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003395 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003396 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003397 if (what & DisplayState::eLayerStackChanged) {
3398 if (state.layerStack != s.layerStack) {
3399 state.layerStack = s.layerStack;
3400 flags |= eDisplayTransactionNeeded;
3401 }
3402 }
3403 if (what & DisplayState::eDisplayProjectionChanged) {
3404 if (state.orientation != s.orientation) {
3405 state.orientation = s.orientation;
3406 flags |= eDisplayTransactionNeeded;
3407 }
3408 if (state.frame != s.frame) {
3409 state.frame = s.frame;
3410 flags |= eDisplayTransactionNeeded;
3411 }
3412 if (state.viewport != s.viewport) {
3413 state.viewport = s.viewport;
3414 flags |= eDisplayTransactionNeeded;
3415 }
3416 }
3417 if (what & DisplayState::eDisplaySizeChanged) {
3418 if (state.width != s.width) {
3419 state.width = s.width;
3420 flags |= eDisplayTransactionNeeded;
3421 }
3422 if (state.height != s.height) {
3423 state.height = s.height;
3424 flags |= eDisplayTransactionNeeded;
3425 }
3426 }
3427
Mathias Agopiane57f2922012-08-09 16:29:12 -07003428 return flags;
3429}
3430
Robert Carrd4ae7f32018-06-07 16:10:57 -07003431bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3432 IPCThreadState* ipc = IPCThreadState::self();
3433 const int pid = ipc->getCallingPid();
3434 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003435 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003436 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003437 return false;
3438 }
3439 return true;
3440}
3441
chaviwca27f252018-02-06 16:46:39 -08003442uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3443 const layer_state_t& s = composerState.state;
3444 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3445
Mathias Agopian13127d82013-03-05 17:47:11 -08003446 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003447 if (layer == nullptr) {
3448 return 0;
3449 }
3450
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003451 if (layer->isPendingRemoval()) {
3452 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3453 return 0;
3454 }
3455
chaviw8b3871a2017-11-01 17:41:01 -07003456 uint32_t flags = 0;
3457
3458 const uint32_t what = s.what;
3459 bool geometryAppliesWithResize =
3460 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003461
3462 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3463 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003464 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003465 layer->pushPendingState();
3466 }
3467
chaviw8b3871a2017-11-01 17:41:01 -07003468 if (what & layer_state_t::ePositionChanged) {
3469 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3470 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003471 }
chaviw8b3871a2017-11-01 17:41:01 -07003472 }
3473 if (what & layer_state_t::eLayerChanged) {
3474 // NOTE: index needs to be calculated before we update the state
3475 const auto& p = layer->getParent();
3476 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003477 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003478 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003479 mCurrentState.layersSortedByZ.removeAt(idx);
3480 mCurrentState.layersSortedByZ.add(layer);
3481 // we need traversal (state changed)
3482 // AND transaction (list changed)
3483 flags |= eTransactionNeeded|eTraversalNeeded;
3484 }
chaviw8b3871a2017-11-01 17:41:01 -07003485 } else {
3486 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003487 flags |= eTransactionNeeded|eTraversalNeeded;
3488 }
3489 }
chaviw8b3871a2017-11-01 17:41:01 -07003490 }
3491 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003492 // NOTE: index needs to be calculated before we update the state
3493 const auto& p = layer->getParent();
3494 if (p == nullptr) {
3495 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3496 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3497 mCurrentState.layersSortedByZ.removeAt(idx);
3498 mCurrentState.layersSortedByZ.add(layer);
3499 // we need traversal (state changed)
3500 // AND transaction (list changed)
3501 flags |= eTransactionNeeded|eTraversalNeeded;
3502 }
3503 } else {
3504 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3505 flags |= eTransactionNeeded|eTraversalNeeded;
3506 }
chaviw8b3871a2017-11-01 17:41:01 -07003507 }
3508 }
3509 if (what & layer_state_t::eSizeChanged) {
3510 if (layer->setSize(s.w, s.h)) {
3511 flags |= eTraversalNeeded;
3512 }
3513 }
3514 if (what & layer_state_t::eAlphaChanged) {
3515 if (layer->setAlpha(s.alpha))
3516 flags |= eTraversalNeeded;
3517 }
3518 if (what & layer_state_t::eColorChanged) {
3519 if (layer->setColor(s.color))
3520 flags |= eTraversalNeeded;
3521 }
Peiyong Lind3788632018-09-18 16:01:31 -07003522 if (what & layer_state_t::eColorTransformChanged) {
3523 if (layer->setColorTransform(s.colorTransform)) {
3524 flags |= eTraversalNeeded;
3525 }
3526 }
chaviw8b3871a2017-11-01 17:41:01 -07003527 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003528 // TODO: b/109894387
3529 //
3530 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3531 // rotation. To see the problem observe that if we have a square parent, and a child
3532 // of the same size, then we rotate the child 45 degrees around it's center, the child
3533 // must now be cropped to a non rectangular 8 sided region.
3534 //
3535 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3536 // private API, and the WindowManager only uses rotation in one case, which is on a top
3537 // level layer in which cropping is not an issue.
3538 //
3539 // However given that abuse of rotation matrices could lead to surfaces extending outside
3540 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3541 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3542 // transformations.
3543 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003544 flags |= eTraversalNeeded;
3545 }
3546 if (what & layer_state_t::eTransparentRegionChanged) {
3547 if (layer->setTransparentRegionHint(s.transparentRegion))
3548 flags |= eTraversalNeeded;
3549 }
3550 if (what & layer_state_t::eFlagsChanged) {
3551 if (layer->setFlags(s.flags, s.mask))
3552 flags |= eTraversalNeeded;
3553 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003554 if (what & layer_state_t::eCropChanged_legacy) {
3555 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003556 flags |= eTraversalNeeded;
3557 }
chaviw8b3871a2017-11-01 17:41:01 -07003558 if (what & layer_state_t::eLayerStackChanged) {
3559 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3560 // We only allow setting layer stacks for top level layers,
3561 // everything else inherits layer stack from its parent.
3562 if (layer->hasParent()) {
3563 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3564 layer->getName().string());
3565 } else if (idx < 0) {
3566 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3567 "that also does not appear in the top level layer list. Something"
3568 " has gone wrong.", layer->getName().string());
3569 } else if (layer->setLayerStack(s.layerStack)) {
3570 mCurrentState.layersSortedByZ.removeAt(idx);
3571 mCurrentState.layersSortedByZ.add(layer);
3572 // we need traversal (state changed)
3573 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003574 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003575 }
3576 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003577 if (what & layer_state_t::eDeferTransaction_legacy) {
3578 if (s.barrierHandle_legacy != nullptr) {
3579 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3580 } else if (s.barrierGbp_legacy != nullptr) {
3581 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003582 if (authenticateSurfaceTextureLocked(gbp)) {
3583 const auto& otherLayer =
3584 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003585 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003586 } else {
3587 ALOGE("Attempt to defer transaction to to an"
3588 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003589 }
3590 }
chaviw8b3871a2017-11-01 17:41:01 -07003591 // We don't trigger a traversal here because if no other state is
3592 // changed, we don't want this to cause any more work
3593 }
3594 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003595 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003596 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003597 if (!hadParent) {
3598 mCurrentState.layersSortedByZ.remove(layer);
3599 }
chaviw8b3871a2017-11-01 17:41:01 -07003600 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003601 }
chaviw8b3871a2017-11-01 17:41:01 -07003602 }
3603 if (what & layer_state_t::eReparentChildren) {
3604 if (layer->reparentChildren(s.reparentHandle)) {
3605 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003606 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003607 }
chaviw8b3871a2017-11-01 17:41:01 -07003608 if (what & layer_state_t::eDetachChildren) {
3609 layer->detachChildren();
3610 }
3611 if (what & layer_state_t::eOverrideScalingModeChanged) {
3612 layer->setOverrideScalingMode(s.overrideScalingMode);
3613 // We don't trigger a traversal here because if no other state is
3614 // changed, we don't want this to cause any more work
3615 }
Marissa Wall61c58622018-07-18 10:12:20 -07003616 if (what & layer_state_t::eTransformChanged) {
3617 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3618 }
3619 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3620 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3621 flags |= eTraversalNeeded;
3622 }
3623 if (what & layer_state_t::eCropChanged) {
3624 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3625 }
3626 if (what & layer_state_t::eBufferChanged) {
3627 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3628 }
3629 if (what & layer_state_t::eAcquireFenceChanged) {
3630 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3631 }
3632 if (what & layer_state_t::eDataspaceChanged) {
3633 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3634 }
3635 if (what & layer_state_t::eHdrMetadataChanged) {
3636 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3637 }
3638 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3639 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3640 }
3641 if (what & layer_state_t::eApiChanged) {
3642 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3643 }
3644 if (what & layer_state_t::eSidebandStreamChanged) {
3645 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3646 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003647 return flags;
3648}
3649
chaviwca27f252018-02-06 16:46:39 -08003650void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3651 const layer_state_t& state = composerState.state;
3652 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3653
3654 sp<Layer> layer(client->getLayerUser(state.surface));
3655 if (layer == nullptr) {
3656 return;
3657 }
3658
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003659 if (layer->isPendingRemoval()) {
3660 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3661 return;
3662 }
3663
chaviwca27f252018-02-06 16:46:39 -08003664 if (state.what & layer_state_t::eDestroySurface) {
3665 removeLayerLocked(mStateLock, layer);
3666 }
3667}
3668
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003669status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003670 const String8& name,
3671 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003672 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003673 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003674 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003675{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003676 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003677 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003678 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003679 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003680 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003681
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003682 status_t result = NO_ERROR;
3683
3684 sp<Layer> layer;
3685
Cody Northropbc755282017-03-31 12:00:08 -06003686 String8 uniqueName = getUniqueLayerName(name);
3687
Mathias Agopian3165cc22012-08-08 19:42:09 -07003688 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003689 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003690 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3691 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003692
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003693 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003694 case ISurfaceComposerClient::eFXSurfaceBufferState:
3695 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3696 break;
chaviw13fdc492017-06-27 12:40:18 -07003697 case ISurfaceComposerClient::eFXSurfaceColor:
3698 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003699 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003700 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003701 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003702 case ISurfaceComposerClient::eFXSurfaceContainer:
3703 result = createContainerLayer(client,
3704 uniqueName, w, h, flags,
3705 handle, &layer);
3706 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003707 default:
3708 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003709 break;
3710 }
3711
Dan Stoza7d89d062015-04-30 13:29:25 -07003712 if (result != NO_ERROR) {
3713 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003714 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003715
Chia-I Wuab0c3192017-08-01 11:29:00 -07003716 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3717 // TODO b/64227542
3718 if (windowType == 441731) {
3719 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3720 layer->setPrimaryDisplayOnly();
3721 }
3722
Albert Chaulk479c60c2017-01-27 14:21:34 -05003723 layer->setInfo(windowType, ownerUid);
3724
Robert Carr1f0a16a2016-10-24 16:27:39 -07003725 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003726 if (result != NO_ERROR) {
3727 return result;
3728 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003729 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003730
3731 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003732 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003733}
3734
Cody Northropbc755282017-03-31 12:00:08 -06003735String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3736{
3737 bool matchFound = true;
3738 uint32_t dupeCounter = 0;
3739
3740 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3741 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3742
Dan Stoza436ccf32018-06-21 12:10:12 -07003743 // Grab the state lock since we're accessing mCurrentState
3744 Mutex::Autolock lock(mStateLock);
3745
Cody Northropbc755282017-03-31 12:00:08 -06003746 // Loop over layers until we're sure there is no matching name
3747 while (matchFound) {
3748 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003749 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003750 if (layer->getName() == uniqueName) {
3751 matchFound = true;
3752 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3753 }
3754 });
3755 }
3756
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003757 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3758 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003759
3760 return uniqueName;
3761}
3762
Marissa Wallfd668622018-05-10 10:21:13 -07003763status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3764 uint32_t w, uint32_t h, uint32_t flags,
3765 PixelFormat& format, sp<IBinder>* handle,
3766 sp<IGraphicBufferProducer>* gbp,
3767 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003768 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003769 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003770 case PIXEL_FORMAT_TRANSPARENT:
3771 case PIXEL_FORMAT_TRANSLUCENT:
3772 format = PIXEL_FORMAT_RGBA_8888;
3773 break;
3774 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003775 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003776 break;
3777 }
3778
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003779 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003780 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003781 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003782 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003783 *handle = layer->getHandle();
3784 *gbp = layer->getProducer();
3785 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003786 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003787
Marissa Wallfd668622018-05-10 10:21:13 -07003788 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003789 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003790}
3791
Marissa Wall61c58622018-07-18 10:12:20 -07003792status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3793 uint32_t w, uint32_t h, uint32_t flags,
3794 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003795 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003796 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003797 *handle = layer->getHandle();
3798 *outLayer = layer;
3799
3800 return NO_ERROR;
3801}
3802
chaviw13fdc492017-06-27 12:40:18 -07003803status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003804 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003805 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003806{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003807 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003808 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003809 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003810}
3811
Robert Carr6b3f6c52018-08-13 13:05:17 -07003812status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3813 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3814 sp<IBinder>* handle, sp<Layer>* outLayer)
3815{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003816 *outLayer =
3817 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003818 *handle = (*outLayer)->getHandle();
3819 return NO_ERROR;
3820}
3821
3822
Mathias Agopianac9fa422013-02-11 16:40:36 -08003823status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003824{
Robert Carr9524cb32017-02-13 11:32:32 -08003825 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003826 status_t err = NO_ERROR;
3827 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003828 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003829 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003830 err = removeLayer(l);
3831 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3832 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003833 }
3834 return err;
3835}
3836
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003837status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003838{
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003839 // called by ~LayerCleaner() when all references to the IBinder (handle)
3840 // are gone
3841 sp<Layer> l = layer.promote();
3842 if (l == nullptr) {
3843 // The layer has already been removed, carry on
3844 return NO_ERROR;
3845 }
3846 // If we have a parent, then we can continue to live as long as it does.
3847 return removeLayer(l, true);
Rob Carr4bba3702018-10-08 21:53:30 +00003848}
3849
Mathias Agopianb60314a2012-04-10 22:09:54 -07003850// ---------------------------------------------------------------------------
3851
Andy McFadden13a082e2012-08-24 10:16:42 -07003852void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003853 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3854 if (!displayToken) return;
3855
Jesse Hall01e29052013-02-19 16:13:35 -08003856 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003857 Vector<ComposerState> state;
3858 Vector<DisplayState> displays;
3859 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003860 d.what = DisplayState::eDisplayProjectionChanged |
3861 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003862 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003863 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003864 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003865 d.frame.makeInvalid();
3866 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003867 d.width = 0;
3868 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003869 displays.add(d);
3870 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003871
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003872 const auto display = getDisplayDevice(displayToken);
3873 if (!display) return;
3874
3875 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3876
3877 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003878 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003879 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003880
Brian Andersond0010582017-03-07 13:20:31 -08003881 // Use phase of 0 since phase is not known.
3882 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07003883 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
3884 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003885}
3886
3887void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003888 // Async since we may be called from the main thread.
3889 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003890}
3891
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003892void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3893 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003894 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003895 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003896
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003897 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003898 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003899 return;
3900 }
3901
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003902 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003903 ALOGW("Trying to set power mode for virtual display");
3904 return;
3905 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003906
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003907 display->setPowerMode(mode);
3908
Lloyd Pique4dccc412018-01-22 17:21:36 -08003909 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003910 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003911 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003912 if (idx < 0) {
3913 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3914 return;
3915 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003916 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003917 }
3918
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003919 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003920 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003921 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003922 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003923 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003924 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003925 if (mUseScheduler) {
3926 mScheduler->onScreenAcquired(mAppConnectionHandle);
3927 } else {
3928 mEventThread->onScreenAcquired();
3929 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07003930 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003931 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003932
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003933 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003934 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003935 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003936
3937 struct sched_param param = {0};
3938 param.sched_priority = 1;
3939 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3940 ALOGW("Couldn't set SCHED_FIFO on display on");
3941 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003942 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003943 // Turn off the display
3944 struct sched_param param = {0};
3945 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3946 ALOGW("Couldn't set SCHED_OTHER on display off");
3947 }
3948
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003949 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07003950 if (mUseScheduler) {
3951 mScheduler->disableHardwareVsync(true);
3952 } else {
3953 disableHardwareVsync(true); // also cancels any in-progress resync
3954 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07003955 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003956 if (mUseScheduler) {
3957 mScheduler->onScreenReleased(mAppConnectionHandle);
3958 } else {
3959 mEventThread->onScreenReleased();
3960 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07003961 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003962
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003963 getHwComposer().setPowerMode(type, mode);
3964 mVisibleRegionsDirty = true;
3965 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003966 } else if (mode == HWC_POWER_MODE_DOZE ||
3967 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003968 // Update display while dozing
3969 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003970 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003971 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003972 if (mUseScheduler) {
3973 mScheduler->onScreenAcquired(mAppConnectionHandle);
3974 } else {
3975 mEventThread->onScreenAcquired();
3976 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003977 resyncToHardwareVsync(true);
3978 }
3979 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3980 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003981 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07003982 if (mUseScheduler) {
3983 mScheduler->disableHardwareVsync(true);
3984 } else {
3985 disableHardwareVsync(true); // also cancels any in-progress resync
3986 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003987 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003988 if (mUseScheduler) {
3989 mScheduler->onScreenReleased(mAppConnectionHandle);
3990 } else {
3991 mEventThread->onScreenReleased();
3992 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003993 }
3994 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003995 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003996 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003997 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003998 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003999
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004000 if (display->isPrimary()) {
4001 mTimeStats.setPowerMode(mode);
4002 }
4003
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004004 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004005}
4006
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004007void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004008 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004009 const auto display = getDisplayDevice(displayToken);
4010 if (!display) {
4011 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4012 displayToken.get());
4013 } else if (display->isVirtual()) {
4014 ALOGW("Attempt to set power mode %d for virtual display", mode);
4015 } else {
4016 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004017 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004018 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004019}
4020
4021// ---------------------------------------------------------------------------
4022
Lloyd Pique755e3192018-01-31 16:46:15 -08004023status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4024 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004025 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004026
Mathias Agopianbd115332013-04-18 16:41:04 -07004027 IPCThreadState* ipc = IPCThreadState::self();
4028 const int pid = ipc->getCallingPid();
4029 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004030
Mathias Agopianbd115332013-04-18 16:41:04 -07004031 if ((uid != AID_SHELL) &&
4032 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004033 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004034 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004035 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004036 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004037 // (this would indicate SF is stuck, but we want to be able to
4038 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004039 status_t err = mStateLock.timedLock(s2ns(1));
4040 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004041 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004042 result.appendFormat(
4043 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4044 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004045 }
4046
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004047 bool dumpAll = true;
4048 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004049 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004050
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004051 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004052 if ((index < numArgs) &&
4053 (args[index] == String16("--list"))) {
4054 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004055 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004056 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004057 }
4058
4059 if ((index < numArgs) &&
4060 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004061 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004062 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004063 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004064 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004065
4066 if ((index < numArgs) &&
4067 (args[index] == String16("--latency-clear"))) {
4068 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004069 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004070 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004071 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004072
4073 if ((index < numArgs) &&
4074 (args[index] == String16("--dispsync"))) {
4075 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004076 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004077 dumpAll = false;
4078 }
Dan Stozab90cf072015-03-05 11:05:59 -08004079
4080 if ((index < numArgs) &&
4081 (args[index] == String16("--static-screen"))) {
4082 index++;
4083 dumpStaticScreenStats(result);
4084 dumpAll = false;
4085 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004086
4087 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004088 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004089 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004090 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004091 dumpAll = false;
4092 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004093
4094 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4095 index++;
4096 dumpWideColorInfo(result);
4097 dumpAll = false;
4098 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004099
4100 if ((index < numArgs) &&
4101 (args[index] == String16("--enable-layer-stats"))) {
4102 index++;
4103 mLayerStats.enable();
4104 dumpAll = false;
4105 }
4106
4107 if ((index < numArgs) &&
4108 (args[index] == String16("--disable-layer-stats"))) {
4109 index++;
4110 mLayerStats.disable();
4111 dumpAll = false;
4112 }
4113
4114 if ((index < numArgs) &&
4115 (args[index] == String16("--clear-layer-stats"))) {
4116 index++;
4117 mLayerStats.clear();
4118 dumpAll = false;
4119 }
4120
4121 if ((index < numArgs) &&
4122 (args[index] == String16("--dump-layer-stats"))) {
4123 index++;
4124 mLayerStats.dump(result);
4125 dumpAll = false;
4126 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004127
4128 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004129 (args[index] == String16("--frame-composition"))) {
4130 index++;
4131 dumpFrameCompositionInfo(result);
4132 dumpAll = false;
4133 }
4134
4135 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004136 (args[index] == String16("--display-identification"))) {
4137 index++;
4138 dumpDisplayIdentificationData(result);
4139 dumpAll = false;
4140 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004141
4142 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4143 index++;
4144 mTimeStats.parseArgs(asProto, args, index, result);
4145 dumpAll = false;
4146 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004147 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004148
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004149 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004150 if (asProto) {
4151 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4152 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4153 } else {
4154 dumpAllLocked(args, index, result);
4155 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004156 }
4157
Mathias Agopian9795c422009-08-26 16:36:26 -07004158 if (locked) {
4159 mStateLock.unlock();
4160 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004161 }
4162 write(fd, result.string(), result.size());
4163 return NO_ERROR;
4164}
4165
Dan Stozac7014012014-02-14 15:03:43 -08004166void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4167 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004168{
Robert Carr2047fae2016-11-28 14:09:09 -08004169 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004170 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004171 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004172}
4173
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004174void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004175 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004176{
4177 String8 name;
4178 if (index < args.size()) {
4179 name = String8(args[index]);
4180 index++;
4181 }
4182
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004183 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4184 getHwComposer().isConnected(displayId)) {
4185 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4186 const nsecs_t period = activeConfig->getVsyncPeriod();
4187 result.appendFormat("%" PRId64 "\n", period);
4188 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004189
4190 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004191 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004192 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004193 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004194 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004195 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004196 }
Robert Carr2047fae2016-11-28 14:09:09 -08004197 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004198 }
4199}
4200
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004201void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004202 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004203{
4204 String8 name;
4205 if (index < args.size()) {
4206 name = String8(args[index]);
4207 index++;
4208 }
4209
Robert Carr2047fae2016-11-28 14:09:09 -08004210 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004211 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004212 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004213 }
Robert Carr2047fae2016-11-28 14:09:09 -08004214 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004215
Svetoslavd85084b2014-03-20 10:28:31 -07004216 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004217}
4218
Jamie Gennis6547ff42013-07-16 20:12:42 -07004219// This should only be called from the main thread. Otherwise it would need
4220// the lock and should use mCurrentState rather than mDrawingState.
4221void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004222 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004223 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004224 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004225
4226 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4227}
4228
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004229void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004230{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004231 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004232
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004233 if (isLayerTripleBufferingDisabled())
4234 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004235
4236 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004237 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004238 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004239 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004240 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4241 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004242 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004243}
4244
Dan Stozab90cf072015-03-05 11:05:59 -08004245void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4246{
4247 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004248 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4249 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004250 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004251 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004252 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4253 b + 1, bucketTimeSec, percent);
4254 }
David Sodman4a36e932017-11-07 14:29:47 -08004255 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004256 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004257 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004258 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004259 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004260}
4261
Dan Stozae77c7662016-05-13 11:37:28 -07004262void SurfaceFlinger::recordBufferingStats(const char* layerName,
4263 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004264 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4265 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004266 for (const auto& segment : history) {
4267 if (!segment.usedThirdBuffer) {
4268 stats.twoBufferTime += segment.totalTime;
4269 }
4270 if (segment.occupancyAverage < 1.0f) {
4271 stats.doubleBufferedTime += segment.totalTime;
4272 } else if (segment.occupancyAverage < 2.0f) {
4273 stats.tripleBufferedTime += segment.totalTime;
4274 }
4275 ++stats.numSegments;
4276 stats.totalTime += segment.totalTime;
4277 }
4278}
4279
Brian Andersond6927fb2016-07-23 23:37:30 -07004280void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4281 result.appendFormat("Layer frame timestamps:\n");
4282
4283 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4284 const size_t count = currentLayers.size();
4285 for (size_t i=0 ; i<count ; i++) {
4286 currentLayers[i]->dumpFrameEvents(result);
4287 }
4288}
4289
Dan Stozae77c7662016-05-13 11:37:28 -07004290void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4291 result.append("Buffering stats:\n");
4292 result.append(" [Layer name] <Active time> <Two buffer> "
4293 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004294 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004295 typedef std::tuple<std::string, float, float, float> BufferTuple;
4296 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004297 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004298 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004299 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004300 if (stats.numSegments == 0) {
4301 continue;
4302 }
4303 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4304 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4305 stats.totalTime;
4306 float doubleBufferRatio = static_cast<float>(
4307 stats.doubleBufferedTime) / stats.totalTime;
4308 float tripleBufferRatio = static_cast<float>(
4309 stats.tripleBufferedTime) / stats.totalTime;
4310 sorted.insert({activeTime, {name, twoBufferRatio,
4311 doubleBufferRatio, tripleBufferRatio}});
4312 }
4313 for (const auto& sortedPair : sorted) {
4314 float activeTime = sortedPair.first;
4315 const BufferTuple& values = sortedPair.second;
4316 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4317 std::get<0>(values).c_str(), activeTime,
4318 std::get<1>(values), std::get<2>(values),
4319 std::get<3>(values));
4320 }
4321 result.append("\n");
4322}
4323
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004324void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004325 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004326 const int32_t displayId = display->getId();
4327 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4328 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004329 continue;
4330 }
4331
Dominik Laskowski7e045462018-05-30 13:02:02 -07004332 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004333 uint8_t port;
4334 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004335 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004336 result.append("no identification data\n");
4337 continue;
4338 }
4339
4340 if (!isEdid(data)) {
4341 result.append("unknown identification data: ");
4342 for (uint8_t byte : data) {
4343 result.appendFormat("%x ", byte);
4344 }
4345 result.append("\n");
4346 continue;
4347 }
4348
4349 const auto edid = parseEdid(data);
4350 if (!edid) {
4351 result.append("invalid EDID: ");
4352 for (uint8_t byte : data) {
4353 result.appendFormat("%x ", byte);
4354 }
4355 result.append("\n");
4356 continue;
4357 }
4358
4359 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4360 result.append(edid->displayName.data(), edid->displayName.length());
4361 result.append("\"\n");
4362 }
4363 result.append("\n");
4364}
4365
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004366void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004367 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4368 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004369 result.appendFormat("DisplayColorSetting: %s\n",
4370 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004371
4372 // TODO: print out if wide-color mode is active or not
4373
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004374 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004375 const int32_t displayId = display->getId();
4376 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004377 continue;
4378 }
4379
Dominik Laskowski7e045462018-05-30 13:02:02 -07004380 result.appendFormat("Display %d color modes:\n", displayId);
4381 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004382 for (auto&& mode : modes) {
4383 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4384 }
4385
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004386 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004387 result.appendFormat(" Current color mode: %s (%d)\n",
4388 decodeColorMode(currentMode).c_str(), currentMode);
4389 }
4390 result.append("\n");
4391}
4392
David Sodman7e4ae112018-02-09 15:02:28 -08004393void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4394 std::string stringResult;
4395
4396 for (const auto& [token, display] : mDisplays) {
4397 const auto displayId = display->getId();
4398 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
4399 continue;
4400 }
4401
4402 const auto& compositionInfoIt = getBE().mEndOfFrameCompositionInfo.find(displayId);
4403 if (compositionInfoIt == getBE().mEndOfFrameCompositionInfo.end()) {
4404 break;
4405 }
4406 const auto& compositionInfoList = compositionInfoIt->second;
4407 stringResult += base::StringPrintf("Display: %d\n", displayId);
4408 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4409 for (const auto& compositionInfo : compositionInfoList) {
4410 compositionInfo.dump(stringResult, nullptr);
4411 stringResult += base::StringPrintf("\n");
4412 }
4413 }
4414
4415 result.append(stringResult.c_str());
4416}
4417
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004418LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004419 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004420 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4421 const State& state = useDrawing ? mDrawingState : mCurrentState;
4422 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004423 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004424 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004425 });
4426
4427 return layersProto;
4428}
4429
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004430LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004431 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004432
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004433 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004434 resolution->set_w(display.getWidth());
4435 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004436
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004437 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4438 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4439 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004440
Dominik Laskowski7e045462018-05-30 13:02:02 -07004441 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004442 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004443 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004444 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004445 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004446 }
4447 });
4448
4449 return layersProto;
4450}
4451
Mathias Agopian74d211a2013-04-22 16:55:35 +02004452void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4453 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004454{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004455 bool colorize = false;
4456 if (index < args.size()
4457 && (args[index] == String16("--color"))) {
4458 colorize = true;
4459 index++;
4460 }
4461
4462 Colorizer colorizer(colorize);
4463
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004464 // figure out if we're stuck somewhere
4465 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004466 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004467 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4468
4469 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004470 * Dump library configuration.
4471 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004472
4473 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004474 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004475 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004476 appendSfConfigString(result);
4477 appendUiConfigString(result);
4478 appendGuiConfigString(result);
4479 result.append("\n");
4480
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004481 result.append("\nDisplay identification data:\n");
4482 dumpDisplayIdentificationData(result);
4483
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004484 result.append("\nWide-Color information:\n");
4485 dumpWideColorInfo(result);
4486
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004487 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004488 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004489 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004490 result.append(SyncFeatures::getInstance().toString());
4491 result.append("\n");
4492
Andy McFadden41d67d72014-04-25 16:58:34 -07004493 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004494 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004495 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004496
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004497 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4498 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004499 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4500 getHwComposer().isConnected(displayId)) {
4501 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004502 result.appendFormat("Display %d: "
4503 "app phase %" PRId64 " ns, "
4504 "sf phase %" PRId64 " ns, "
4505 "early app phase %" PRId64 " ns, "
4506 "early sf phase %" PRId64 " ns, "
4507 "early app gl phase %" PRId64 " ns, "
4508 "early sf gl phase %" PRId64 " ns, "
4509 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4510 displayId,
4511 vsyncPhaseOffsetNs,
4512 sfVsyncPhaseOffsetNs,
4513 appEarlyOffset,
4514 sfEarlyOffset,
4515 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004516 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004517 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004518 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004519 result.append("\n");
4520
Dan Stozab90cf072015-03-05 11:05:59 -08004521 // Dump static screen stats
4522 result.append("\n");
4523 dumpStaticScreenStats(result);
4524 result.append("\n");
4525
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004526 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4527
Dan Stozae77c7662016-05-13 11:37:28 -07004528 dumpBufferingStats(result);
4529
Andy McFadden4803b742012-09-24 19:07:20 -07004530 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004531 * Dump the visible layer list
4532 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004533 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004534 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004535 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4536 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004537 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004538
Chia-I Wu2f884132018-09-13 15:17:58 -07004539 {
4540 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4541 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4542 result.append(LayerProtoParser::layerTreeToString(layerTree).c_str());
4543 result.append("\n");
4544 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004545
David Sodman7e4ae112018-02-09 15:02:28 -08004546 result.append("\nFrame-Composition information:\n");
4547 dumpFrameCompositionInfo(result);
4548 result.append("\n");
4549
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004550 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004551 * Dump Display state
4552 */
4553
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004554 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004555 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004556 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004557 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004558 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004559 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004560 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004561
4562 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004563 * Dump SurfaceFlinger global state
4564 */
4565
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004566 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004567 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004568 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004569
Mathias Agopian888c8222012-08-04 21:10:38 -07004570 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004571 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004572
David Sodmanbc815282017-11-05 18:57:52 -08004573 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004574
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004575 if (display) {
4576 display->undefinedRegion.dump(result, "undefinedRegion");
4577 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4578 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004579 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004580 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004581 " gpu_to_cpu_unsupported : %d\n",
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004582 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004583
4584 if (display) {
4585 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4586 result.appendFormat(" refresh-rate : %f fps\n"
4587 " x-dpi : %f\n"
4588 " y-dpi : %f\n",
4589 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4590 activeConfig->getDpiY());
4591 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004592
Mathias Agopian74d211a2013-04-22 16:55:35 +02004593 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004594 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004595
Ana Krulec98b5b242018-08-10 15:03:23 -07004596 result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004597 /*
4598 * VSYNC state
4599 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004600 if (mUseScheduler) {
4601 mScheduler->dump(mAppConnectionHandle, result);
4602 } else {
4603 mEventThread->dump(result);
4604 }
Dan Stozae22aec72016-08-01 13:20:59 -07004605 result.append("\n");
4606
4607 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004608 * Tracing state
4609 */
4610 mTracing.dump(result);
4611 result.append("\n");
4612
4613 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004614 * HWC layer minidump
4615 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004616 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004617 const int32_t displayId = display->getId();
4618 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004619 continue;
4620 }
4621
Dominik Laskowski7e045462018-05-30 13:02:02 -07004622 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004623 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004624 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004625 result.append("\n");
4626 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004627
4628 /*
4629 * Dump HWComposer state
4630 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004631 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004632 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004633 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004634 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004635 result.appendFormat(" h/w composer %s\n",
4636 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004637 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004638
4639 /*
4640 * Dump gralloc state
4641 */
4642 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4643 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004644
4645 /*
4646 * Dump VrFlinger state if in use.
4647 */
4648 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4649 result.append("VrFlinger state:\n");
4650 result.append(mVrFlinger->Dump().c_str());
4651 result.append("\n");
4652 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004653}
4654
Dominik Laskowski7e045462018-05-30 13:02:02 -07004655const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004656 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004657 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004658 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004659 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004660 }
4661 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004662
4663 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4664 static const Vector<sp<Layer>> empty;
4665 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004666}
4667
Keun young Park63f165f2012-08-31 10:53:36 -07004668bool SurfaceFlinger::startDdmConnection()
4669{
4670 void* libddmconnection_dso =
4671 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4672 if (!libddmconnection_dso) {
4673 return false;
4674 }
4675 void (*DdmConnection_start)(const char* name);
4676 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004677 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004678 if (!DdmConnection_start) {
4679 dlclose(libddmconnection_dso);
4680 return false;
4681 }
4682 (*DdmConnection_start)(getServiceName());
4683 return true;
4684}
4685
Chia-I Wu28f320b2018-05-03 11:02:56 -07004686void SurfaceFlinger::updateColorMatrixLocked() {
4687 mat4 colorMatrix;
4688 if (mGlobalSaturationFactor != 1.0f) {
4689 // Rec.709 luma coefficients
4690 float3 luminance{0.213f, 0.715f, 0.072f};
4691 luminance *= 1.0f - mGlobalSaturationFactor;
4692 mat4 saturationMatrix = mat4(
4693 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4694 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4695 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4696 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4697 );
4698 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4699 } else {
4700 colorMatrix = mClientColorMatrix * mDaltonizer();
4701 }
4702
4703 if (mCurrentState.colorMatrix != colorMatrix) {
4704 mCurrentState.colorMatrix = colorMatrix;
4705 mCurrentState.colorMatrixChanged = true;
4706 setTransactionFlags(eTransactionNeeded);
4707 }
4708}
4709
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004710status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004711#pragma clang diagnostic push
4712#pragma clang diagnostic error "-Wswitch-enum"
4713 switch (static_cast<ISurfaceComposerTag>(code)) {
4714 // These methods should at minimum make sure that the client requested
4715 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004716 case BOOT_FINISHED:
4717 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004718 case CREATE_CONNECTION:
4719 case CREATE_DISPLAY:
4720 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004721 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004722 case GET_ACTIVE_COLOR_MODE:
4723 case GET_ANIMATION_FRAME_STATS:
4724 case GET_HDR_CAPABILITIES:
4725 case SET_ACTIVE_CONFIG:
4726 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004727 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004728 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004729 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4730 IPCThreadState* ipc = IPCThreadState::self();
4731 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4732 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004733 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004734 }
Robert Carr1db73f62016-12-21 12:58:51 -08004735 return OK;
4736 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004737 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004738 IPCThreadState* ipc = IPCThreadState::self();
4739 const int pid = ipc->getCallingPid();
4740 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004741 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4742 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004743 return PERMISSION_DENIED;
4744 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004745 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004746 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004747 // Used by apps to hook Choreographer to SurfaceFlinger.
4748 case CREATE_DISPLAY_EVENT_CONNECTION:
4749 // The following calls are currently used by clients that do not
4750 // request necessary permissions. However, they do not expose any secret
4751 // information, so it is OK to pass them.
4752 case AUTHENTICATE_SURFACE:
4753 case GET_ACTIVE_CONFIG:
4754 case GET_BUILT_IN_DISPLAY:
4755 case GET_DISPLAY_COLOR_MODES:
4756 case GET_DISPLAY_CONFIGS:
4757 case GET_DISPLAY_STATS:
4758 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4759 // Calling setTransactionState is safe, because you need to have been
4760 // granted a reference to Client* and Handle* to do anything with it.
4761 case SET_TRANSACTION_STATE:
4762 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004763 case CREATE_SCOPED_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004764 case GET_COLOR_MANAGEMENT:
Peiyong Lin0256f722018-08-31 15:45:10 -07004765 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004766 return OK;
4767 }
4768 case CAPTURE_LAYERS:
4769 case CAPTURE_SCREEN: {
4770 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004771 IPCThreadState* ipc = IPCThreadState::self();
4772 const int pid = ipc->getCallingPid();
4773 const int uid = ipc->getCallingUid();
4774 if ((uid != AID_GRAPHICS) &&
4775 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4776 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4777 return PERMISSION_DENIED;
4778 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004779 return OK;
4780 }
4781 // The following codes are deprecated and should never be allowed to access SF.
4782 case CONNECT_DISPLAY_UNUSED:
4783 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4784 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4785 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004786 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004787 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004788
4789 // These codes are used for the IBinder protocol to either interrogate the recipient
4790 // side of the transaction for its canonical interface descriptor or to dump its state.
4791 // We let them pass by default.
4792 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4793 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4794 code == IBinder::SYSPROPS_TRANSACTION) {
4795 return OK;
4796 }
Peiyong Lin3b44a032018-10-24 18:18:12 -07004797 // Numbers from 1000 to 1030 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004798 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin3b44a032018-10-24 18:18:12 -07004799 if (code >= 1000 && code <= 1030) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004800 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4801 return OK;
4802 }
4803 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4804 return PERMISSION_DENIED;
4805#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004806}
4807
Ana Krulec13be8ad2018-08-21 02:43:56 +00004808status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4809 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004810 status_t credentialCheck = CheckTransactCodeCredentials(code);
4811 if (credentialCheck != OK) {
4812 return credentialCheck;
4813 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004814
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004815 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4816 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004817 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004818 IPCThreadState* ipc = IPCThreadState::self();
4819 const int uid = ipc->getCallingUid();
4820 if (CC_UNLIKELY(uid != AID_SYSTEM
4821 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004822 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004823 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004824 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004825 return PERMISSION_DENIED;
4826 }
4827 int n;
4828 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004829 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004830 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004831 return NO_ERROR;
4832 case 1002: // SHOW_UPDATES
4833 n = data.readInt32();
4834 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004835 invalidateHwcGeometry();
4836 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004837 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004838 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004839 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004840 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004841 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004842 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004843 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004844 setTransactionFlags(
4845 eTransactionNeeded|
4846 eDisplayTransactionNeeded|
4847 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004848 return NO_ERROR;
4849 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004850 case 1006:{ // send empty update
4851 signalRefresh();
4852 return NO_ERROR;
4853 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004854 case 1008: // toggle use of hw composer
4855 n = data.readInt32();
4856 mDebugDisableHWC = n ? 1 : 0;
4857 invalidateHwcGeometry();
4858 repaintEverything();
4859 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004860 case 1009: // toggle use of transform hint
4861 n = data.readInt32();
4862 mDebugDisableTransformHint = n ? 1 : 0;
4863 invalidateHwcGeometry();
4864 repaintEverything();
4865 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004866 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004867 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004868 reply->writeInt32(0);
4869 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004870 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004871 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004872 return NO_ERROR;
4873 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004874 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004875 if (!display) {
4876 return NAME_NOT_FOUND;
4877 }
4878
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004879 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004880 return NO_ERROR;
4881 }
4882 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004883 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004884 // daltonize
4885 n = data.readInt32();
4886 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004887 case 1:
4888 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4889 break;
4890 case 2:
4891 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4892 break;
4893 case 3:
4894 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4895 break;
4896 default:
4897 mDaltonizer.setType(ColorBlindnessType::None);
4898 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004899 }
4900 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004901 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004902 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004903 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004904 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004905
4906 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004907 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004908 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004909 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004910 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004911 // apply a color matrix
4912 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004913 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004914 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004915 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004916 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004917 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004918 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004919 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004920 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004921 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004922 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004923
4924 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4925 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004926 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004927 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4928 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4929 }
4930
Chia-I Wu28f320b2018-05-03 11:02:56 -07004931 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004932 return NO_ERROR;
4933 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004934 // This is an experimental interface
4935 // Needs to be shifted to proper binder interface when we productize
4936 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004937 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07004938 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07004939 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004940 return NO_ERROR;
4941 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004942 case 1017: {
4943 n = data.readInt32();
4944 mForceFullDamage = static_cast<bool>(n);
4945 return NO_ERROR;
4946 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004947 case 1018: { // Modify Choreographer's phase offset
4948 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004949 if (mUseScheduler) {
4950 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
4951 } else {
4952 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4953 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004954 return NO_ERROR;
4955 }
4956 case 1019: { // Modify SurfaceFlinger's phase offset
4957 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004958 if (mUseScheduler) {
4959 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
4960 } else {
4961 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4962 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004963 return NO_ERROR;
4964 }
Irvel468051e2016-06-13 16:44:44 -07004965 case 1020: { // Layer updates interceptor
4966 n = data.readInt32();
4967 if (n) {
4968 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004969 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004970 }
4971 else{
4972 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004973 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004974 }
4975 return NO_ERROR;
4976 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004977 case 1021: { // Disable HWC virtual displays
4978 n = data.readInt32();
4979 mUseHwcVirtualDisplays = !n;
4980 return NO_ERROR;
4981 }
Romain Guy0147a172017-06-01 13:53:56 -07004982 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004983 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004984 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004985
Chia-I Wu28f320b2018-05-03 11:02:56 -07004986 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004987 return NO_ERROR;
4988 }
Romain Guy54f154a2017-10-24 21:40:32 +01004989 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004990 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004991 invalidateHwcGeometry();
4992 repaintEverything();
4993 return NO_ERROR;
4994 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004995 // Deprecate, use 1030 to check whether the device is color managed.
4996 case 1024: {
4997 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004998 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004999 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005000 n = data.readInt32();
5001 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005002 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005003 mTracing.enable();
5004 doTracing("tracing.enable");
5005 reply->writeInt32(NO_ERROR);
5006 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005007 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005008 status_t err = mTracing.disable();
5009 reply->writeInt32(err);
5010 }
5011 return NO_ERROR;
5012 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005013 case 1026: { // Get layer tracing status
5014 reply->writeBool(mTracing.isEnabled());
5015 return NO_ERROR;
5016 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005017 // Is a DisplayColorSetting supported?
5018 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005019 const auto display = getDefaultDisplayDevice();
5020 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005021 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005022 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005023
5024 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5025 switch (setting) {
5026 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005027 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005028 break;
5029 case DisplayColorSetting::UNMANAGED:
5030 reply->writeBool(true);
5031 break;
5032 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005033 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005034 break;
5035 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005036 reply->writeBool(
5037 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005038 break;
5039 }
5040 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005041 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005042 // Is VrFlinger active?
5043 case 1028: {
5044 Mutex::Autolock _l(mStateLock);
5045 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5046 return NO_ERROR;
5047 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005048 // Is device color managed?
5049 case 1030: {
5050 reply->writeBool(useColorManagement);
5051 return NO_ERROR;
5052 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005053 }
5054 }
5055 return err;
5056}
5057
Steven Thomas6d8110b2017-08-31 18:24:21 -07005058void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005059 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005060 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005061}
5062
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005063// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5064class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005065public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005066 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5067 ~WindowDisconnector() {
5068 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005069 }
5070
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005071private:
5072 ANativeWindow* mWindow;
5073 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005074};
5075
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005076status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005077 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5078 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005079 uint32_t reqWidth, uint32_t reqHeight,
5080 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005081 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005082 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005083
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005084 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005085
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005086 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5087
Chia-I Wu20261cb2018-08-23 12:55:44 -07005088 sp<DisplayDevice> display;
5089 {
5090 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005091
Chia-I Wu20261cb2018-08-23 12:55:44 -07005092 display = getDisplayDeviceLocked(displayToken);
5093 if (!display) return BAD_VALUE;
5094
Chia-I Wucb023152018-08-28 12:57:23 -07005095 // set the requested width/height to the logical display viewport size
5096 // by default
5097 if (reqWidth == 0 || reqHeight == 0) {
5098 reqWidth = uint32_t(display->getViewport().width());
5099 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005100 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005101 }
5102
Peiyong Lin0e003c92018-09-17 11:09:51 -07005103 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5104 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005105
5106 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005107 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005108 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5109 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005110}
5111
5112status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005113 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5114 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005115 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005116 ATRACE_CALL();
5117
5118 class LayerRenderArea : public RenderArea {
5119 public:
Robert Carr578038f2018-03-09 12:25:24 -08005120 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005121 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5122 bool childrenOnly)
5123 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005124 mLayer(layer),
5125 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005126 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005127 mFlinger(flinger),
5128 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005129 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005130 Rect getBounds() const override {
5131 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005132 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005133 }
Marissa Wall61c58622018-07-18 10:12:20 -07005134 int getHeight() const override {
5135 return mLayer->getActiveHeight(mLayer->getDrawingState());
5136 }
5137 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005138 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005139 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005140 Rect getSourceCrop() const override {
5141 if (mCrop.isEmpty()) {
5142 return getBounds();
5143 } else {
5144 return mCrop;
5145 }
5146 }
Robert Carr578038f2018-03-09 12:25:24 -08005147 class ReparentForDrawing {
5148 public:
5149 const sp<Layer>& oldParent;
5150 const sp<Layer>& newParent;
5151
5152 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5153 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005154 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005155 }
Robert Carr15eae092018-03-23 13:43:53 -07005156 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005157 };
5158
5159 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005160 const Rect sourceCrop = getSourceCrop();
5161 // no need to check rotation because there is none
5162 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5163 sourceCrop.height() != getReqHeight();
5164
Robert Carr578038f2018-03-09 12:25:24 -08005165 if (!mChildrenOnly) {
5166 mTransform = mLayer->getTransform().inverse();
5167 drawLayers();
5168 } else {
5169 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005170 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005171 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5172 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005173
5174 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5175 drawLayers();
5176 }
5177 }
chaviwa76b2712017-09-20 12:02:26 -07005178
chaviwa76b2712017-09-20 12:02:26 -07005179 private:
chaviw7206d492017-11-10 16:16:12 -08005180 const sp<Layer> mLayer;
5181 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005182
5183 // In the "childrenOnly" case we reparent the children to a screenshot
5184 // layer which has no properties set and which does not draw.
5185 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005186 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005187 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005188
5189 SurfaceFlinger* mFlinger;
5190 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005191 };
5192
5193 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5194 auto parent = layerHandle->owner.promote();
5195
Jorim Jaggi10c985e2018-10-23 11:17:45 +00005196 if (parent == nullptr || parent->isPendingRemoval()) {
chaviw7206d492017-11-10 16:16:12 -08005197 ALOGE("captureLayers called with a removed parent");
5198 return NAME_NOT_FOUND;
5199 }
5200
Robert Carr578038f2018-03-09 12:25:24 -08005201 const int uid = IPCThreadState::self()->getCallingUid();
5202 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5203 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5204 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5205 return PERMISSION_DENIED;
5206 }
5207
chaviw7206d492017-11-10 16:16:12 -08005208 Rect crop(sourceCrop);
5209 if (sourceCrop.width() <= 0) {
5210 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005211 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005212 }
5213
5214 if (sourceCrop.height() <= 0) {
5215 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005216 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005217 }
5218
5219 int32_t reqWidth = crop.width() * frameScale;
5220 int32_t reqHeight = crop.height() * frameScale;
5221
Chia-I Wu20261cb2018-08-23 12:55:44 -07005222 // really small crop or frameScale
5223 if (reqWidth <= 0) {
5224 reqWidth = 1;
5225 }
5226 if (reqHeight <= 0) {
5227 reqHeight = 1;
5228 }
5229
Peiyong Lin0e003c92018-09-17 11:09:51 -07005230 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005231
Robert Carr578038f2018-03-09 12:25:24 -08005232 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005233 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5234 if (!layer->isVisible()) {
5235 return;
Robert Carr578038f2018-03-09 12:25:24 -08005236 } else if (childrenOnly && layer == parent.get()) {
5237 return;
chaviwa76b2712017-09-20 12:02:26 -07005238 }
5239 visitor(layer);
5240 });
5241 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005242 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005243}
5244
5245status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5246 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005247 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005248 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005249 bool useIdentityTransform) {
5250 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005251
Peiyong Lin0e003c92018-09-17 11:09:51 -07005252 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005253 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5254 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005255 *outBuffer =
5256 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5257 static_cast<android_pixel_format>(reqPixelFormat), 1,
5258 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005259
5260 // This mutex protects syncFd and captureResult for communication of the return values from the
5261 // main thread back to this Binder thread
5262 std::mutex captureMutex;
5263 std::condition_variable captureCondition;
5264 std::unique_lock<std::mutex> captureLock(captureMutex);
5265 int syncFd = -1;
5266 std::optional<status_t> captureResult;
5267
Robert Carr03480e22018-01-04 16:02:06 -08005268 const int uid = IPCThreadState::self()->getCallingUid();
5269 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5270
Dominik Laskowski8c001672018-05-30 16:52:06 -07005271 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005272 // If there is a refresh pending, bug out early and tell the binder thread to try again
5273 // after the refresh.
5274 if (mRefreshPending) {
5275 ATRACE_NAME("Skipping screenshot for now");
5276 std::unique_lock<std::mutex> captureLock(captureMutex);
5277 captureResult = std::make_optional<status_t>(EAGAIN);
5278 captureCondition.notify_one();
5279 return;
5280 }
5281
5282 status_t result = NO_ERROR;
5283 int fd = -1;
5284 {
5285 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005286 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005287 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5288 useIdentityTransform, forSystem, &fd);
5289 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005290 }
5291
5292 {
5293 std::unique_lock<std::mutex> captureLock(captureMutex);
5294 syncFd = fd;
5295 captureResult = std::make_optional<status_t>(result);
5296 captureCondition.notify_one();
5297 }
5298 });
5299
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005300 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005301 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005302 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005303 while (*captureResult == EAGAIN) {
5304 captureResult.reset();
5305 result = postMessageAsync(message);
5306 if (result != NO_ERROR) {
5307 return result;
5308 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005309 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005310 }
5311 result = *captureResult;
5312 }
5313
5314 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005315 sync_wait(syncFd, -1);
5316 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005317 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005318
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005319 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005320}
5321
chaviwa76b2712017-09-20 12:02:26 -07005322void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005323 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005324 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005325 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005326
Lloyd Pique144e1162017-12-20 16:44:52 -08005327 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005328
chaviwa76b2712017-09-20 12:02:26 -07005329 const auto reqWidth = renderArea.getReqWidth();
5330 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005331 const auto sourceCrop = renderArea.getSourceCrop();
5332 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005333
Peiyong Lin0e003c92018-09-17 11:09:51 -07005334 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005335 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005336
Mathias Agopian180f10d2013-04-10 22:55:41 -07005337 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005338 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005339
5340 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005341 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005342 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005343
chaviw50da5042018-04-09 13:49:37 -07005344 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005345 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005346 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005347
chaviwa76b2712017-09-20 12:02:26 -07005348 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005349 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005350 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005351 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005352 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005353}
5354
chaviwa76b2712017-09-20 12:02:26 -07005355status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5356 TraverseLayersFunction traverseLayers,
5357 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005358 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005359 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005360 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005361 ATRACE_CALL();
5362
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005363 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005364
5365 traverseLayers([&](Layer* layer) {
5366 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5367 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005368
Robert Carr03480e22018-01-04 16:02:06 -08005369 // We allow the system server to take screenshots of secure layers for
5370 // use in situations like the Screen-rotation animation and place
5371 // the impetus on WindowManager to not persist them.
5372 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005373 ALOGW("FB is protected: PERMISSION_DENIED");
5374 return PERMISSION_DENIED;
5375 }
5376
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005377 // this binds the given EGLImage as a framebuffer for the
5378 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005379 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005380 if (bufferBond.getStatus() != NO_ERROR) {
5381 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005382 return INVALID_OPERATION;
5383 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005384
Dan Stozaabcda352017-06-01 14:37:39 -07005385 // this will in fact render into our dequeued buffer
5386 // via an FBO, which means we didn't have to create
5387 // an EGLSurface and therefore we're not
5388 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005389 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005390
Alec Mouri492bc572018-09-11 21:40:04 +00005391 base::unique_fd syncFd = getRenderEngine().flush();
5392 if (syncFd < 0) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005393 getRenderEngine().finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005394 }
Alec Mouri492bc572018-09-11 21:40:04 +00005395 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005396
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005397 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005398}
5399
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005400// ---------------------------------------------------------------------------
5401
Dan Stoza412903f2017-04-27 13:42:17 -07005402void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5403 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005404}
5405
Dan Stoza412903f2017-04-27 13:42:17 -07005406void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5407 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005408}
5409
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005410void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005411 const LayerVector::Visitor& visitor) {
5412 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005413 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005414 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005415 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005416 continue;
5417 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005418 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005419 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005420 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005421 return;
5422 }
chaviwa76b2712017-09-20 12:02:26 -07005423 if (!layer->isVisible()) {
5424 return;
5425 }
5426 visitor(layer);
5427 });
5428 }
5429}
5430
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005431}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005432
Lloyd Pique074e8122018-07-26 12:57:23 -07005433
Mathias Agopian3f844832013-08-07 21:24:32 -07005434#if defined(__gl_h_)
5435#error "don't include gl/gl.h in this file"
5436#endif
5437
5438#if defined(__gl2_h_)
5439#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005440#endif