blob: fc8ca547973bbe9278aef21aef7cd7e17c2baa6b [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 Lin0256f722018-08-31 15:45:10 -0700199Dataspace SurfaceFlinger::compositionDataSpace = Dataspace::V0_SRGB;
200ui::PixelFormat SurfaceFlinger::compositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700201
Kalle Raitaa099a242017-01-11 11:17:29 -0800202std::string getHwcServiceName() {
203 char value[PROPERTY_VALUE_MAX] = {};
204 property_get("debug.sf.hwc_service_name", value, "default");
205 ALOGI("Using HWComposer service: '%s'", value);
206 return std::string(value);
207}
208
209bool useTrebleTestingOverride() {
210 char value[PROPERTY_VALUE_MAX] = {};
211 property_get("debug.sf.treble_testing_override", value, "false");
212 ALOGI("Treble testing override: '%s'", value);
213 return std::string(value) == "true";
214}
215
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800216std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
217 switch(displayColorSetting) {
218 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700219 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800220 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700221 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800222 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700223 return std::string("Enhanced");
224 default:
225 return std::string("Unknown ") +
226 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800227 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800228}
229
David Sodmanbc815282017-11-05 18:57:52 -0800230SurfaceFlingerBE::SurfaceFlingerBE()
231 : mHwcServiceName(getHwcServiceName()),
232 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800233 mFrameBuckets(),
234 mTotalTime(0),
235 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800236 mComposerSequenceId(0) {
237}
238
Lloyd Pique90c115d2018-09-18 21:39:42 -0700239SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
240 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800241 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700242 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700243 mTransactionPending(false),
244 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700245 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700246 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800247 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700248 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800249 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800250 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800251 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800252 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800253 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700254 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700255 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700256 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700257 mDebugInTransaction(0),
258 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700259 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700260 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700261 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800262 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800263 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800264 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700265 mVrFlingerRequestsDisplay(false),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700266 mMainThreadId(std::this_thread::get_id()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800267
Lloyd Pique90c115d2018-09-18 21:39:42 -0700268SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
269 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800270 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800271
272 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
273 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
274
275 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
276 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
277
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800278 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
279 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800280
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700281 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
282 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
283
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700284 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
285 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
286
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800287 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
288 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
289
Steven Thomas050b2c82017-03-06 11:45:16 -0800290 // Vr flinger is only enabled on Daydream ready devices.
291 useVrFlinger = getBool< ISurfaceFlingerConfigs,
292 &ISurfaceFlingerConfigs::useVrFlinger>(false);
293
Fabien Sanglard1971b632017-03-10 14:50:03 -0800294 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
295 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
296
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600297 hasWideColorDisplay =
298 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700299 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700300 getBool<V1_2::ISurfaceFlingerConfigs,
301 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
302
303 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
304 if (surfaceFlingerConfigsServiceV1_2) {
305 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
306 [&](Dataspace tmpDataSpace, ui::PixelFormat tmpPixelFormat) {
307 compositionDataSpace = tmpDataSpace;
308 compositionPixelFormat = tmpPixelFormat;
309 });
310 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600311
Peiyong Linb3839ad2018-09-05 15:37:19 -0700312 useContextPriority = getBool<ISurfaceFlingerConfigs,
313 &ISurfaceFlingerConfigs::useContextPriority>(true);
314
Iris Chang7501ed62018-04-30 14:45:42 +0800315 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700316 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
317 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800318 V1_1::DisplayOrientation::ORIENTATION_0);
319
320 switch (primaryDisplayOrientation) {
321 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700322 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800323 break;
324 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700325 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800326 break;
327 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700328 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800329 break;
330 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700331 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800332 break;
333 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700334 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800335
Lloyd Pique90c115d2018-09-18 21:39:42 -0700336 mPrimaryDispSync =
337 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
338 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700339
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800340 // debugging stuff...
341 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700342
Mathias Agopianb4b17302013-03-20 18:36:41 -0700343 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700344 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700345
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800346 property_get("debug.sf.showupdates", value, "0");
347 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700348
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700349 property_get("debug.sf.ddms", value, "0");
350 mDebugDDMS = atoi(value);
351 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700352 if (!startDdmConnection()) {
353 // start failed, and DDMS debugging not enabled
354 mDebugDDMS = 0;
355 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700356 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700357 ALOGI_IF(mDebugRegion, "showupdates enabled");
358 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700359
360 property_get("debug.sf.disable_backpressure", value, "0");
361 mPropagateBackpressure = !atoi(value);
362 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700363
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800364 property_get("debug.sf.enable_hwc_vds", value, "0");
365 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800366 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800367
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800368 property_get("ro.sf.disable_triple_buffer", value, "1");
369 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800370 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700371
Yiwei Zhang243b3782018-05-15 17:40:04 -0700372 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700373 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
374 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
375
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200376 property_get("debug.sf.early_phase_offset_ns", value, "-1");
377 const int earlySfOffsetNs = atoi(value);
378
379 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
380 const int earlyGlSfOffsetNs = atoi(value);
381
382 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
383 const int earlyAppOffsetNs = atoi(value);
384
385 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
386 const int earlyGlAppOffsetNs = atoi(value);
387
Ana Krulec98b5b242018-08-10 15:03:23 -0700388 property_get("debug.sf.use_scheduler", value, "0");
389 mUseScheduler = atoi(value);
390
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200391 const VSyncModulator::Offsets earlyOffsets =
392 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
393 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
394 const VSyncModulator::Offsets earlyGlOffsets =
395 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
396 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
397 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
398 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700399
Romain Guy11d63f42017-07-20 12:47:14 -0700400 // We should be reading 'persist.sys.sf.color_saturation' here
401 // but since /data may be encrypted, we need to wait until after vold
402 // comes online to attempt to read the property. The property is
403 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800404
405 if (useTrebleTestingOverride()) {
406 // Without the override SurfaceFlinger cannot connect to HIDL
407 // services that are not listed in the manifests. Considered
408 // deriving the setting from the set service name, but it
409 // would be brittle if the name that's not 'default' is used
410 // for production purposes later on.
411 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
412 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800413}
414
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800415void SurfaceFlinger::onFirstRef()
416{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800417 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800418}
419
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800420SurfaceFlinger::~SurfaceFlinger()
421{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800422}
423
Dan Stozac7014012014-02-14 15:03:43 -0800424void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800425{
426 // the window manager died on us. prepare its eulogy.
427
Andy McFadden13a082e2012-08-24 10:16:42 -0700428 // restore initial conditions (default device unblank, etc)
429 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800430
431 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700432 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800433}
434
Robert Carr1db73f62016-12-21 12:58:51 -0800435static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700436 status_t err = client->initCheck();
437 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800438 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800439 }
Robert Carr1db73f62016-12-21 12:58:51 -0800440 return nullptr;
441}
442
443sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
444 return initClient(new Client(this));
445}
446
447sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
448 const sp<IGraphicBufferProducer>& gbp) {
449 if (authenticateSurfaceTexture(gbp) == false) {
450 return nullptr;
451 }
452 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
453 if (layer == nullptr) {
454 return nullptr;
455 }
456
457 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800458}
459
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700460sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
461 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700462{
463 class DisplayToken : public BBinder {
464 sp<SurfaceFlinger> flinger;
465 virtual ~DisplayToken() {
466 // no more references, this display must be terminated
467 Mutex::Autolock _l(flinger->mStateLock);
468 flinger->mCurrentState.displays.removeItem(this);
469 flinger->setTransactionFlags(eDisplayTransactionNeeded);
470 }
471 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700472 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700473 : flinger(flinger) {
474 }
475 };
476
477 sp<BBinder> token = new DisplayToken(this);
478
479 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700480 DisplayDeviceState info;
481 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700482 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700483 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700484 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800485 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700486 return token;
487}
488
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700489void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700490 Mutex::Autolock _l(mStateLock);
491
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700492 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700493 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700494 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700495 return;
496 }
497
498 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700499 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700500 ALOGE("destroyDisplay called for non-virtual display");
501 return;
502 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700503 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700504 mCurrentState.displays.removeItemsAt(idx);
505 setTransactionFlags(eDisplayTransactionNeeded);
506}
507
Mathias Agopiane57f2922012-08-09 16:29:12 -0700508sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700509 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700510 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800511 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700512 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700513 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700514}
515
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700516bool SurfaceFlinger::isColorManagementUsed() const {
517 return useColorManagement;
518}
519
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800520void SurfaceFlinger::bootFinished()
521{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700522 if (mStartPropertySetThread->join() != NO_ERROR) {
523 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800524 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800525 const nsecs_t now = systemTime();
526 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000527 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700528
529 // wait patiently for the window manager death
530 const String16 name("window");
531 sp<IBinder> window(defaultServiceManager()->getService(name));
532 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700533 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700534 }
535
Steven Thomas050b2c82017-03-06 11:45:16 -0800536 if (mVrFlinger) {
537 mVrFlinger->OnBootFinished();
538 }
539
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700540 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700541 // formerly we would just kill the process, but we now ask it to exit so it
542 // can choose where to stop the animation.
543 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700544
545 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
546 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
547 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700548
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800549 postMessageAsync(new LambdaMessage([this] {
550 readPersistentProperties();
551 mBootStage = BootStage::FINISHED;
552 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800553}
554
Dan Stoza436ccf32018-06-21 12:10:12 -0700555uint32_t SurfaceFlinger::getNewTexture() {
556 {
557 std::lock_guard lock(mTexturePoolMutex);
558 if (!mTexturePool.empty()) {
559 uint32_t name = mTexturePool.back();
560 mTexturePool.pop_back();
561 ATRACE_INT("TexturePoolSize", mTexturePool.size());
562 return name;
563 }
564
565 // The pool was too small, so increase it for the future
566 ++mTexturePoolSize;
567 }
568
569 // The pool was empty, so we need to get a new texture name directly using a
570 // blocking call to the main thread
571 uint32_t name = 0;
572 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
573 return name;
574}
575
Mathias Agopian3f844832013-08-07 21:24:32 -0700576void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700577 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700578}
579
Wei Wangf9b05ee2017-07-19 20:59:39 -0700580// Do not call property_set on main thread which will be blocked by init
581// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700582void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700583 ALOGI( "SurfaceFlinger's main thread ready to run. "
584 "Initializing graphics H/W...");
585
Thierry Strudel2924d012017-08-14 15:19:37 -0700586 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900587
Steven Thomasb02664d2017-07-26 18:48:28 -0700588 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800589
Steven Thomasb02664d2017-07-26 18:48:28 -0700590 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700591 if (mUseScheduler) {
Lloyd Pique90c115d2018-09-18 21:39:42 -0700592 mScheduler = getFactory().createScheduler(
Ana Krulece588e312018-09-18 12:32:24 -0700593 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Ana Krulec98b5b242018-08-10 15:03:23 -0700594 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700595 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700596 [this] { resyncWithRateLimit(); },
597 impl::EventThread::InterceptVSyncsCallback());
598 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700599 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700600 [this] { resyncWithRateLimit(); },
601 [this](nsecs_t timestamp) {
602 mInterceptor->saveVSyncEvent(timestamp);
603 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800604
Ana Krulec98b5b242018-08-10 15:03:23 -0700605 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700606 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
607 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700608 } else {
609 mEventThreadSource =
610 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
611 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
612 mEventThread =
613 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
614 [this] { resyncWithRateLimit(); },
615 impl::EventThread::InterceptVSyncsCallback(),
616 "appEventThread");
617 mSfEventThreadSource =
618 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
619 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
620
621 mSFEventThread =
622 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
623 [this] { resyncWithRateLimit(); },
624 [this](nsecs_t timestamp) {
625 mInterceptor->saveVSyncEvent(timestamp);
626 },
627 "sfEventThread");
628 mEventQueue->setEventThread(mSFEventThread.get());
629 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
630 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800631
Steven Thomasb02664d2017-07-26 18:48:28 -0700632 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700633 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700634 renderEngineFeature |= (useColorManagement ?
635 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700636 renderEngineFeature |= (useContextPriority ?
637 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700638
639 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
640 getBE().mRenderEngine =
Peiyong Linf11f39b2018-09-05 14:37:41 -0700641 renderengine::RenderEngine::create(static_cast<int32_t>(compositionPixelFormat),
642 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800643 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700644
645 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
646 "Starting with vr flinger active is not currently supported.");
Lloyd Pique90c115d2018-09-18 21:39:42 -0700647 getBE().mHwc = getFactory().createHWComposer(getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -0700648 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800649 // Process any initial hotplug and resulting display changes.
650 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700651 const auto display = getDefaultDisplayDeviceLocked();
652 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
653 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
654 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800655
Lloyd Piquefcd86612017-12-14 17:15:36 -0800656 // make the default display GLContext current so that we can create textures
657 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700658 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800659
Steven Thomas050b2c82017-03-06 11:45:16 -0800660 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700661 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700662 // This callback is called from the vr flinger dispatch thread. We
663 // need to call signalTransaction(), which requires holding
664 // mStateLock when we're not on the main thread. Acquiring
665 // mStateLock from the vr flinger dispatch thread might trigger a
666 // deadlock in surface flinger (see b/66916578), so post a message
667 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700668 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700669 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
670 mVrFlingerRequestsDisplay = requestDisplay;
671 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700672 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800673 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700674 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
675 getHwComposer()
676 .getHwcDisplayId(display->getId())
677 .value_or(0),
678 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800679 if (!mVrFlinger) {
680 ALOGE("Failed to start vrflinger");
681 }
682 }
683
Lloyd Pique90c115d2018-09-18 21:39:42 -0700684 mEventControlThread = getFactory().createEventControlThread(
Lloyd Pique379adc12018-01-22 17:31:47 -0800685 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700686
Mathias Agopian92a979a2012-08-02 18:32:23 -0700687 // initialize our drawing state
688 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700689
Andy McFadden13a082e2012-08-24 10:16:42 -0700690 // set initial conditions (e.g. unblank default device)
691 initializeDisplays();
692
David Sodmanbc815282017-11-05 18:57:52 -0800693 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700694
Wei Wangf9b05ee2017-07-19 20:59:39 -0700695 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700696
697 const bool presentFenceReliable =
698 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
699 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700700
701 if (mStartPropertySetThread->Start() != NO_ERROR) {
702 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800703 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800704
Chia-I Wud49d6692018-06-27 07:17:41 +0800705 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
706 // is used to saturate legacy sRGB content. However, to make sure the same color under
707 // Display P3 will be saturated to the same color, we intentionally break the API spec
708 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
709 // such saturation matrix on Display P3 is understood fully, the API should always return
710 // identify matrix.
711 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
712 Dataspace::SRGB_LINEAR);
713
714 // we will apply this on Display P3.
715 if (mEnhancedSaturationMatrix != mat4()) {
716 ColorSpace srgb(ColorSpace::sRGB());
717 ColorSpace displayP3(ColorSpace::DisplayP3());
718 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
719 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
720 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
721 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800722
Dan Stoza9e56aa02015-11-02 13:00:03 -0800723 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700724}
725
Romain Guy11d63f42017-07-20 12:47:14 -0700726void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700727 Mutex::Autolock _l(mStateLock);
728
Romain Guy11d63f42017-07-20 12:47:14 -0700729 char value[PROPERTY_VALUE_MAX];
730
731 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800732 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700733 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800734 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100735
736 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700737 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700738}
739
Mathias Agopiana67e4182012-06-19 17:26:12 -0700740void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800741 // Start boot animation service by setting a property mailbox
742 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700743 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800744 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700745 if (mStartPropertySetThread->join() != NO_ERROR) {
746 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800747 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700748}
749
Mathias Agopian875d8e12013-06-07 15:35:48 -0700750size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800751 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700752}
753
Mathias Agopian875d8e12013-06-07 15:35:48 -0700754size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800755 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700756}
757
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800758// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800759
Jamie Gennis582270d2011-08-17 18:19:00 -0700760bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800761 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800762 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800763 return authenticateSurfaceTextureLocked(bufferProducer);
764}
765
766bool SurfaceFlinger::authenticateSurfaceTextureLocked(
767 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800768 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800769 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800770}
771
Brian Anderson6b376712017-04-04 10:51:39 -0700772status_t SurfaceFlinger::getSupportedFrameTimestamps(
773 std::vector<FrameEvent>* outSupported) const {
774 *outSupported = {
775 FrameEvent::REQUESTED_PRESENT,
776 FrameEvent::ACQUIRE,
777 FrameEvent::LATCH,
778 FrameEvent::FIRST_REFRESH_START,
779 FrameEvent::LAST_REFRESH_START,
780 FrameEvent::GPU_COMPOSITION_DONE,
781 FrameEvent::DEQUEUE_READY,
782 FrameEvent::RELEASE,
783 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700784 ConditionalLock _l(mStateLock,
785 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700786 if (!getHwComposer().hasCapability(
787 HWC2::Capability::PresentFenceIsNotReliable)) {
788 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
789 }
790 return NO_ERROR;
791}
792
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700793status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
794 Vector<DisplayInfo>* configs) {
795 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700796 return BAD_VALUE;
797 }
798
Jesse Hall692c7232012-11-08 15:41:56 -0800799 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700800 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
801 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700802 type = i;
803 break;
804 }
805 }
806
807 if (type < 0) {
808 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700809 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700810
Mathias Agopian8b736f12012-08-13 17:54:26 -0700811 // TODO: Not sure if display density should handled by SF any longer
812 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700813 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700814 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700815 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800816 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700817 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700818 }
819 return density;
820 }
821 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700822 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700823 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700824 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700825 return getDensityFromProperty("ro.sf.lcd_density"); }
826 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700827
Dan Stoza7f7da322014-05-02 15:26:25 -0700828 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700829
Steven Thomas6d8110b2017-08-31 18:24:21 -0700830 ConditionalLock _l(mStateLock,
831 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800832 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700833 DisplayInfo info = DisplayInfo();
834
Dan Stoza9e56aa02015-11-02 13:00:03 -0800835 float xdpi = hwConfig->getDpiX();
836 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700837
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700838 info.w = hwConfig->getWidth();
839 info.h = hwConfig->getHeight();
840 // Default display viewport to display width and height
841 info.viewportW = info.w;
842 info.viewportH = info.h;
843
Dan Stoza7f7da322014-05-02 15:26:25 -0700844 if (type == DisplayDevice::DISPLAY_PRIMARY) {
845 // The density of the device is provided by a build property
846 float density = Density::getBuildDensity() / 160.0f;
847 if (density == 0) {
848 // the build doesn't provide a density -- this is wrong!
849 // use xdpi instead
850 ALOGE("ro.sf.lcd_density must be defined as a build property");
851 density = xdpi / 160.0f;
852 }
853 if (Density::getEmuDensity()) {
854 // if "qemu.sf.lcd_density" is specified, it overrides everything
855 xdpi = ydpi = density = Density::getEmuDensity();
856 density /= 160.0f;
857 }
858 info.density = density;
859
860 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700861 const auto display = getDefaultDisplayDeviceLocked();
862 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700863
864 // This is for screenrecord
865 const Rect viewport = display->getViewport();
866 if (viewport.isValid()) {
867 info.viewportW = uint32_t(viewport.getWidth());
868 info.viewportH = uint32_t(viewport.getHeight());
869 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700870 } else {
871 // TODO: where should this value come from?
872 static const int TV_DENSITY = 213;
873 info.density = TV_DENSITY / 160.0f;
874 info.orientation = 0;
875 }
876
Dan Stoza7f7da322014-05-02 15:26:25 -0700877 info.xdpi = xdpi;
878 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800879 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900880 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800881
Andy McFadden91b2ca82014-06-13 14:04:23 -0700882 // This is how far in advance a buffer must be queued for
883 // presentation at a given time. If you want a buffer to appear
884 // on the screen at time N, you must submit the buffer before
885 // (N - presentationDeadline).
886 //
887 // Normally it's one full refresh period (to give SF a chance to
888 // latch the buffer), but this can be reduced by configuring a
889 // DispSync offset. Any additional delays introduced by the hardware
890 // composer or panel must be accounted for here.
891 //
892 // We add an additional 1ms to allow for processing time and
893 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800894 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800895 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700896
897 // All non-virtual displays are currently considered secure.
898 info.secure = true;
899
Iris Chang7501ed62018-04-30 14:45:42 +0800900 if (type == DisplayDevice::DISPLAY_PRIMARY &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700901 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800902 std::swap(info.w, info.h);
903 }
904
Michael Wright28f24d02016-07-12 13:30:53 -0700905 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700906 }
907
Dan Stoza7f7da322014-05-02 15:26:25 -0700908 return NO_ERROR;
909}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700910
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700911status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
912 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700913 return BAD_VALUE;
914 }
915
Ana Krulece588e312018-09-18 12:32:24 -0700916 // FIXME for now we always return stats for the primary display.
917 if (mUseScheduler) {
918 mScheduler->getDisplayStatInfo(stats);
919 } else {
920 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
921 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
922 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700923 return NO_ERROR;
924}
925
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700926int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
927 const auto display = getDisplayDevice(displayToken);
928 if (!display) {
929 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800930 return BAD_VALUE;
931 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700932
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700933 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700934}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700935
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700936void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
937 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700938 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700939 return;
940 }
941
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700942 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700943 ALOGW("Trying to set config for virtual display");
944 return;
945 }
946
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700947 display->setActiveConfig(mode);
948 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700949}
950
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700951status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700952 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700953 Vector<DisplayInfo> configs;
954 getDisplayConfigs(displayToken, &configs);
955 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
956 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
957 configs.size());
958 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700959 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700960 const auto display = getDisplayDevice(displayToken);
961 if (!display) {
962 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
963 displayToken.get());
964 } else if (display->isVirtual()) {
965 ALOGW("Attempt to set active config %d for virtual display", mode);
966 } else {
967 setActiveConfigInternal(display, mode);
968 }
969 }));
970
Mathias Agopian888c8222012-08-04 21:10:38 -0700971 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700972}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700973status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
974 Vector<ColorMode>* outColorModes) {
975 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700976 return BAD_VALUE;
977 }
978
Michael Wright28f24d02016-07-12 13:30:53 -0700979 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700980 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
981 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700982 type = i;
983 break;
984 }
985 }
986
987 if (type < 0) {
988 return type;
989 }
990
Peiyong Lina52f0292018-03-14 17:26:31 -0700991 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700992 {
993 ConditionalLock _l(mStateLock,
994 std::this_thread::get_id() != mMainThreadId);
995 modes = getHwComposer().getColorModes(type);
996 }
Michael Wright28f24d02016-07-12 13:30:53 -0700997 outColorModes->clear();
998 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
999
1000 return NO_ERROR;
1001}
1002
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001003ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1004 if (const auto display = getDisplayDevice(displayToken)) {
1005 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001006 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001007 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001008}
1009
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001010void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1011 Dataspace dataSpace, RenderIntent renderIntent) {
1012 ColorMode currentMode = display->getActiveColorMode();
1013 Dataspace currentDataSpace = display->getCompositionDataSpace();
1014 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001015
Peiyong Lin38e9a562018-04-10 16:24:20 -07001016 if (mode == currentMode && dataSpace == currentDataSpace &&
1017 renderIntent == currentRenderIntent) {
1018 return;
1019 }
1020
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001021 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001022 ALOGW("Trying to set config for virtual display");
1023 return;
1024 }
1025
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001026 display->setActiveColorMode(mode);
1027 display->setCompositionDataSpace(dataSpace);
1028 display->setActiveRenderIntent(renderIntent);
1029 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001030
1031 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001032 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1033 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001034}
1035
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001036status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001037 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001038 Vector<ColorMode> modes;
1039 getDisplayColorModes(displayToken, &modes);
1040 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1041 if (mode < ColorMode::NATIVE || !exists) {
1042 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1043 decodeColorMode(mode).c_str(), mode, displayToken.get());
1044 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001045 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001046 const auto display = getDisplayDevice(displayToken);
1047 if (!display) {
1048 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1049 decodeColorMode(mode).c_str(), mode, displayToken.get());
1050 } else if (display->isVirtual()) {
1051 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1052 decodeColorMode(mode).c_str(), mode);
1053 } else {
1054 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1055 RenderIntent::COLORIMETRIC);
1056 }
1057 }));
1058
Michael Wright28f24d02016-07-12 13:30:53 -07001059 return NO_ERROR;
1060}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001061
Svetoslavd85084b2014-03-20 10:28:31 -07001062status_t SurfaceFlinger::clearAnimationFrameStats() {
1063 Mutex::Autolock _l(mStateLock);
1064 mAnimFrameTracker.clearStats();
1065 return NO_ERROR;
1066}
1067
1068status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1069 Mutex::Autolock _l(mStateLock);
1070 mAnimFrameTracker.getStats(outStats);
1071 return NO_ERROR;
1072}
1073
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001074status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1075 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001076 Mutex::Autolock _l(mStateLock);
1077
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001078 const auto display = getDisplayDeviceLocked(displayToken);
1079 if (!display) {
1080 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001081 return BAD_VALUE;
1082 }
1083
Peiyong Linfb069302018-04-25 14:34:31 -07001084 // At this point the DisplayDeivce should already be set up,
1085 // meaning the luminance information is already queried from
1086 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001087 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001088 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1089 capabilities.getDesiredMaxLuminance(),
1090 capabilities.getDesiredMaxAverageLuminance(),
1091 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001092
1093 return NO_ERROR;
1094}
1095
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001096status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001097 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001098 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001099
Chia-I Wu90f669f2017-10-05 14:24:41 -07001100 if (mInjectVSyncs == enable) {
1101 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001102 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001103
Ana Krulec98b5b242018-08-10 15:03:23 -07001104 // TODO(akrulec): Part of the Injector should be refactored, so that it
1105 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001106 if (enable) {
1107 ALOGV("VSync Injections enabled");
1108 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001109 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001110 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001111 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001112 impl::EventThread::InterceptVSyncsCallback(),
1113 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001114 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001115 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001116 } else {
1117 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001118 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001119 }
1120
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001121 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001122 }));
1123
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001124 return NO_ERROR;
1125}
1126
1127status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001128 Mutex::Autolock _l(mStateLock);
1129
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001130 if (!mInjectVSyncs) {
1131 ALOGE("VSync Injections not enabled");
1132 return BAD_VALUE;
1133 }
1134 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1135 ALOGV("Injecting VSync inside SurfaceFlinger");
1136 mVSyncInjector->onInjectSyncEvent(when);
1137 }
1138 return NO_ERROR;
1139}
1140
Lloyd Pique755e3192018-01-31 16:46:15 -08001141status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1142 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001143 // Try to acquire a lock for 1s, fail gracefully
1144 const status_t err = mStateLock.timedLock(s2ns(1));
1145 const bool locked = (err == NO_ERROR);
1146 if (!locked) {
1147 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1148 return TIMED_OUT;
1149 }
1150
1151 outLayers->clear();
1152 mCurrentState.traverseInZOrder([&](Layer* layer) {
1153 outLayers->push_back(layer->getLayerDebugInfo());
1154 });
1155
1156 mStateLock.unlock();
1157 return NO_ERROR;
1158}
1159
Peiyong Lin0256f722018-08-31 15:45:10 -07001160status_t SurfaceFlinger::getCompositionPreference(Dataspace* outDataSpace,
1161 ui::PixelFormat* outPixelFormat) const {
1162 *outDataSpace = compositionDataSpace;
1163 *outPixelFormat = compositionPixelFormat;
1164 return NO_ERROR;
1165}
1166
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001167// ----------------------------------------------------------------------------
1168
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001169sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1170 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001171 if (mUseScheduler) {
1172 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1173 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1174 } else {
1175 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1176 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001177 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001178 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1179 return mSFEventThread->createEventConnection();
1180 } else {
1181 return mEventThread->createEventConnection();
1182 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001183 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001184}
1185
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001186// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001187
1188void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001189 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001190}
1191
1192void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001193 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001194}
1195
1196void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001197 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001198}
1199
1200void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001201 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001202 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001203}
1204
1205status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001206 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001207 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001208}
1209
1210status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001211 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001212 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001213 if (res == NO_ERROR) {
1214 msg->wait();
1215 }
1216 return res;
1217}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001218
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001219void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001220 do {
1221 waitForEvent();
1222 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001223}
1224
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001225void SurfaceFlinger::enableHardwareVsync() {
1226 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001227 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001228 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001229 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001230 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001231 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001232}
1233
Jesse Hall948fe0c2013-10-14 12:56:09 -07001234void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001235 Mutex::Autolock _l(mHWVsyncLock);
1236
Jesse Hall948fe0c2013-10-14 12:56:09 -07001237 if (makeAvailable) {
1238 mHWVsyncAvailable = true;
1239 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001240 // Hardware vsync is not currently available, so abort the resync
1241 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001242 return;
1243 }
1244
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001245 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1246 if (!getHwComposer().isConnected(displayId)) {
1247 return;
1248 }
1249
1250 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001251 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001252
Ana Krulece588e312018-09-18 12:32:24 -07001253 if (mUseScheduler) {
1254 mScheduler->setVsyncPeriod(period);
1255 } else {
1256 mPrimaryDispSync->reset();
1257 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001258
Ana Krulece588e312018-09-18 12:32:24 -07001259 if (!mPrimaryHWVsyncEnabled) {
1260 mPrimaryDispSync->beginResync();
1261 mEventControlThread->setVsyncEnabled(true);
1262 mPrimaryHWVsyncEnabled = true;
1263 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001264 }
1265}
1266
Jesse Hall948fe0c2013-10-14 12:56:09 -07001267void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001268 Mutex::Autolock _l(mHWVsyncLock);
1269 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001270 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001271 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001272 mPrimaryHWVsyncEnabled = false;
1273 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001274 if (makeUnavailable) {
1275 mHWVsyncAvailable = false;
1276 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001277}
1278
Tim Murray4a4e4a22016-04-19 16:29:23 +00001279void SurfaceFlinger::resyncWithRateLimit() {
1280 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001281
1282 // No explicit locking is needed here since EventThread holds a lock while calling this method
1283 static nsecs_t sLastResyncAttempted = 0;
1284 const nsecs_t now = systemTime();
1285 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001286 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001287 }
Dan Stoza57164302017-05-08 14:03:54 -07001288 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001289}
1290
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001291void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1292 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001293 ATRACE_NAME("SF onVsync");
1294
Steven Thomas3cfac282017-02-06 12:29:30 -08001295 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001296 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001297 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001298 return;
1299 }
1300
1301 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001302 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001303 return;
1304 }
1305
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001306 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1307 // For now, we don't do anything with external display vsyncs.
1308 return;
1309 }
1310
Ana Krulece588e312018-09-18 12:32:24 -07001311 if (mUseScheduler) {
1312 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001313 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001314 bool needsHwVsync = false;
1315 { // Scope for the lock
1316 Mutex::Autolock _l(mHWVsyncLock);
1317 if (mPrimaryHWVsyncEnabled) {
1318 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1319 }
1320 }
1321
1322 if (needsHwVsync) {
1323 enableHardwareVsync();
1324 } else {
1325 disableHardwareVsync(false);
1326 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001327 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001328}
1329
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001330void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001331 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1332 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001333}
1334
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001335void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001336 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001337 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001338 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001339
Lloyd Piqueba04e622017-12-14 17:11:26 -08001340 // Ignore events that do not have the right sequenceId.
1341 if (sequenceId != getBE().mComposerSequenceId) {
1342 return;
1343 }
1344
Steven Thomasb02664d2017-07-26 18:48:28 -07001345 // Only lock if we're not on the main thread. This function is normally
1346 // called on a hwbinder thread, but for the primary display it's called on
1347 // the main thread with the state lock already held, so don't attempt to
1348 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001349 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001350
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001351 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001352
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001353 if (std::this_thread::get_id() == mMainThreadId) {
1354 // Process all pending hot plug events immediately if we are on the main thread.
1355 processDisplayHotplugEventsLocked();
1356 }
1357
Lloyd Piqueba04e622017-12-14 17:11:26 -08001358 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001359}
1360
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001361void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001362 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001363 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001364 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001365 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001366 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001367}
1368
Dan Stoza9e56aa02015-11-02 13:00:03 -08001369void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001370 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001371 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001372 getHwComposer().setVsyncEnabled(disp,
1373 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001374}
1375
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001376// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001377void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001378 if (mUseScheduler) {
1379 mScheduler->disableHardwareVsync(true);
1380 } else {
1381 disableHardwareVsync(true);
1382 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001383 // Clear the drawing state so that the logic inside of
1384 // handleTransactionLocked will fire. It will determine the delta between
1385 // mCurrentState and mDrawingState and re-apply all changes when we make the
1386 // transition.
1387 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001388 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001389 mDisplays.clear();
1390}
1391
Steven Thomas050b2c82017-03-06 11:45:16 -08001392void SurfaceFlinger::updateVrFlinger() {
1393 if (!mVrFlinger)
1394 return;
1395 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001396 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001397 return;
1398 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001399
David Sodman105b7dc2017-11-04 20:28:14 -07001400 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001401 ALOGE("Vr flinger is only supported for remote hardware composer"
1402 " service connections. Ignoring request to transition to vr"
1403 " flinger.");
1404 mVrFlingerRequestsDisplay = false;
1405 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001406 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001407
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001408 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001409
Steven Thomas0123ac62018-07-12 11:32:34 -07001410 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001411 LOG_ALWAYS_FATAL_IF(!display);
1412 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001413 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1414 // called below. Clear the reference now so we don't accidentally use it
1415 // later.
1416 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001417
Steven Thomasb02664d2017-07-26 18:48:28 -07001418 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001419 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001420 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001421
Steven Thomasb02664d2017-07-26 18:48:28 -07001422 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001423 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Pique90c115d2018-09-18 21:39:42 -07001424 getBE().mHwc = getFactory().createHWComposer(
1425 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -07001426 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001427
David Sodman105b7dc2017-11-04 20:28:14 -07001428 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1429 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001430
1431 if (vrFlingerRequestsDisplay) {
1432 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001433 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001434
1435 mVisibleRegionsDirty = true;
1436 invalidateHwcGeometry();
1437
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001438 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001439 display = getDefaultDisplayDeviceLocked();
1440 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001441 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001442
Steven Thomasb02664d2017-07-26 18:48:28 -07001443 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001444 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001445 const nsecs_t period = activeConfig->getVsyncPeriod();
1446 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001447
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001448 // The present fences returned from vr_hwc are not an accurate
1449 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001450 if (mUseScheduler) {
1451 mScheduler->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() || !hasSyncFramework);
1452 } else {
1453 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1454 !hasSyncFramework);
1455 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001456
Steven Thomasb02664d2017-07-26 18:48:28 -07001457 // Use phase of 0 since phase is not known.
1458 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001459 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1460 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001461
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001462 resyncToHardwareVsync(false);
1463
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001464 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001465 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001466}
1467
Mathias Agopian4fec8732012-06-29 14:12:52 -07001468void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001469 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001470 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001471 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001472 bool frameMissed = !mHadClientComposition &&
1473 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001474 (mPreviousPresentFence->getSignalTime() ==
1475 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001476 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001477 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001478 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001479 mTimeStats.incrementMissedFrames();
1480 if (mPropagateBackpressure) {
1481 signalLayerUpdate();
1482 break;
1483 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001484 }
Dan Stoza50182882016-07-08 12:02:20 -07001485
Steven Thomas050b2c82017-03-06 11:45:16 -08001486 // Now that we're going to make it to the handleMessageTransaction()
1487 // call below it's safe to call updateVrFlinger(), which will
1488 // potentially trigger a display handoff.
1489 updateVrFlinger();
1490
Dan Stoza6b9454d2014-11-07 16:00:59 -08001491 bool refreshNeeded = handleMessageTransaction();
1492 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001493 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001494 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001495 // Signal a refresh if a transaction modified the window state,
1496 // a new buffer was latched, or if HWC has requested a full
1497 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001498 signalRefresh();
1499 }
1500 break;
1501 }
1502 case MessageQueue::REFRESH: {
1503 handleMessageRefresh();
1504 break;
1505 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001506 }
1507}
1508
Dan Stoza6b9454d2014-11-07 16:00:59 -08001509bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001510 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001511 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001512 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001513 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001514 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001515 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001516}
1517
Mathias Agopian4fec8732012-06-29 14:12:52 -07001518void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001519 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001520
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001521 mRefreshPending = false;
1522
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001523 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001524 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001525 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001526 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001527 for (const auto& [token, display] : mDisplays) {
1528 beginFrame(display);
1529 prepareFrame(display);
1530 doDebugFlashRegions(display, repaintEverything);
1531 doComposition(display, repaintEverything);
1532 }
1533
Adrian Roos1e1a1282017-11-01 19:05:31 +01001534 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001535 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001536
1537 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001538 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001539
Dan Stozabfbffeb2016-07-21 14:49:33 -07001540 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001541 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001542 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001543 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001544 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001545
Alec Mouri86770e52018-09-24 22:40:58 +00001546 // Setup RenderEngine sync fences if native sync is supported.
1547 if (getBE().mRenderEngine->useNativeFenceSync()) {
1548 if (mHadClientComposition) {
1549 base::unique_fd flushFence(getRenderEngine().flush());
1550 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1551 getBE().flushFence = new Fence(std::move(flushFence));
1552 } else {
1553 // Cleanup for hygiene.
1554 getBE().flushFence = Fence::NO_FENCE;
1555 }
1556 }
1557
Jorim Jaggi90535212018-05-23 23:44:06 +02001558 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001559
David Sodman7e4ae112018-02-09 15:02:28 -08001560 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001561 for (const auto& [token, display] : mDisplays) {
1562 const auto displayId = display->getId();
David Sodman7e4ae112018-02-09 15:02:28 -08001563 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[displayId]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001564 compositionInfo.hwc.hwcLayer = nullptr;
1565 }
David Sodmanba340492018-08-05 21:51:33 -07001566 }
David Sodman7e4ae112018-02-09 15:02:28 -08001567
1568 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001569}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001570
David Sodmanfa9b2af2017-12-24 13:28:59 -08001571
1572bool SurfaceFlinger::handleMessageInvalidate() {
1573 ATRACE_CALL();
1574 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001575}
1576
David Sodman79bba0e2018-08-05 18:07:49 -07001577void SurfaceFlinger::calculateWorkingSet() {
1578 ATRACE_CALL();
1579 ALOGV(__FUNCTION__);
1580
David Sodman79bba0e2018-08-05 18:07:49 -07001581 // build the h/w work list
1582 if (CC_UNLIKELY(mGeometryInvalid)) {
1583 mGeometryInvalid = false;
1584 for (const auto& [token, display] : mDisplays) {
1585 const auto displayId = display->getId();
1586 if (displayId >= 0) {
1587 const Vector<sp<Layer>>& currentLayers(
1588 display->getVisibleLayersSortedByZ());
1589 for (size_t i = 0; i < currentLayers.size(); i++) {
1590 const auto& layer = currentLayers[i];
1591
1592 if (!layer->hasHwcLayer(displayId)) {
1593 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1594 layer->forceClientComposition(displayId);
1595 continue;
1596 }
1597 }
1598
1599 layer->setGeometry(display, i);
1600 if (mDebugDisableHWC || mDebugRegion) {
1601 layer->forceClientComposition(displayId);
1602 }
1603 }
1604 }
1605 }
1606 }
1607
1608 // Set the per-frame data
1609 for (const auto& [token, display] : mDisplays) {
1610 const auto displayId = display->getId();
1611 if (displayId < 0) {
1612 continue;
1613 }
1614
1615 if (mDrawingState.colorMatrixChanged) {
1616 display->setColorTransform(mDrawingState.colorMatrix);
1617 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1618 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1619 "display %d: %d", displayId, result);
1620 }
1621 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1622 if (layer->isHdrY410()) {
1623 layer->forceClientComposition(displayId);
1624 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1625 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1626 !display->hasHDR10Support()) {
1627 layer->forceClientComposition(displayId);
1628 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1629 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1630 !display->hasHLGSupport()) {
1631 layer->forceClientComposition(displayId);
1632 }
1633
Peiyong Lind3788632018-09-18 16:01:31 -07001634 // TODO(b/111562338) remove when composer 2.3 is shipped.
1635 if (layer->hasColorTransform()) {
1636 layer->forceClientComposition(displayId);
1637 }
1638
David Sodman79bba0e2018-08-05 18:07:49 -07001639 if (layer->getForceClientComposition(displayId)) {
1640 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1641 layer->setCompositionType(displayId, HWC2::Composition::Client);
1642 continue;
1643 }
1644
1645 layer->setPerFrameData(display);
1646 }
1647
Peiyong Lin13effd12018-07-24 17:01:47 -07001648 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001649 ColorMode colorMode;
1650 Dataspace dataSpace;
1651 RenderIntent renderIntent;
1652 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1653 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1654 }
1655 }
1656
1657 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001658
1659 for (const auto& [token, display] : mDisplays) {
David Sodman15fb96e2018-01-07 10:23:24 -08001660 const auto displayId = display->getId();
1661 getBE().mCompositionInfo[displayId].clear();
David Sodmanba340492018-08-05 21:51:33 -07001662 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1663 auto displayId = display->getId();
1664 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1665 if (!layer->setHwcLayer(displayId)) {
1666 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1667 }
David Sodman15fb96e2018-01-07 10:23:24 -08001668 layer->getBE().compositionInfo.hwc.displayId = displayId;
1669 getBE().mCompositionInfo[displayId].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001670 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1671 }
1672 }
David Sodman79bba0e2018-08-05 18:07:49 -07001673}
1674
David Sodmanfa9b2af2017-12-24 13:28:59 -08001675void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001676{
David Sodmanfb95bcc2017-12-22 15:45:30 -08001677 const auto displayId = display->getId();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001678 // is debugging enabled
1679 if (CC_LIKELY(!mDebugRegion))
1680 return;
1681
David Sodmanfa9b2af2017-12-24 13:28:59 -08001682 if (display->isPoweredOn()) {
1683 // transform the dirty region into this screen's coordinate space
1684 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1685 if (!dirtyRegion.isEmpty()) {
1686 // redraw the whole screen
1687 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001688
David Sodmanfa9b2af2017-12-24 13:28:59 -08001689 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001690 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001691 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001692
David Sodmanfa9b2af2017-12-24 13:28:59 -08001693 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001694 }
1695 }
1696
David Sodmanfa9b2af2017-12-24 13:28:59 -08001697 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001698
1699 if (mDebugRegion > 1) {
1700 usleep(mDebugRegion * 1000);
1701 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001702
David Sodmanfa9b2af2017-12-24 13:28:59 -08001703 if (display->isPoweredOn()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08001704 status_t result = display->prepareFrame(
1705 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001706 ALOGE_IF(result != NO_ERROR,
1707 "prepareFrame for display %d failed:"
1708 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001709 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001710 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001711}
1712
Adrian Roos1e1a1282017-11-01 19:05:31 +01001713void SurfaceFlinger::doTracing(const char* where) {
1714 ATRACE_CALL();
1715 ATRACE_NAME(where);
1716 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001717 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001718 }
1719}
1720
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001721void SurfaceFlinger::logLayerStats() {
1722 ATRACE_CALL();
1723 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001724 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001725 if (display->isPrimary()) {
1726 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001727 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001728 }
1729 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001730
1731 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001732 }
1733}
1734
David Sodman2b406362017-12-15 13:33:47 -08001735void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001736{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001737 ATRACE_CALL();
1738 ALOGV("preComposition");
1739
David Sodman2b406362017-12-15 13:33:47 -08001740 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1741
Mathias Agopiancd60f992012-08-16 16:28:27 -07001742 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001743 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001744 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001745 needExtraInvalidate = true;
1746 }
Robert Carr2047fae2016-11-28 14:09:09 -08001747 });
1748
Mathias Agopiancd60f992012-08-16 16:28:27 -07001749 if (needExtraInvalidate) {
1750 signalLayerUpdate();
1751 }
1752}
1753
Ana Krulece588e312018-09-18 12:32:24 -07001754void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1755 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001756 // Update queue of past composite+present times and determine the
1757 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001758 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001759 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001760 while (!getBE().mCompositePresentTimes.empty()) {
1761 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001762 // Cached values should have been updated before calling this method,
1763 // which helps avoid duplicate syscalls.
1764 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1765 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1766 break;
1767 }
1768 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001769 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001770 }
1771
1772 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001773 while (getBE().mCompositePresentTimes.size() > 16) {
1774 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001775 }
1776
Ana Krulece588e312018-09-18 12:32:24 -07001777 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001778}
1779
Ana Krulece588e312018-09-18 12:32:24 -07001780void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1781 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001782 // Integer division and modulo round toward 0 not -inf, so we need to
1783 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001784 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1785 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1786 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001787
Brian Andersond0010582017-03-07 13:20:31 -08001788 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1789 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001790 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001791 }
1792
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001793 // Snap the latency to a value that removes scheduling jitter from the
1794 // composition and present times, which often have >1ms of jitter.
1795 // Reducing jitter is important if an app attempts to extrapolate
1796 // something (such as user input) to an accurate diasplay time.
1797 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1798 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001799 nsecs_t bias = stats.vsyncPeriod / 2;
1800 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1801 nsecs_t snappedCompositeToPresentLatency =
1802 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001803
David Sodman99974d22017-11-28 12:04:33 -08001804 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001805 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1806 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001807 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001808}
1809
David Sodman2b406362017-12-15 13:33:47 -08001810void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001811{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001812 ATRACE_CALL();
1813 ALOGV("postComposition");
1814
Brian Anderson3546a3f2016-07-14 11:51:14 -07001815 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001816 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001817 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001818 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001819 }
1820
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001821 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001822 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001823
David Sodman73beded2017-11-15 11:56:06 -08001824 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001825 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001826 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001827 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001828 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001829 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001830 } else {
1831 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1832 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001833
David Sodman73beded2017-11-15 11:56:06 -08001834 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001835 mPreviousPresentFence =
1836 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1837 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001838 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001839
Ana Krulece588e312018-09-18 12:32:24 -07001840 DisplayStatInfo stats;
1841 if (mUseScheduler) {
1842 mScheduler->getDisplayStatInfo(&stats);
1843 } else {
1844 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1845 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
1846 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001847
David Sodman2b406362017-12-15 13:33:47 -08001848 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001849 // when we started doing work for this frame, but that should be okay
1850 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07001851 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001852 CompositorTiming compositorTiming;
1853 {
David Sodman99974d22017-11-28 12:04:33 -08001854 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1855 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001856 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001857
Robert Carr2047fae2016-11-28 14:09:09 -08001858 mDrawingState.traverseInZOrder([&](Layer* layer) {
1859 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001860 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001861 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001862 recordBufferingStats(layer->getName().string(),
1863 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001864 }
Robert Carr2047fae2016-11-28 14:09:09 -08001865 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001866
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001867 if (presentFenceTime->isValid()) {
Ana Krulece588e312018-09-18 12:32:24 -07001868 if (mUseScheduler) {
1869 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001870 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001871 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
1872 enableHardwareVsync();
1873 } else {
1874 disableHardwareVsync(false);
1875 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001876 }
1877 }
1878
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001879 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001880 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07001881 if (mUseScheduler) {
1882 mScheduler->enableHardwareVsync();
1883 } else {
1884 enableHardwareVsync();
1885 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001886 }
1887 }
1888
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001889 if (mAnimCompositionPending) {
1890 mAnimCompositionPending = false;
1891
Brian Anderson4e606e32017-03-16 15:34:57 -07001892 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001893 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001894 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001895 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001896 // The HWC doesn't support present fences, so use the refresh
1897 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001898 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001899 mAnimFrameTracker.setActualPresentTime(presentTime);
1900 }
1901 mAnimFrameTracker.advanceFrame();
1902 }
Dan Stozab90cf072015-03-05 11:05:59 -08001903
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001904 mTimeStats.incrementTotalFrames();
1905 if (mHadClientComposition) {
1906 mTimeStats.incrementClientCompositionFrames();
1907 }
1908
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001909 mTimeStats.setPresentFenceGlobal(presentFenceTime);
1910
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001911 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001912 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001913 return;
1914 }
1915
1916 nsecs_t currentTime = systemTime();
1917 if (mHasPoweredOff) {
1918 mHasPoweredOff = false;
1919 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001920 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001921 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001922 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1923 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001924 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001925 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001926 }
David Sodman4a36e932017-11-07 14:29:47 -08001927 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001928 }
David Sodman4a36e932017-11-07 14:29:47 -08001929 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001930
1931 {
1932 std::lock_guard lock(mTexturePoolMutex);
1933 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1934 if (refillCount > 0) {
1935 const size_t offset = mTexturePool.size();
1936 mTexturePool.resize(mTexturePoolSize);
1937 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1938 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1939 }
1940 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001941}
1942
1943void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001944 ATRACE_CALL();
1945 ALOGV("rebuildLayerStacks");
1946
Mathias Agopiancd60f992012-08-16 16:28:27 -07001947 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001948 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001949 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001950 mVisibleRegionsDirty = false;
1951 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001952
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001953 for (const auto& pair : mDisplays) {
1954 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001955 Region opaqueRegion;
1956 Region dirtyRegion;
1957 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001958 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001959 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001960 const Rect bounds = display->getBounds();
1961 if (display->isPoweredOn()) {
1962 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001963
Jeff Sharkey76488112017-02-27 14:15:18 -07001964 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001965 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001966 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001967 Region drawRegion(tr.transform(
1968 layer->visibleNonTransparentRegion));
1969 drawRegion.andSelf(bounds);
1970 if (!drawRegion.isEmpty()) {
1971 layersSortedByZ.add(layer);
1972 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001973 // Clear out the HWC layer if this layer was
1974 // previously visible, but no longer is
1975 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001976 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001977 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001978 // WM changes display->layerStack upon sleep/awake.
1979 // Here we make sure we delete the HWC layers even if
1980 // WM changed their layer stack.
1981 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001982 }
1983
1984 // If a layer is not going to get a release fence because
1985 // it is invisible, but it is also going to release its
1986 // old buffer, add it to the list of layers needing
1987 // fences.
1988 if (hwcLayerDestroyed) {
1989 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1990 mLayersWithQueuedFrames.cend(), layer);
1991 if (found != mLayersWithQueuedFrames.cend()) {
1992 layersNeedingFences.add(layer);
1993 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001994 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001995 });
1996 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001997 display->setVisibleLayersSortedByZ(layersSortedByZ);
1998 display->setLayersNeedingFences(layersNeedingFences);
1999 display->undefinedRegion.set(bounds);
2000 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2001 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002002 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002003 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002004}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002005
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002006// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002007// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002008// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002009// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002010// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002011// The returned HDR data space is one of
2012// - Dataspace::UNKNOWN
2013// - Dataspace::BT2020_HLG
2014// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002015Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2016 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07002017 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002018 *outHdrDataSpace = Dataspace::UNKNOWN;
2019
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002020 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002021 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002022 case Dataspace::V0_SCRGB:
2023 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002024 case Dataspace::BT2020:
2025 case Dataspace::BT2020_ITU:
2026 case Dataspace::BT2020_LINEAR:
2027 case Dataspace::DISPLAY_BT2020:
2028 bestDataSpace = Dataspace::DISPLAY_BT2020;
2029 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002030 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002031 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002032 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002033 case Dataspace::BT2020_PQ:
2034 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002035 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002036 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002037 case Dataspace::BT2020_HLG:
2038 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002039 // When there's mixed PQ content and HLG content, we set the HDR
2040 // data space to be BT2020_PQ and convert HLG to PQ.
2041 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2042 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002043 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002044 break;
2045 default:
2046 break;
2047 }
Romain Guy54f154a2017-10-24 21:40:32 +01002048 }
2049
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002050 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002051}
2052
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002053// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002054void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2055 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002056 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2057 *outMode = ColorMode::NATIVE;
2058 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002059 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002060 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002061 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002062
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002063 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002064 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002065
Peiyong Lindfde5112018-06-05 10:58:41 -07002066 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002067 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002068 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002069 if (isHdr) {
2070 bestDataSpace = hdrDataSpace;
2071 }
2072
Chia-I Wu0d711262018-05-21 15:19:35 -07002073 RenderIntent intent;
2074 switch (mDisplayColorSetting) {
2075 case DisplayColorSetting::MANAGED:
2076 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002077 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002078 break;
2079 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002080 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002081 break;
2082 default: // vendor display color setting
2083 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2084 break;
2085 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002086
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002087 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002088}
2089
David Sodmanfa9b2af2017-12-24 13:28:59 -08002090void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002091{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002092 bool dirty = !display->getDirtyRegion(false).isEmpty();
2093 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2094 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002095
David Sodmanfa9b2af2017-12-24 13:28:59 -08002096 // If nothing has changed (!dirty), don't recompose.
2097 // If something changed, but we don't currently have any visible layers,
2098 // and didn't when we last did a composition, then skip it this time.
2099 // The second rule does two things:
2100 // - When all layers are removed from a display, we'll emit one black
2101 // frame, then nothing more until we get new layers.
2102 // - When a display is created with a private layer stack, we won't
2103 // emit any black frames until a layer is added to the layer stack.
2104 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002105
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002106 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2107 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002108 mustRecompose ? "doing" : "skipping",
2109 dirty ? "+" : "-",
2110 empty ? "+" : "-",
2111 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002112
David Sodmanfa9b2af2017-12-24 13:28:59 -08002113 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002114
David Sodmanfa9b2af2017-12-24 13:28:59 -08002115 if (mustRecompose) {
2116 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002117 }
2118}
2119
David Sodmanfa9b2af2017-12-24 13:28:59 -08002120void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002121{
David Sodmanfb95bcc2017-12-22 15:45:30 -08002122 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002123 if (!display->isPoweredOn()) {
2124 return;
David Sodman2b406362017-12-15 13:33:47 -08002125 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002126
David Sodmanfb95bcc2017-12-22 15:45:30 -08002127 status_t result = display->prepareFrame(
2128 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08002129 ALOGE_IF(result != NO_ERROR,
2130 "prepareFrame for display %d failed:"
2131 " %d (%s)",
2132 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002133}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002134
David Sodmanfa9b2af2017-12-24 13:28:59 -08002135void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002136 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002137 ALOGV("doComposition");
2138
David Sodmanfa9b2af2017-12-24 13:28:59 -08002139 if (display->isPoweredOn()) {
2140 // transform the dirty region into this screen's coordinate space
2141 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002142
David Sodmanfa9b2af2017-12-24 13:28:59 -08002143 // repaint the framebuffer (if needed)
2144 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002145
David Sodmanfa9b2af2017-12-24 13:28:59 -08002146 display->dirtyRegion.clear();
2147 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002148 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002149 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002150}
2151
David Sodmanfa9b2af2017-12-24 13:28:59 -08002152void SurfaceFlinger::postFrame()
2153{
2154 // |mStateLock| not needed as we are on the main thread
2155 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2156 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2157 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2158 logFrameStats();
2159 }
2160 }
2161}
2162
2163void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002164{
Mathias Agopian841cde52012-03-01 15:44:37 -08002165 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002166 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002167
David Sodmanfa9b2af2017-12-24 13:28:59 -08002168 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002169
David Sodmanfa9b2af2017-12-24 13:28:59 -08002170 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002171 const auto displayId = display->getId();
2172 if (displayId >= 0) {
2173 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002174 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002175 display->onSwapBuffersCompleted();
2176 display->makeCurrent();
David Sodman15094112018-10-11 09:39:37 -07002177 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002178 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002179
Chia-I Wu7b549592017-11-15 09:14:57 -08002180 // The layer buffer from the previous frame (if any) is released
2181 // by HWC only when the release fence from this frame (if any) is
2182 // signaled. Always get the release fence from HWC first.
David Sodman15094112018-10-11 09:39:37 -07002183 auto hwcLayer = layer->getHwcLayer(displayId);
2184 if (displayId >= 0) {
2185 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002186 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002187
2188 // If the layer was client composited in the previous frame, we
2189 // need to merge with the previous client target acquire fence.
2190 // Since we do not track that, always merge with the current
2191 // client target acquire fence when it is available, even though
2192 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002193 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002194 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002195 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002196 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002197
David Sodman15094112018-10-11 09:39:37 -07002198 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002199 }
Chia-I Wu83806892017-11-16 10:50:20 -08002200
2201 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002202 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002203 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002204 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002205 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002206 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002207 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002208 }
2209 }
2210
Dominik Laskowski7e045462018-05-30 13:02:02 -07002211 if (displayId >= 0) {
2212 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002213 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002214 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002215}
2216
Mathias Agopian87baae12012-07-31 12:38:26 -07002217void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002218{
Mathias Agopian841cde52012-03-01 15:44:37 -08002219 ATRACE_CALL();
2220
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002221 // here we keep a copy of the drawing state (that is the state that's
2222 // going to be overwritten by handleTransactionLocked()) outside of
2223 // mStateLock so that the side-effects of the State assignment
2224 // don't happen with mStateLock held (which can cause deadlocks).
2225 State drawingState(mDrawingState);
2226
Mathias Agopianca4d3602011-05-19 15:38:14 -07002227 Mutex::Autolock _l(mStateLock);
2228 const nsecs_t now = systemTime();
2229 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002230
Mathias Agopianca4d3602011-05-19 15:38:14 -07002231 // Here we're guaranteed that some transaction flags are set
2232 // so we can call handleTransactionLocked() unconditionally.
2233 // We call getTransactionFlags(), which will also clear the flags,
2234 // with mStateLock held to guarantee that mCurrentState won't change
2235 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002236
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002237 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002238 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002239 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002240
Mathias Agopianca4d3602011-05-19 15:38:14 -07002241 mLastTransactionTime = systemTime() - now;
2242 mDebugInTransaction = 0;
2243 invalidateHwcGeometry();
2244 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002245}
2246
Dominik Laskowski7e045462018-05-30 13:02:02 -07002247DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002248 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002249 // Figure out whether the event is for the primary display or an
2250 // external display by matching the Hwc display id against one for a
2251 // connected display. If we did not find a match, we then check what
2252 // displays are not already connected to determine the type. If we don't
2253 // have a connected primary display, we assume the new display is meant to
2254 // be the primary display, and then if we don't have an external display,
2255 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002256 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2257 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002258 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002259 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002260 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002261 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002262 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002263 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002264 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002265 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002266 return DisplayDevice::DISPLAY_EXTERNAL;
2267 }
2268
2269 return DisplayDevice::DISPLAY_ID_INVALID;
2270}
2271
Lloyd Piqueba04e622017-12-14 17:11:26 -08002272void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2273 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002274 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002275 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002276 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002277 continue;
2278 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002279
2280 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2281 ALOGE("External displays are not supported by the vr hardware composer.");
2282 continue;
2283 }
2284
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002285 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002286 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002287 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002288 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002289 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002290
2291 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002292 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002293 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002294 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002295 DisplayDeviceState info;
2296 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002297 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2298 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002299 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002300 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002301 mInterceptor->saveDisplayCreation(info);
2302 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002303 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002304 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002305
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002306 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002307 if (idx >= 0) {
2308 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002309 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002310 mCurrentState.displays.removeItemsAt(idx);
2311 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002312 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002313 }
2314
2315 processDisplayChangesLocked();
2316 }
2317
2318 mPendingHotplugEvents.clear();
2319}
2320
Lloyd Pique99d3da52018-01-22 17:48:03 -08002321sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002322 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002323 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002324 DisplayDeviceCreationArgs creationArgs(this, displayToken, state.type, displayId);
2325 creationArgs.isSecure = state.isSecure;
2326 creationArgs.displaySurface = dispSurface;
2327 creationArgs.hasWideColorGamut = false;
2328 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002329
Peiyong Lin13effd12018-07-24 17:01:47 -07002330 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002331 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002332 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002333 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002334 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002335 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002336
Dominik Laskowski7e045462018-05-30 13:02:02 -07002337 std::vector<RenderIntent> renderIntents =
2338 getHwComposer().getRenderIntents(displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002339 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002340 }
tangrobin6753a022018-08-10 10:58:54 +08002341 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002342
tangrobin6753a022018-08-10 10:58:54 +08002343 if (displayId >= 0) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002344 getHwComposer().getHdrCapabilities(displayId, &creationArgs.hdrCapabilities);
2345 creationArgs.supportedPerFrameMetadata =
2346 getHwComposer().getSupportedPerFrameMetadata(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002347 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002348
Lloyd Pique90c115d2018-09-18 21:39:42 -07002349 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002350 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002351 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002352
2353 /*
2354 * Create our display's surface
2355 */
Peiyong Lin833074a2018-08-28 11:53:54 -07002356 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002357 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002358 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002359 renderSurface->setNativeWindow(nativeWindow.get());
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002360 creationArgs.displayWidth = renderSurface->getWidth();
2361 creationArgs.displayHeight = renderSurface->getHeight();
2362 creationArgs.renderSurface = std::move(renderSurface);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002363
2364 // Make sure that composition can never be stalled by a virtual display
2365 // consumer that isn't processing buffers fast enough. We have to do this
2366 // in two places:
2367 // * Here, in case the display is composed entirely by HWC.
2368 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2369 // window's swap interval in eglMakeCurrent, so they'll override the
2370 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002371 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002372 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2373 }
2374
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002375 creationArgs.displayInstallOrientation = state.type == DisplayDevice::DISPLAY_PRIMARY
2376 ? primaryDisplayOrientation
2377 : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002378
Lloyd Pique99d3da52018-01-22 17:48:03 -08002379 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002380 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002381
Lloyd Pique90c115d2018-09-18 21:39:42 -07002382 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002383
2384 if (maxFrameBufferAcquiredBuffers >= 3) {
2385 nativeWindowSurface->preallocateBuffers();
2386 }
2387
2388 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002389 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002390 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002391 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002392 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002393 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002394 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002395 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002396 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002397 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002398 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002399 display->setLayerStack(state.layerStack);
2400 display->setProjection(state.orientation, state.viewport, state.frame);
2401 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002402
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002403 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002404}
2405
Lloyd Pique347200f2017-12-14 17:00:15 -08002406void SurfaceFlinger::processDisplayChangesLocked() {
2407 // here we take advantage of Vector's copy-on-write semantics to
2408 // improve performance by skipping the transaction entirely when
2409 // know that the lists are identical
2410 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2411 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2412 if (!curr.isIdenticalTo(draw)) {
2413 mVisibleRegionsDirty = true;
2414 const size_t cc = curr.size();
2415 size_t dc = draw.size();
2416
2417 // find the displays that were removed
2418 // (ie: in drawing state but not in current state)
2419 // also handle displays that changed
2420 // (ie: displays that are in both lists)
2421 for (size_t i = 0; i < dc;) {
2422 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2423 if (j < 0) {
2424 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002425 // Call makeCurrent() on the primary display so we can
2426 // be sure that nothing associated with this display
2427 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002428 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2429 defaultDisplay->makeCurrent();
2430 }
2431 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2432 display->disconnect(getHwComposer());
2433 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002434 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002435 if (mUseScheduler) {
2436 mScheduler->hotplugReceived(mAppConnectionHandle,
2437 EventThread::DisplayType::Primary, false);
2438 } else {
2439 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2440 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002441 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002442 if (mUseScheduler) {
2443 mScheduler->hotplugReceived(mAppConnectionHandle,
2444 EventThread::DisplayType::External, false);
2445 } else {
2446 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2447 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002448 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002449 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002450 } else {
2451 // this display is in both lists. see if something changed.
2452 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002453 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002454 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2455 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2456 if (state_binder != draw_binder) {
2457 // changing the surface is like destroying and
2458 // recreating the DisplayDevice, so we just remove it
2459 // from the drawing state, so that it get re-added
2460 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002461 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2462 display->disconnect(getHwComposer());
2463 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002464 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002465 mDrawingState.displays.removeItemsAt(i);
2466 dc--;
2467 // at this point we must loop to the next item
2468 continue;
2469 }
2470
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002471 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002472 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002473 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002474 }
2475 if ((state.orientation != draw[i].orientation) ||
2476 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002477 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002478 }
2479 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002480 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002481 }
2482 }
2483 }
2484 ++i;
2485 }
2486
2487 // find displays that were added
2488 // (ie: in current state but not in drawing state)
2489 for (size_t i = 0; i < cc; i++) {
2490 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2491 const DisplayDeviceState& state(curr[i]);
2492
2493 sp<DisplaySurface> dispSurface;
2494 sp<IGraphicBufferProducer> producer;
2495 sp<IGraphicBufferProducer> bqProducer;
2496 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002497 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002498
Dominik Laskowski7e045462018-05-30 13:02:02 -07002499 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002500 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002501 // Virtual displays without a surface are dormant:
2502 // they have external state (layer stack, projection,
2503 // etc.) but no internal state (i.e. a DisplayDevice).
2504 if (state.surface != nullptr) {
2505 // Allow VR composer to use virtual displays.
2506 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2507 int width = 0;
2508 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2509 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2510 int height = 0;
2511 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2512 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2513 int intFormat = 0;
2514 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2515 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002516 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002517
Dominik Laskowski7e045462018-05-30 13:02:02 -07002518 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2519 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002520 }
2521
2522 // TODO: Plumb requested format back up to consumer
2523
2524 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002525 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002526 bqProducer, bqConsumer,
2527 state.displayName);
2528
2529 dispSurface = vds;
2530 producer = vds;
2531 }
2532 } else {
2533 ALOGE_IF(state.surface != nullptr,
2534 "adding a supported display, but rendering "
2535 "surface is provided (%p), ignoring it",
2536 state.surface.get());
2537
Dominik Laskowski7e045462018-05-30 13:02:02 -07002538 displayId = state.type;
2539 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002540 producer = bqProducer;
2541 }
2542
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002543 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002544 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002545 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002546 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002547 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002548 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002549 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002550 if (mUseScheduler) {
2551 mScheduler->hotplugReceived(mAppConnectionHandle,
2552 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002553 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002554 } else {
2555 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2556 true);
2557 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002558 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002559 if (mUseScheduler) {
2560 mScheduler->hotplugReceived(mAppConnectionHandle,
2561 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002562 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002563 } else {
2564 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2565 true);
2566 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002567 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002568 }
2569 }
2570 }
2571 }
2572 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002573
2574 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002575}
2576
Mathias Agopian87baae12012-07-31 12:38:26 -07002577void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002578{
Dan Stoza7dde5992015-05-22 09:51:44 -07002579 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002580 mCurrentState.traverseInZOrder([](Layer* layer) {
2581 layer->notifyAvailableFrames();
2582 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002583
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002584 /*
2585 * Traversal of the children
2586 * (perform the transaction for each of them if needed)
2587 */
2588
Mathias Agopian3559b072012-08-15 13:46:03 -07002589 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002590 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002591 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002592 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002593
2594 const uint32_t flags = layer->doTransaction(0);
2595 if (flags & Layer::eVisibleRegion)
2596 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002597 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002598 }
2599
2600 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002601 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002602 */
2603
Mathias Agopiane57f2922012-08-09 16:29:12 -07002604 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002605 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002606 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002607 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002608
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002609 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002610 // The transform hint might have changed for some layers
2611 // (either because a display has changed, or because a layer
2612 // as changed).
2613 //
2614 // Walk through all the layers in currentLayers,
2615 // and update their transform hint.
2616 //
2617 // If a layer is visible only on a single display, then that
2618 // display is used to calculate the hint, otherwise we use the
2619 // default display.
2620 //
2621 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2622 // the hint is set before we acquire a buffer from the surface texture.
2623 //
2624 // NOTE: layer transactions have taken place already, so we use their
2625 // drawing state. However, SurfaceFlinger's own transaction has not
2626 // happened yet, so we must use the current state layer list
2627 // (soon to become the drawing state list).
2628 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002629 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002630 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002631 bool first = true;
2632 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002633 // NOTE: we rely on the fact that layers are sorted by
2634 // layerStack first (so we don't have to traverse the list
2635 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002636 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002637 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002638 currentlayerStack = layerStack;
2639 // figure out if this layerstack is mirrored
2640 // (more than one display) if so, pick the default display,
2641 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002642 hintDisplay = nullptr;
2643 for (const auto& [token, display] : mDisplays) {
2644 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2645 if (hintDisplay) {
2646 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002647 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002648 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002649 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002650 }
2651 }
2652 }
2653 }
Chet Haase91d25932013-04-11 15:24:55 -07002654
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002655 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002656 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2657 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002658
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002659 // could be null when this layer is using a layerStack
2660 // that is not visible on any display. Also can occur at
2661 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002662 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002663 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002664
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002665 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002666 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002667 if (hintDisplay) {
2668 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002669 }
Robert Carr2047fae2016-11-28 14:09:09 -08002670
2671 first = false;
2672 });
Mathias Agopian84300952012-11-21 16:02:13 -08002673 }
2674
2675
Mathias Agopian3559b072012-08-15 13:46:03 -07002676 /*
2677 * Perform our own transaction if needed
2678 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002679
2680 if (mLayersAdded) {
2681 mLayersAdded = false;
2682 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002683 mVisibleRegionsDirty = true;
2684 }
2685
2686 // some layers might have been removed, so
2687 // we need to update the regions they're exposing.
2688 if (mLayersRemoved) {
2689 mLayersRemoved = false;
2690 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002691 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002692 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002693 // this layer is not visible anymore
2694 // TODO: we could traverse the tree from front to back and
2695 // compute the actual visible region
2696 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002697 Region visibleReg;
2698 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002699 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002700 }
Robert Carr2047fae2016-11-28 14:09:09 -08002701 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002702 }
2703
2704 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002705
2706 updateCursorAsync();
2707}
2708
2709void SurfaceFlinger::updateCursorAsync()
2710{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002711 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002712 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002713 continue;
2714 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002715
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002716 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2717 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002718 }
2719 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002720}
2721
2722void SurfaceFlinger::commitTransaction()
2723{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002724 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002725 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002726 for (const auto& l : mLayersPendingRemoval) {
2727 recordBufferingStats(l->getName().string(),
2728 l->getOccupancyHistory(true));
Jorim Jaggi10c985e2018-10-23 11:17:45 +00002729 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002730 }
2731 mLayersPendingRemoval.clear();
2732 }
2733
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002734 // If this transaction is part of a window animation then the next frame
2735 // we composite should be considered an animation as well.
2736 mAnimCompositionPending = mAnimTransactionPending;
2737
Mathias Agopian4fec8732012-06-29 14:12:52 -07002738 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002739 // clear the "changed" flags in current state
2740 mCurrentState.colorMatrixChanged = false;
2741
Robert Carr1f0a16a2016-10-24 16:27:39 -07002742 mDrawingState.traverseInZOrder([](Layer* layer) {
2743 layer->commitChildList();
2744 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002745 mTransactionPending = false;
2746 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002747 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002748}
2749
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002750void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2751 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002752 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002753 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002754
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002755 Region aboveOpaqueLayers;
2756 Region aboveCoveredLayers;
2757 Region dirty;
2758
Mathias Agopian87baae12012-07-31 12:38:26 -07002759 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002760
Robert Carr2047fae2016-11-28 14:09:09 -08002761 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002762 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002763 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002764
Jesse Hall01e29052013-02-19 16:13:35 -08002765 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002766 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002767 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002768 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002769
Mathias Agopianab028732010-03-16 16:41:46 -07002770 /*
2771 * opaqueRegion: area of a surface that is fully opaque.
2772 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002773 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002774
2775 /*
2776 * visibleRegion: area of a surface that is visible on screen
2777 * and not fully transparent. This is essentially the layer's
2778 * footprint minus the opaque regions above it.
2779 * Areas covered by a translucent surface are considered visible.
2780 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002781 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002782
2783 /*
2784 * coveredRegion: area of a surface that is covered by all
2785 * visible regions above it (which includes the translucent areas).
2786 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002787 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002788
Jesse Halla8026d22012-09-25 13:25:04 -07002789 /*
2790 * transparentRegion: area of a surface that is hinted to be completely
2791 * transparent. This is only used to tell when the layer has no visible
2792 * non-transparent regions and can be removed from the layer list. It
2793 * does not affect the visibleRegion of this layer or any layers
2794 * beneath it. The hint may not be correct if apps don't respect the
2795 * SurfaceView restrictions (which, sadly, some don't).
2796 */
2797 Region transparentRegion;
2798
Mathias Agopianab028732010-03-16 16:41:46 -07002799
2800 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002801 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002802 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002803 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002804 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002805 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002806 if (!visibleRegion.isEmpty()) {
2807 // Remove the transparent area from the visible region
2808 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002809 if (tr.preserveRects()) {
2810 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002811 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002812 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002813 // transformation too complex, can't do the
2814 // transparent region optimization.
2815 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002816 }
Mathias Agopianab028732010-03-16 16:41:46 -07002817 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002818
Mathias Agopianab028732010-03-16 16:41:46 -07002819 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002820 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002821 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002822 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002823 // the opaque region is the layer's footprint
2824 opaqueRegion = visibleRegion;
2825 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002826 }
2827 }
2828
Robert Carre5f4f692018-01-12 13:12:28 -08002829 if (visibleRegion.isEmpty()) {
2830 layer->clearVisibilityRegions();
2831 return;
2832 }
2833
Mathias Agopianab028732010-03-16 16:41:46 -07002834 // Clip the covered region to the visible region
2835 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2836
2837 // Update aboveCoveredLayers for next (lower) layer
2838 aboveCoveredLayers.orSelf(visibleRegion);
2839
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002840 // subtract the opaque region covered by the layers above us
2841 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002842
2843 // compute this layer's dirty region
2844 if (layer->contentDirty) {
2845 // we need to invalidate the whole region
2846 dirty = visibleRegion;
2847 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002848 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002849 layer->contentDirty = false;
2850 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002851 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002852 * the exposed region consists of two components:
2853 * 1) what's VISIBLE now and was COVERED before
2854 * 2) what's EXPOSED now less what was EXPOSED before
2855 *
2856 * note that (1) is conservative, we start with the whole
2857 * visible region but only keep what used to be covered by
2858 * something -- which mean it may have been exposed.
2859 *
2860 * (2) handles areas that were not covered by anything but got
2861 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002862 */
Mathias Agopianab028732010-03-16 16:41:46 -07002863 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002864 const Region oldVisibleRegion = layer->visibleRegion;
2865 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002866 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2867 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002868 }
2869 dirty.subtractSelf(aboveOpaqueLayers);
2870
2871 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002872 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002873
Mathias Agopianab028732010-03-16 16:41:46 -07002874 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002875 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002876
Jesse Halla8026d22012-09-25 13:25:04 -07002877 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002878 layer->setVisibleRegion(visibleRegion);
2879 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002880 layer->setVisibleNonTransparentRegion(
2881 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002882 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002883
Mathias Agopian87baae12012-07-31 12:38:26 -07002884 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002885}
2886
Chia-I Wuab0c3192017-08-01 11:29:00 -07002887void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002888 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002889 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2890 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002891 }
2892 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002893}
2894
Dan Stoza6b9454d2014-11-07 16:00:59 -08002895bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002896{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002897 ALOGV("handlePageFlip");
2898
Brian Andersond6927fb2016-07-23 23:37:30 -07002899 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002900
Mathias Agopian4fec8732012-06-29 14:12:52 -07002901 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002902 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002903 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002904
2905 // Store the set of layers that need updates. This set must not change as
2906 // buffers are being latched, as this could result in a deadlock.
2907 // Example: Two producers share the same command stream and:
2908 // 1.) Layer 0 is latched
2909 // 2.) Layer 0 gets a new frame
2910 // 2.) Layer 1 gets a new frame
2911 // 3.) Layer 1 is latched.
2912 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2913 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002914 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002915 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002916 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002917 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2918 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002919 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002920 } else {
2921 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002922 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002923 } else {
2924 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002925 }
Robert Carr2047fae2016-11-28 14:09:09 -08002926 });
2927
Dan Stoza9e56aa02015-11-02 13:00:03 -08002928 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri86770e52018-09-24 22:40:58 +00002929 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
Dan Stozaee44edd2015-03-23 15:50:23 -07002930 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002931 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002932 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002933 newDataLatched = true;
2934 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002935 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002936
Alec Mouri86770e52018-09-24 22:40:58 +00002937 // Clear the renderengine fence here...
2938 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
2939 // clear instead of sp::clear.
2940 getBE().flushFence = Fence::NO_FENCE;
2941
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002942 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002943
2944 // If we will need to wake up at some time in the future to deal with a
2945 // queued frame that shouldn't be displayed during this vsync period, wake
2946 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002947 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002948 signalLayerUpdate();
2949 }
2950
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002951 // enter boot animation on first buffer latch
2952 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2953 ALOGI("Enter boot animation");
2954 mBootStage = BootStage::BOOTANIMATION;
2955 }
2956
Dan Stoza6b9454d2014-11-07 16:00:59 -08002957 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002958 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002959}
2960
Mathias Agopianad456f92011-01-13 17:53:01 -08002961void SurfaceFlinger::invalidateHwcGeometry()
2962{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002963 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002964}
2965
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002966void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2967 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002968 // We only need to actually compose the display if:
2969 // 1) It is being handled by hardware composer, which may need this to
2970 // keep its virtual display state machine in sync, or
2971 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002972 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002973 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002974 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002975 return;
2976 }
2977
Dan Stoza9e56aa02015-11-02 13:00:03 -08002978 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002979 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002980
2981 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002982 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002983}
2984
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002985bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002986 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002987
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002988 const Region bounds(display->bounds());
2989 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002990 const auto displayId = display->getId();
2991 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002992 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002993
Peiyong Lind3788632018-09-18 16:01:31 -07002994 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002995 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002996 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002997
Dan Stoza9e56aa02015-11-02 13:00:03 -08002998 if (hasClientComposition) {
2999 ALOGV("hasClientComposition");
3000
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003001 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003002 if (display->hasWideColorGamut()) {
3003 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003004 }
3005 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003006 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003007 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003008
Dominik Laskowski7e045462018-05-30 13:02:02 -07003009 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003010 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3011 HWC2::Capability::SkipClientColorTransform);
3012
Peiyong Lind3788632018-09-18 16:01:31 -07003013 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003014 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3015 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003016 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003017 }
3018
Chia-I Wud49d6692018-06-27 07:17:41 +08003019 // The current enhanced saturation matrix is designed to enhance Display P3,
3020 // thus we only apply this matrix when the render intent is not colorimetric
3021 // and the output color space is Display P3.
3022 needsEnhancedColorMatrix =
3023 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3024 outputDataspace == Dataspace::DISPLAY_P3);
3025 if (needsEnhancedColorMatrix) {
3026 colorMatrix *= mEnhancedSaturationMatrix;
3027 }
3028
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003029 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003030 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003031 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003032 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003033
3034 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003035 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3036 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3037 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003038 }
3039 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003040 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003041
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003042 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003043 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003044 // when using overlays, we assume a fully transparent framebuffer
3045 // NOTE: we could reduce how much we need to clear, for instance
3046 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003047 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003048 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003049 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003050 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003051 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003052 // we're left with the letterbox region
3053 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003054 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003055
3056 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003057 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003058
Mathias Agopianb9494d52012-04-18 02:28:45 -07003059 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003060 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003061 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003062 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003063 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003064 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003065
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003066 const Rect& bounds = display->getBounds();
3067 const Rect& scissor = display->getScissor();
3068 if (scissor != bounds) {
3069 // scissor doesn't match the screen's dimensions, so we
3070 // need to clear everything outside of it and enable
3071 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003072
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003073 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003074 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003075 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003076 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003077
Mathias Agopian85d751c2012-08-29 16:59:24 -07003078 /*
3079 * and then, render the layers targeted at the framebuffer
3080 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003081
Dan Stoza9e56aa02015-11-02 13:00:03 -08003082 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003083 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003084 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003085 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003086 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003087 displayTransform.transform(layer->visibleRegion)));
3088 ALOGV("Layer: %s", layer->getName().string());
3089 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003090 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003091 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003092 case HWC2::Composition::Cursor:
3093 case HWC2::Composition::Device:
3094 case HWC2::Composition::Sideband:
3095 case HWC2::Composition::SolidColor: {
David Sodmanc1498e62018-09-12 14:36:26 -07003096 const Layer::State& state(layer->getDrawingState());
3097 if (layer->getClearClientTarget(displayId) && !firstLayer &&
3098 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3099 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003100 // never clear the very first layer since we're
3101 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003102 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003103 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003104 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003105 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003106 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003107 if (layer->hasColorTransform()) {
3108 mat4 tmpMatrix;
3109 if (applyColorMatrix) {
3110 tmpMatrix = mDrawingState.colorMatrix;
3111 }
3112 tmpMatrix *= layer->getColorTransform();
3113 if (needsEnhancedColorMatrix) {
3114 tmpMatrix *= mEnhancedSaturationMatrix;
3115 }
3116 getRenderEngine().setColorTransform(tmpMatrix);
3117 } else {
3118 getRenderEngine().setColorTransform(colorMatrix);
3119 }
David Sodmanc1498e62018-09-12 14:36:26 -07003120 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003121 break;
3122 }
3123 default:
3124 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003125 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003126 } else {
3127 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003128 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003129 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003130 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003131
Peiyong Lind3788632018-09-18 16:01:31 -07003132 // Clear color transform matrix at the end of the frame.
3133 getRenderEngine().setColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003134
Mathias Agopianf45c5102012-10-24 16:29:17 -07003135 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003136 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003137 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003138}
3139
Chia-I Wu28e3a252018-09-07 12:05:02 -07003140void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003141 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003142 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003143}
3144
Dan Stoza7d89d062015-04-30 13:29:25 -07003145status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003146 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003147 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003148 const sp<Layer>& lbc,
3149 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003150{
Dan Stoza7d89d062015-04-30 13:29:25 -07003151 // add this layer to the current state list
3152 {
3153 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003154 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003155 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3156 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003157 return NO_MEMORY;
3158 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003159 if (parent == nullptr) {
3160 mCurrentState.layersSortedByZ.add(lbc);
3161 } else {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003162 if (parent->isPendingRemoval()) {
3163 ALOGE("addClientLayer called with a removed parent");
3164 return NAME_NOT_FOUND;
3165 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003166 parent->addChild(lbc);
3167 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003168
Yiwei Zhang243b3782018-05-15 17:40:04 -07003169 if (gbc != nullptr) {
3170 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3171 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3172 mMaxGraphicBufferProducerListSize,
3173 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3174 mGraphicBufferProducerList.size(),
3175 mMaxGraphicBufferProducerListSize, mNumLayers);
3176 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003177 mLayersAdded = true;
3178 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003179 }
3180
Mathias Agopian96f08192010-06-02 23:28:45 -07003181 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003182 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003183
Dan Stoza7d89d062015-04-30 13:29:25 -07003184 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003185}
3186
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003187status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003188 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003189 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3190}
Robert Carr7f9b8992017-03-10 11:08:39 -08003191
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003192status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
chaviwca27f252018-02-06 16:46:39 -08003193 bool topLevelOnly) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003194 if (layer->isPendingRemoval()) {
3195 return NO_ERROR;
3196 }
3197
Robert Carr1f0a16a2016-10-24 16:27:39 -07003198 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003199 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003200 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003201 if (topLevelOnly) {
3202 return NO_ERROR;
3203 }
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003204
3205 sp<Layer> ancestor = p;
3206 while (ancestor->getParent() != nullptr) {
3207 ancestor = ancestor->getParent();
3208 }
3209 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3210 ALOGE("removeLayer called with a layer whose parent has been removed");
3211 return NAME_NOT_FOUND;
3212 }
3213
Chia-I Wufae51c42017-06-15 12:53:59 -07003214 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003215 } else {
3216 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003217 }
3218
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003219 // As a matter of normal operation, the LayerCleaner will produce a second
3220 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3221 // so we will succeed in promoting it, but it's already been removed
3222 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3223 // otherwise something has gone wrong and we are leaking the layer.
3224 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
3225 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3226 layer->getName().string(),
3227 (p != nullptr) ? p->getName().string() : "no-parent");
3228 return BAD_VALUE;
3229 } else if (index < 0) {
3230 return NO_ERROR;
3231 }
Robert Carrf478f9f2018-10-15 12:43:33 -07003232
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003233 layer->onRemovedFromCurrentState();
3234 mLayersPendingRemoval.add(layer);
3235 mLayersRemoved = true;
3236 mNumLayers -= 1 + layer->getChildrenCount();
3237 setTransactionFlags(eTransactionNeeded);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003238 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003239}
3240
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003241uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003242 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003243}
3244
Mathias Agopian3f844832013-08-07 21:24:32 -07003245uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003246 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003247}
3248
Mathias Agopian3f844832013-08-07 21:24:32 -07003249uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003250 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003251}
3252
3253uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003254 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003255 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003256 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003257 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003258 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003259 }
3260 return old;
3261}
3262
chaviwca27f252018-02-06 16:46:39 -08003263bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3264 for (const ComposerState& state : states) {
3265 // Here we need to check that the interface we're given is indeed
3266 // one of our own. A malicious client could give us a nullptr
3267 // IInterface, or one of its own or even one of our own but a
3268 // different type. All these situations would cause us to crash.
3269 if (state.client == nullptr) {
3270 return true;
3271 }
3272
3273 sp<IBinder> binder = IInterface::asBinder(state.client);
3274 if (binder == nullptr) {
3275 return true;
3276 }
3277
3278 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3279 return true;
3280 }
3281 }
3282 return false;
3283}
3284
Mathias Agopian8b33f032012-07-24 20:43:54 -07003285void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003286 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003287 const Vector<DisplayState>& displays,
3288 uint32_t flags)
3289{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003290 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003291 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003292 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003293
chaviwca27f252018-02-06 16:46:39 -08003294 if (containsAnyInvalidClientState(states)) {
3295 return;
3296 }
3297
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003298 if (flags & eAnimation) {
3299 // For window updates that are part of an animation we must wait for
3300 // previous animation "frames" to be handled.
3301 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003302 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003303 if (CC_UNLIKELY(err != NO_ERROR)) {
3304 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003305 // caller after a few seconds.
3306 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3307 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003308 mAnimTransactionPending = false;
3309 break;
3310 }
3311 }
3312 }
3313
chaviwca27f252018-02-06 16:46:39 -08003314 for (const DisplayState& display : displays) {
3315 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003316 }
3317
chaviwca27f252018-02-06 16:46:39 -08003318 for (const ComposerState& state : states) {
3319 transactionFlags |= setClientStateLocked(state);
3320 }
3321
3322 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3323 // as destroyed should only occur after setting all other states. This is to allow for a
3324 // child re-parent to happen before marking its original parent as destroyed (which would
3325 // then mark the child as destroyed).
3326 for (const ComposerState& state : states) {
3327 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003328 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003329
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003330 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3331 // anyway. This can be used as a flush mechanism for previous async transactions.
3332 // Empty animation transaction can be used to simulate back-pressure, so also force a
3333 // transaction for empty animation transactions.
3334 if (transactionFlags == 0 &&
3335 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003336 transactionFlags = eTransactionNeeded;
3337 }
3338
Mathias Agopian386aa982011-11-07 21:58:03 -08003339 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003340 if (mInterceptor->isEnabled()) {
3341 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003342 }
Irvel468051e2016-06-13 16:44:44 -07003343
Mathias Agopian386aa982011-11-07 21:58:03 -08003344 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003345 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3346 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003347 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003348
3349 // if this is a synchronous transaction, wait for it to take effect
3350 // before returning.
3351 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003352 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003353 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003354 if (flags & eAnimation) {
3355 mAnimTransactionPending = true;
3356 }
3357 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003358 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3359 if (CC_UNLIKELY(err != NO_ERROR)) {
3360 // just in case something goes wrong in SF, return to the
3361 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003362 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3363 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003364 break;
3365 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003366 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003367 }
3368}
3369
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003370uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3371 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3372 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003373
Mathias Agopiane57f2922012-08-09 16:29:12 -07003374 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003375 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3376
3377 const uint32_t what = s.what;
3378 if (what & DisplayState::eSurfaceChanged) {
3379 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3380 state.surface = s.surface;
3381 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003382 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003383 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003384 if (what & DisplayState::eLayerStackChanged) {
3385 if (state.layerStack != s.layerStack) {
3386 state.layerStack = s.layerStack;
3387 flags |= eDisplayTransactionNeeded;
3388 }
3389 }
3390 if (what & DisplayState::eDisplayProjectionChanged) {
3391 if (state.orientation != s.orientation) {
3392 state.orientation = s.orientation;
3393 flags |= eDisplayTransactionNeeded;
3394 }
3395 if (state.frame != s.frame) {
3396 state.frame = s.frame;
3397 flags |= eDisplayTransactionNeeded;
3398 }
3399 if (state.viewport != s.viewport) {
3400 state.viewport = s.viewport;
3401 flags |= eDisplayTransactionNeeded;
3402 }
3403 }
3404 if (what & DisplayState::eDisplaySizeChanged) {
3405 if (state.width != s.width) {
3406 state.width = s.width;
3407 flags |= eDisplayTransactionNeeded;
3408 }
3409 if (state.height != s.height) {
3410 state.height = s.height;
3411 flags |= eDisplayTransactionNeeded;
3412 }
3413 }
3414
Mathias Agopiane57f2922012-08-09 16:29:12 -07003415 return flags;
3416}
3417
Robert Carrd4ae7f32018-06-07 16:10:57 -07003418bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3419 IPCThreadState* ipc = IPCThreadState::self();
3420 const int pid = ipc->getCallingPid();
3421 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003422 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003423 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003424 return false;
3425 }
3426 return true;
3427}
3428
chaviwca27f252018-02-06 16:46:39 -08003429uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3430 const layer_state_t& s = composerState.state;
3431 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3432
Mathias Agopian13127d82013-03-05 17:47:11 -08003433 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003434 if (layer == nullptr) {
3435 return 0;
3436 }
3437
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003438 if (layer->isPendingRemoval()) {
3439 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3440 return 0;
3441 }
3442
chaviw8b3871a2017-11-01 17:41:01 -07003443 uint32_t flags = 0;
3444
3445 const uint32_t what = s.what;
3446 bool geometryAppliesWithResize =
3447 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003448
3449 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3450 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003451 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003452 layer->pushPendingState();
3453 }
3454
chaviw8b3871a2017-11-01 17:41:01 -07003455 if (what & layer_state_t::ePositionChanged) {
3456 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3457 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003458 }
chaviw8b3871a2017-11-01 17:41:01 -07003459 }
3460 if (what & layer_state_t::eLayerChanged) {
3461 // NOTE: index needs to be calculated before we update the state
3462 const auto& p = layer->getParent();
3463 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003464 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003465 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003466 mCurrentState.layersSortedByZ.removeAt(idx);
3467 mCurrentState.layersSortedByZ.add(layer);
3468 // we need traversal (state changed)
3469 // AND transaction (list changed)
3470 flags |= eTransactionNeeded|eTraversalNeeded;
3471 }
chaviw8b3871a2017-11-01 17:41:01 -07003472 } else {
3473 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003474 flags |= eTransactionNeeded|eTraversalNeeded;
3475 }
3476 }
chaviw8b3871a2017-11-01 17:41:01 -07003477 }
3478 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003479 // NOTE: index needs to be calculated before we update the state
3480 const auto& p = layer->getParent();
3481 if (p == nullptr) {
3482 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3483 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3484 mCurrentState.layersSortedByZ.removeAt(idx);
3485 mCurrentState.layersSortedByZ.add(layer);
3486 // we need traversal (state changed)
3487 // AND transaction (list changed)
3488 flags |= eTransactionNeeded|eTraversalNeeded;
3489 }
3490 } else {
3491 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3492 flags |= eTransactionNeeded|eTraversalNeeded;
3493 }
chaviw8b3871a2017-11-01 17:41:01 -07003494 }
3495 }
3496 if (what & layer_state_t::eSizeChanged) {
3497 if (layer->setSize(s.w, s.h)) {
3498 flags |= eTraversalNeeded;
3499 }
3500 }
3501 if (what & layer_state_t::eAlphaChanged) {
3502 if (layer->setAlpha(s.alpha))
3503 flags |= eTraversalNeeded;
3504 }
3505 if (what & layer_state_t::eColorChanged) {
3506 if (layer->setColor(s.color))
3507 flags |= eTraversalNeeded;
3508 }
Peiyong Lind3788632018-09-18 16:01:31 -07003509 if (what & layer_state_t::eColorTransformChanged) {
3510 if (layer->setColorTransform(s.colorTransform)) {
3511 flags |= eTraversalNeeded;
3512 }
3513 }
chaviw8b3871a2017-11-01 17:41:01 -07003514 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003515 // TODO: b/109894387
3516 //
3517 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3518 // rotation. To see the problem observe that if we have a square parent, and a child
3519 // of the same size, then we rotate the child 45 degrees around it's center, the child
3520 // must now be cropped to a non rectangular 8 sided region.
3521 //
3522 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3523 // private API, and the WindowManager only uses rotation in one case, which is on a top
3524 // level layer in which cropping is not an issue.
3525 //
3526 // However given that abuse of rotation matrices could lead to surfaces extending outside
3527 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3528 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3529 // transformations.
3530 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003531 flags |= eTraversalNeeded;
3532 }
3533 if (what & layer_state_t::eTransparentRegionChanged) {
3534 if (layer->setTransparentRegionHint(s.transparentRegion))
3535 flags |= eTraversalNeeded;
3536 }
3537 if (what & layer_state_t::eFlagsChanged) {
3538 if (layer->setFlags(s.flags, s.mask))
3539 flags |= eTraversalNeeded;
3540 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003541 if (what & layer_state_t::eCropChanged_legacy) {
3542 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003543 flags |= eTraversalNeeded;
3544 }
chaviw8b3871a2017-11-01 17:41:01 -07003545 if (what & layer_state_t::eLayerStackChanged) {
3546 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3547 // We only allow setting layer stacks for top level layers,
3548 // everything else inherits layer stack from its parent.
3549 if (layer->hasParent()) {
3550 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3551 layer->getName().string());
3552 } else if (idx < 0) {
3553 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3554 "that also does not appear in the top level layer list. Something"
3555 " has gone wrong.", layer->getName().string());
3556 } else if (layer->setLayerStack(s.layerStack)) {
3557 mCurrentState.layersSortedByZ.removeAt(idx);
3558 mCurrentState.layersSortedByZ.add(layer);
3559 // we need traversal (state changed)
3560 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003561 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003562 }
3563 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003564 if (what & layer_state_t::eDeferTransaction_legacy) {
3565 if (s.barrierHandle_legacy != nullptr) {
3566 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3567 } else if (s.barrierGbp_legacy != nullptr) {
3568 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003569 if (authenticateSurfaceTextureLocked(gbp)) {
3570 const auto& otherLayer =
3571 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003572 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003573 } else {
3574 ALOGE("Attempt to defer transaction to to an"
3575 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003576 }
3577 }
chaviw8b3871a2017-11-01 17:41:01 -07003578 // We don't trigger a traversal here because if no other state is
3579 // changed, we don't want this to cause any more work
3580 }
3581 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003582 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003583 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003584 if (!hadParent) {
3585 mCurrentState.layersSortedByZ.remove(layer);
3586 }
chaviw8b3871a2017-11-01 17:41:01 -07003587 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003588 }
chaviw8b3871a2017-11-01 17:41:01 -07003589 }
3590 if (what & layer_state_t::eReparentChildren) {
3591 if (layer->reparentChildren(s.reparentHandle)) {
3592 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003593 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003594 }
chaviw8b3871a2017-11-01 17:41:01 -07003595 if (what & layer_state_t::eDetachChildren) {
3596 layer->detachChildren();
3597 }
3598 if (what & layer_state_t::eOverrideScalingModeChanged) {
3599 layer->setOverrideScalingMode(s.overrideScalingMode);
3600 // We don't trigger a traversal here because if no other state is
3601 // changed, we don't want this to cause any more work
3602 }
Marissa Wall61c58622018-07-18 10:12:20 -07003603 if (what & layer_state_t::eTransformChanged) {
3604 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3605 }
3606 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3607 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3608 flags |= eTraversalNeeded;
3609 }
3610 if (what & layer_state_t::eCropChanged) {
3611 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3612 }
3613 if (what & layer_state_t::eBufferChanged) {
3614 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3615 }
3616 if (what & layer_state_t::eAcquireFenceChanged) {
3617 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3618 }
3619 if (what & layer_state_t::eDataspaceChanged) {
3620 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3621 }
3622 if (what & layer_state_t::eHdrMetadataChanged) {
3623 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3624 }
3625 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3626 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3627 }
3628 if (what & layer_state_t::eApiChanged) {
3629 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3630 }
3631 if (what & layer_state_t::eSidebandStreamChanged) {
3632 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3633 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003634 return flags;
3635}
3636
chaviwca27f252018-02-06 16:46:39 -08003637void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3638 const layer_state_t& state = composerState.state;
3639 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3640
3641 sp<Layer> layer(client->getLayerUser(state.surface));
3642 if (layer == nullptr) {
3643 return;
3644 }
3645
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003646 if (layer->isPendingRemoval()) {
3647 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3648 return;
3649 }
3650
chaviwca27f252018-02-06 16:46:39 -08003651 if (state.what & layer_state_t::eDestroySurface) {
3652 removeLayerLocked(mStateLock, layer);
3653 }
3654}
3655
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003656status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003657 const String8& name,
3658 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003659 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003660 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003661 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003662{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003663 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003664 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003665 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003666 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003667 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003668
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003669 status_t result = NO_ERROR;
3670
3671 sp<Layer> layer;
3672
Cody Northropbc755282017-03-31 12:00:08 -06003673 String8 uniqueName = getUniqueLayerName(name);
3674
Mathias Agopian3165cc22012-08-08 19:42:09 -07003675 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003676 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003677 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3678 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003679
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003680 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003681 case ISurfaceComposerClient::eFXSurfaceBufferState:
3682 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3683 break;
chaviw13fdc492017-06-27 12:40:18 -07003684 case ISurfaceComposerClient::eFXSurfaceColor:
3685 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003686 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003687 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003688 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003689 case ISurfaceComposerClient::eFXSurfaceContainer:
3690 result = createContainerLayer(client,
3691 uniqueName, w, h, flags,
3692 handle, &layer);
3693 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003694 default:
3695 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003696 break;
3697 }
3698
Dan Stoza7d89d062015-04-30 13:29:25 -07003699 if (result != NO_ERROR) {
3700 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003701 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003702
Chia-I Wuab0c3192017-08-01 11:29:00 -07003703 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3704 // TODO b/64227542
3705 if (windowType == 441731) {
3706 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3707 layer->setPrimaryDisplayOnly();
3708 }
3709
Albert Chaulk479c60c2017-01-27 14:21:34 -05003710 layer->setInfo(windowType, ownerUid);
3711
Robert Carr1f0a16a2016-10-24 16:27:39 -07003712 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003713 if (result != NO_ERROR) {
3714 return result;
3715 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003716 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003717
3718 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003719 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003720}
3721
Cody Northropbc755282017-03-31 12:00:08 -06003722String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3723{
3724 bool matchFound = true;
3725 uint32_t dupeCounter = 0;
3726
3727 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3728 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3729
Dan Stoza436ccf32018-06-21 12:10:12 -07003730 // Grab the state lock since we're accessing mCurrentState
3731 Mutex::Autolock lock(mStateLock);
3732
Cody Northropbc755282017-03-31 12:00:08 -06003733 // Loop over layers until we're sure there is no matching name
3734 while (matchFound) {
3735 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003736 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003737 if (layer->getName() == uniqueName) {
3738 matchFound = true;
3739 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3740 }
3741 });
3742 }
3743
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003744 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3745 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003746
3747 return uniqueName;
3748}
3749
Marissa Wallfd668622018-05-10 10:21:13 -07003750status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3751 uint32_t w, uint32_t h, uint32_t flags,
3752 PixelFormat& format, sp<IBinder>* handle,
3753 sp<IGraphicBufferProducer>* gbp,
3754 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003755 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003756 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003757 case PIXEL_FORMAT_TRANSPARENT:
3758 case PIXEL_FORMAT_TRANSLUCENT:
3759 format = PIXEL_FORMAT_RGBA_8888;
3760 break;
3761 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003762 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003763 break;
3764 }
3765
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003766 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003767 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003768 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003769 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003770 *handle = layer->getHandle();
3771 *gbp = layer->getProducer();
3772 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003773 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003774
Marissa Wallfd668622018-05-10 10:21:13 -07003775 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003776 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003777}
3778
Marissa Wall61c58622018-07-18 10:12:20 -07003779status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3780 uint32_t w, uint32_t h, uint32_t flags,
3781 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003782 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003783 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003784 *handle = layer->getHandle();
3785 *outLayer = layer;
3786
3787 return NO_ERROR;
3788}
3789
chaviw13fdc492017-06-27 12:40:18 -07003790status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003791 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003792 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003793{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003794 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003795 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003796 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003797}
3798
Robert Carr6b3f6c52018-08-13 13:05:17 -07003799status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3800 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3801 sp<IBinder>* handle, sp<Layer>* outLayer)
3802{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003803 *outLayer =
3804 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003805 *handle = (*outLayer)->getHandle();
3806 return NO_ERROR;
3807}
3808
3809
Mathias Agopianac9fa422013-02-11 16:40:36 -08003810status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003811{
Robert Carr9524cb32017-02-13 11:32:32 -08003812 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003813 status_t err = NO_ERROR;
3814 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003815 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003816 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003817 err = removeLayer(l);
3818 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3819 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003820 }
3821 return err;
3822}
3823
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003824status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003825{
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003826 // called by ~LayerCleaner() when all references to the IBinder (handle)
3827 // are gone
3828 sp<Layer> l = layer.promote();
3829 if (l == nullptr) {
3830 // The layer has already been removed, carry on
3831 return NO_ERROR;
3832 }
3833 // If we have a parent, then we can continue to live as long as it does.
3834 return removeLayer(l, true);
Rob Carr4bba3702018-10-08 21:53:30 +00003835}
3836
Mathias Agopianb60314a2012-04-10 22:09:54 -07003837// ---------------------------------------------------------------------------
3838
Andy McFadden13a082e2012-08-24 10:16:42 -07003839void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003840 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3841 if (!displayToken) return;
3842
Jesse Hall01e29052013-02-19 16:13:35 -08003843 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003844 Vector<ComposerState> state;
3845 Vector<DisplayState> displays;
3846 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003847 d.what = DisplayState::eDisplayProjectionChanged |
3848 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003849 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003850 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003851 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003852 d.frame.makeInvalid();
3853 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003854 d.width = 0;
3855 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003856 displays.add(d);
3857 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003858
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003859 const auto display = getDisplayDevice(displayToken);
3860 if (!display) return;
3861
3862 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3863
3864 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003865 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003866 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003867
Brian Andersond0010582017-03-07 13:20:31 -08003868 // Use phase of 0 since phase is not known.
3869 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07003870 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
3871 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003872}
3873
3874void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003875 // Async since we may be called from the main thread.
3876 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003877}
3878
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003879void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3880 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003881 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003882 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003883
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003884 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003885 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003886 return;
3887 }
3888
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003889 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003890 ALOGW("Trying to set power mode for virtual display");
3891 return;
3892 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003893
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003894 display->setPowerMode(mode);
3895
Lloyd Pique4dccc412018-01-22 17:21:36 -08003896 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003897 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003898 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003899 if (idx < 0) {
3900 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3901 return;
3902 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003903 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003904 }
3905
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003906 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003907 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003908 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003909 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003910 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003911 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003912 if (mUseScheduler) {
3913 mScheduler->onScreenAcquired(mAppConnectionHandle);
3914 } else {
3915 mEventThread->onScreenAcquired();
3916 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07003917 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003918 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003919
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003920 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003921 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003922 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003923
3924 struct sched_param param = {0};
3925 param.sched_priority = 1;
3926 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3927 ALOGW("Couldn't set SCHED_FIFO on display on");
3928 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003929 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003930 // Turn off the display
3931 struct sched_param param = {0};
3932 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3933 ALOGW("Couldn't set SCHED_OTHER on display off");
3934 }
3935
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003936 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07003937 if (mUseScheduler) {
3938 mScheduler->disableHardwareVsync(true);
3939 } else {
3940 disableHardwareVsync(true); // also cancels any in-progress resync
3941 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07003942 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003943 if (mUseScheduler) {
3944 mScheduler->onScreenReleased(mAppConnectionHandle);
3945 } else {
3946 mEventThread->onScreenReleased();
3947 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07003948 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003949
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003950 getHwComposer().setPowerMode(type, mode);
3951 mVisibleRegionsDirty = true;
3952 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003953 } else if (mode == HWC_POWER_MODE_DOZE ||
3954 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003955 // Update display while dozing
3956 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003957 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003958 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003959 if (mUseScheduler) {
3960 mScheduler->onScreenAcquired(mAppConnectionHandle);
3961 } else {
3962 mEventThread->onScreenAcquired();
3963 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003964 resyncToHardwareVsync(true);
3965 }
3966 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3967 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003968 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07003969 if (mUseScheduler) {
3970 mScheduler->disableHardwareVsync(true);
3971 } else {
3972 disableHardwareVsync(true); // also cancels any in-progress resync
3973 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003974 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07003975 if (mUseScheduler) {
3976 mScheduler->onScreenReleased(mAppConnectionHandle);
3977 } else {
3978 mEventThread->onScreenReleased();
3979 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003980 }
3981 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003982 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003983 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003984 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003985 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003986
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003987 if (display->isPrimary()) {
3988 mTimeStats.setPowerMode(mode);
3989 }
3990
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003991 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003992}
3993
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003994void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003995 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003996 const auto display = getDisplayDevice(displayToken);
3997 if (!display) {
3998 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3999 displayToken.get());
4000 } else if (display->isVirtual()) {
4001 ALOGW("Attempt to set power mode %d for virtual display", mode);
4002 } else {
4003 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004004 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004005 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004006}
4007
4008// ---------------------------------------------------------------------------
4009
Lloyd Pique755e3192018-01-31 16:46:15 -08004010status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4011 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004012 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004013
Mathias Agopianbd115332013-04-18 16:41:04 -07004014 IPCThreadState* ipc = IPCThreadState::self();
4015 const int pid = ipc->getCallingPid();
4016 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004017
Mathias Agopianbd115332013-04-18 16:41:04 -07004018 if ((uid != AID_SHELL) &&
4019 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004020 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004021 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004022 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004023 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004024 // (this would indicate SF is stuck, but we want to be able to
4025 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004026 status_t err = mStateLock.timedLock(s2ns(1));
4027 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004028 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004029 result.appendFormat(
4030 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4031 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004032 }
4033
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004034 bool dumpAll = true;
4035 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004036 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004037
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004038 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004039 if ((index < numArgs) &&
4040 (args[index] == String16("--list"))) {
4041 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004042 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004043 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004044 }
4045
4046 if ((index < numArgs) &&
4047 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004048 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004049 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004050 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004051 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004052
4053 if ((index < numArgs) &&
4054 (args[index] == String16("--latency-clear"))) {
4055 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004056 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004057 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004058 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004059
4060 if ((index < numArgs) &&
4061 (args[index] == String16("--dispsync"))) {
4062 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004063 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004064 dumpAll = false;
4065 }
Dan Stozab90cf072015-03-05 11:05:59 -08004066
4067 if ((index < numArgs) &&
4068 (args[index] == String16("--static-screen"))) {
4069 index++;
4070 dumpStaticScreenStats(result);
4071 dumpAll = false;
4072 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004073
4074 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004075 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004076 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004077 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004078 dumpAll = false;
4079 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004080
4081 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4082 index++;
4083 dumpWideColorInfo(result);
4084 dumpAll = false;
4085 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004086
4087 if ((index < numArgs) &&
4088 (args[index] == String16("--enable-layer-stats"))) {
4089 index++;
4090 mLayerStats.enable();
4091 dumpAll = false;
4092 }
4093
4094 if ((index < numArgs) &&
4095 (args[index] == String16("--disable-layer-stats"))) {
4096 index++;
4097 mLayerStats.disable();
4098 dumpAll = false;
4099 }
4100
4101 if ((index < numArgs) &&
4102 (args[index] == String16("--clear-layer-stats"))) {
4103 index++;
4104 mLayerStats.clear();
4105 dumpAll = false;
4106 }
4107
4108 if ((index < numArgs) &&
4109 (args[index] == String16("--dump-layer-stats"))) {
4110 index++;
4111 mLayerStats.dump(result);
4112 dumpAll = false;
4113 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004114
4115 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004116 (args[index] == String16("--frame-composition"))) {
4117 index++;
4118 dumpFrameCompositionInfo(result);
4119 dumpAll = false;
4120 }
4121
4122 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004123 (args[index] == String16("--display-identification"))) {
4124 index++;
4125 dumpDisplayIdentificationData(result);
4126 dumpAll = false;
4127 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004128
4129 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4130 index++;
4131 mTimeStats.parseArgs(asProto, args, index, result);
4132 dumpAll = false;
4133 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004134 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004135
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004136 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004137 if (asProto) {
4138 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4139 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4140 } else {
4141 dumpAllLocked(args, index, result);
4142 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004143 }
4144
Mathias Agopian9795c422009-08-26 16:36:26 -07004145 if (locked) {
4146 mStateLock.unlock();
4147 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004148 }
4149 write(fd, result.string(), result.size());
4150 return NO_ERROR;
4151}
4152
Dan Stozac7014012014-02-14 15:03:43 -08004153void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4154 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004155{
Robert Carr2047fae2016-11-28 14:09:09 -08004156 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004157 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004158 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004159}
4160
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004161void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004162 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004163{
4164 String8 name;
4165 if (index < args.size()) {
4166 name = String8(args[index]);
4167 index++;
4168 }
4169
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004170 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4171 getHwComposer().isConnected(displayId)) {
4172 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4173 const nsecs_t period = activeConfig->getVsyncPeriod();
4174 result.appendFormat("%" PRId64 "\n", period);
4175 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004176
4177 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004178 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004179 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004180 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004181 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004182 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004183 }
Robert Carr2047fae2016-11-28 14:09:09 -08004184 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004185 }
4186}
4187
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004188void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004189 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004190{
4191 String8 name;
4192 if (index < args.size()) {
4193 name = String8(args[index]);
4194 index++;
4195 }
4196
Robert Carr2047fae2016-11-28 14:09:09 -08004197 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004198 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004199 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004200 }
Robert Carr2047fae2016-11-28 14:09:09 -08004201 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004202
Svetoslavd85084b2014-03-20 10:28:31 -07004203 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004204}
4205
Jamie Gennis6547ff42013-07-16 20:12:42 -07004206// This should only be called from the main thread. Otherwise it would need
4207// the lock and should use mCurrentState rather than mDrawingState.
4208void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004209 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004210 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004211 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004212
4213 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4214}
4215
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004216void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004217{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004218 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004219
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004220 if (isLayerTripleBufferingDisabled())
4221 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004222
4223 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004224 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004225 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004226 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004227 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4228 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004229 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004230}
4231
Dan Stozab90cf072015-03-05 11:05:59 -08004232void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4233{
4234 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004235 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4236 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004237 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004238 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004239 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4240 b + 1, bucketTimeSec, percent);
4241 }
David Sodman4a36e932017-11-07 14:29:47 -08004242 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004243 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004244 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004245 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004246 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004247}
4248
Dan Stozae77c7662016-05-13 11:37:28 -07004249void SurfaceFlinger::recordBufferingStats(const char* layerName,
4250 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004251 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4252 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004253 for (const auto& segment : history) {
4254 if (!segment.usedThirdBuffer) {
4255 stats.twoBufferTime += segment.totalTime;
4256 }
4257 if (segment.occupancyAverage < 1.0f) {
4258 stats.doubleBufferedTime += segment.totalTime;
4259 } else if (segment.occupancyAverage < 2.0f) {
4260 stats.tripleBufferedTime += segment.totalTime;
4261 }
4262 ++stats.numSegments;
4263 stats.totalTime += segment.totalTime;
4264 }
4265}
4266
Brian Andersond6927fb2016-07-23 23:37:30 -07004267void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4268 result.appendFormat("Layer frame timestamps:\n");
4269
4270 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4271 const size_t count = currentLayers.size();
4272 for (size_t i=0 ; i<count ; i++) {
4273 currentLayers[i]->dumpFrameEvents(result);
4274 }
4275}
4276
Dan Stozae77c7662016-05-13 11:37:28 -07004277void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4278 result.append("Buffering stats:\n");
4279 result.append(" [Layer name] <Active time> <Two buffer> "
4280 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004281 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004282 typedef std::tuple<std::string, float, float, float> BufferTuple;
4283 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004284 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004285 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004286 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004287 if (stats.numSegments == 0) {
4288 continue;
4289 }
4290 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4291 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4292 stats.totalTime;
4293 float doubleBufferRatio = static_cast<float>(
4294 stats.doubleBufferedTime) / stats.totalTime;
4295 float tripleBufferRatio = static_cast<float>(
4296 stats.tripleBufferedTime) / stats.totalTime;
4297 sorted.insert({activeTime, {name, twoBufferRatio,
4298 doubleBufferRatio, tripleBufferRatio}});
4299 }
4300 for (const auto& sortedPair : sorted) {
4301 float activeTime = sortedPair.first;
4302 const BufferTuple& values = sortedPair.second;
4303 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4304 std::get<0>(values).c_str(), activeTime,
4305 std::get<1>(values), std::get<2>(values),
4306 std::get<3>(values));
4307 }
4308 result.append("\n");
4309}
4310
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004311void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004312 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004313 const int32_t displayId = display->getId();
4314 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4315 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004316 continue;
4317 }
4318
Dominik Laskowski7e045462018-05-30 13:02:02 -07004319 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004320 uint8_t port;
4321 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004322 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004323 result.append("no identification data\n");
4324 continue;
4325 }
4326
4327 if (!isEdid(data)) {
4328 result.append("unknown identification data: ");
4329 for (uint8_t byte : data) {
4330 result.appendFormat("%x ", byte);
4331 }
4332 result.append("\n");
4333 continue;
4334 }
4335
4336 const auto edid = parseEdid(data);
4337 if (!edid) {
4338 result.append("invalid EDID: ");
4339 for (uint8_t byte : data) {
4340 result.appendFormat("%x ", byte);
4341 }
4342 result.append("\n");
4343 continue;
4344 }
4345
4346 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4347 result.append(edid->displayName.data(), edid->displayName.length());
4348 result.append("\"\n");
4349 }
4350 result.append("\n");
4351}
4352
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004353void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004354 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4355 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004356 result.appendFormat("DisplayColorSetting: %s\n",
4357 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004358
4359 // TODO: print out if wide-color mode is active or not
4360
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004361 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004362 const int32_t displayId = display->getId();
4363 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004364 continue;
4365 }
4366
Dominik Laskowski7e045462018-05-30 13:02:02 -07004367 result.appendFormat("Display %d color modes:\n", displayId);
4368 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004369 for (auto&& mode : modes) {
4370 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4371 }
4372
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004373 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004374 result.appendFormat(" Current color mode: %s (%d)\n",
4375 decodeColorMode(currentMode).c_str(), currentMode);
4376 }
4377 result.append("\n");
4378}
4379
David Sodman7e4ae112018-02-09 15:02:28 -08004380void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4381 std::string stringResult;
4382
4383 for (const auto& [token, display] : mDisplays) {
4384 const auto displayId = display->getId();
4385 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
4386 continue;
4387 }
4388
4389 const auto& compositionInfoIt = getBE().mEndOfFrameCompositionInfo.find(displayId);
4390 if (compositionInfoIt == getBE().mEndOfFrameCompositionInfo.end()) {
4391 break;
4392 }
4393 const auto& compositionInfoList = compositionInfoIt->second;
4394 stringResult += base::StringPrintf("Display: %d\n", displayId);
4395 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4396 for (const auto& compositionInfo : compositionInfoList) {
4397 compositionInfo.dump(stringResult, nullptr);
4398 stringResult += base::StringPrintf("\n");
4399 }
4400 }
4401
4402 result.append(stringResult.c_str());
4403}
4404
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004405LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004406 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004407 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4408 const State& state = useDrawing ? mDrawingState : mCurrentState;
4409 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004410 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004411 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004412 });
4413
4414 return layersProto;
4415}
4416
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004417LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004418 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004419
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004420 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004421 resolution->set_w(display.getWidth());
4422 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004423
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004424 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4425 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4426 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004427
Dominik Laskowski7e045462018-05-30 13:02:02 -07004428 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004429 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004430 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004431 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004432 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004433 }
4434 });
4435
4436 return layersProto;
4437}
4438
Mathias Agopian74d211a2013-04-22 16:55:35 +02004439void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4440 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004441{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004442 bool colorize = false;
4443 if (index < args.size()
4444 && (args[index] == String16("--color"))) {
4445 colorize = true;
4446 index++;
4447 }
4448
4449 Colorizer colorizer(colorize);
4450
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004451 // figure out if we're stuck somewhere
4452 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004453 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004454 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4455
4456 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004457 * Dump library configuration.
4458 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004459
4460 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004461 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004462 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004463 appendSfConfigString(result);
4464 appendUiConfigString(result);
4465 appendGuiConfigString(result);
4466 result.append("\n");
4467
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004468 result.append("\nDisplay identification data:\n");
4469 dumpDisplayIdentificationData(result);
4470
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004471 result.append("\nWide-Color information:\n");
4472 dumpWideColorInfo(result);
4473
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004474 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004475 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004476 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004477 result.append(SyncFeatures::getInstance().toString());
4478 result.append("\n");
4479
Andy McFadden41d67d72014-04-25 16:58:34 -07004480 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004481 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004482 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004483
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004484 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4485 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004486 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4487 getHwComposer().isConnected(displayId)) {
4488 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004489 result.appendFormat("Display %d: "
4490 "app phase %" PRId64 " ns, "
4491 "sf phase %" PRId64 " ns, "
4492 "early app phase %" PRId64 " ns, "
4493 "early sf phase %" PRId64 " ns, "
4494 "early app gl phase %" PRId64 " ns, "
4495 "early sf gl phase %" PRId64 " ns, "
4496 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4497 displayId,
4498 vsyncPhaseOffsetNs,
4499 sfVsyncPhaseOffsetNs,
4500 appEarlyOffset,
4501 sfEarlyOffset,
4502 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004503 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004504 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004505 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004506 result.append("\n");
4507
Dan Stozab90cf072015-03-05 11:05:59 -08004508 // Dump static screen stats
4509 result.append("\n");
4510 dumpStaticScreenStats(result);
4511 result.append("\n");
4512
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004513 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4514
Dan Stozae77c7662016-05-13 11:37:28 -07004515 dumpBufferingStats(result);
4516
Andy McFadden4803b742012-09-24 19:07:20 -07004517 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004518 * Dump the visible layer list
4519 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004520 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004521 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004522 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4523 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004524 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004525
Chia-I Wu2f884132018-09-13 15:17:58 -07004526 {
4527 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4528 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4529 result.append(LayerProtoParser::layerTreeToString(layerTree).c_str());
4530 result.append("\n");
4531 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004532
David Sodman7e4ae112018-02-09 15:02:28 -08004533 result.append("\nFrame-Composition information:\n");
4534 dumpFrameCompositionInfo(result);
4535 result.append("\n");
4536
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004537 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004538 * Dump Display state
4539 */
4540
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004541 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004542 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004543 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004544 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004545 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004546 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004547 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004548
4549 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004550 * Dump SurfaceFlinger global state
4551 */
4552
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004553 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004554 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004555 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004556
Mathias Agopian888c8222012-08-04 21:10:38 -07004557 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004558 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004559
David Sodmanbc815282017-11-05 18:57:52 -08004560 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004561
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004562 if (display) {
4563 display->undefinedRegion.dump(result, "undefinedRegion");
4564 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4565 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004566 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004567 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004568 " gpu_to_cpu_unsupported : %d\n",
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004569 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004570
4571 if (display) {
4572 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4573 result.appendFormat(" refresh-rate : %f fps\n"
4574 " x-dpi : %f\n"
4575 " y-dpi : %f\n",
4576 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4577 activeConfig->getDpiY());
4578 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004579
Mathias Agopian74d211a2013-04-22 16:55:35 +02004580 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004581 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004582
Ana Krulec98b5b242018-08-10 15:03:23 -07004583 result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004584 /*
4585 * VSYNC state
4586 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004587 if (mUseScheduler) {
4588 mScheduler->dump(mAppConnectionHandle, result);
4589 } else {
4590 mEventThread->dump(result);
4591 }
Dan Stozae22aec72016-08-01 13:20:59 -07004592 result.append("\n");
4593
4594 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004595 * Tracing state
4596 */
4597 mTracing.dump(result);
4598 result.append("\n");
4599
4600 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004601 * HWC layer minidump
4602 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004603 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004604 const int32_t displayId = display->getId();
4605 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004606 continue;
4607 }
4608
Dominik Laskowski7e045462018-05-30 13:02:02 -07004609 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004610 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004611 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004612 result.append("\n");
4613 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004614
4615 /*
4616 * Dump HWComposer state
4617 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004618 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004619 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004620 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004621 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004622 result.appendFormat(" h/w composer %s\n",
4623 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004624 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004625
4626 /*
4627 * Dump gralloc state
4628 */
4629 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4630 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004631
4632 /*
4633 * Dump VrFlinger state if in use.
4634 */
4635 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4636 result.append("VrFlinger state:\n");
4637 result.append(mVrFlinger->Dump().c_str());
4638 result.append("\n");
4639 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004640}
4641
Dominik Laskowski7e045462018-05-30 13:02:02 -07004642const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004643 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004644 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004645 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004646 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004647 }
4648 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004649
4650 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4651 static const Vector<sp<Layer>> empty;
4652 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004653}
4654
Keun young Park63f165f2012-08-31 10:53:36 -07004655bool SurfaceFlinger::startDdmConnection()
4656{
4657 void* libddmconnection_dso =
4658 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4659 if (!libddmconnection_dso) {
4660 return false;
4661 }
4662 void (*DdmConnection_start)(const char* name);
4663 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004664 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004665 if (!DdmConnection_start) {
4666 dlclose(libddmconnection_dso);
4667 return false;
4668 }
4669 (*DdmConnection_start)(getServiceName());
4670 return true;
4671}
4672
Chia-I Wu28f320b2018-05-03 11:02:56 -07004673void SurfaceFlinger::updateColorMatrixLocked() {
4674 mat4 colorMatrix;
4675 if (mGlobalSaturationFactor != 1.0f) {
4676 // Rec.709 luma coefficients
4677 float3 luminance{0.213f, 0.715f, 0.072f};
4678 luminance *= 1.0f - mGlobalSaturationFactor;
4679 mat4 saturationMatrix = mat4(
4680 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4681 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4682 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4683 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4684 );
4685 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4686 } else {
4687 colorMatrix = mClientColorMatrix * mDaltonizer();
4688 }
4689
4690 if (mCurrentState.colorMatrix != colorMatrix) {
4691 mCurrentState.colorMatrix = colorMatrix;
4692 mCurrentState.colorMatrixChanged = true;
4693 setTransactionFlags(eTransactionNeeded);
4694 }
4695}
4696
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004697status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004698#pragma clang diagnostic push
4699#pragma clang diagnostic error "-Wswitch-enum"
4700 switch (static_cast<ISurfaceComposerTag>(code)) {
4701 // These methods should at minimum make sure that the client requested
4702 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004703 case BOOT_FINISHED:
4704 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004705 case CREATE_CONNECTION:
4706 case CREATE_DISPLAY:
4707 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004708 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004709 case GET_ACTIVE_COLOR_MODE:
4710 case GET_ANIMATION_FRAME_STATS:
4711 case GET_HDR_CAPABILITIES:
4712 case SET_ACTIVE_CONFIG:
4713 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004714 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004715 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004716 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4717 IPCThreadState* ipc = IPCThreadState::self();
4718 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4719 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004720 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004721 }
Robert Carr1db73f62016-12-21 12:58:51 -08004722 return OK;
4723 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004724 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004725 IPCThreadState* ipc = IPCThreadState::self();
4726 const int pid = ipc->getCallingPid();
4727 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004728 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4729 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004730 return PERMISSION_DENIED;
4731 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004732 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004733 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004734 // Used by apps to hook Choreographer to SurfaceFlinger.
4735 case CREATE_DISPLAY_EVENT_CONNECTION:
4736 // The following calls are currently used by clients that do not
4737 // request necessary permissions. However, they do not expose any secret
4738 // information, so it is OK to pass them.
4739 case AUTHENTICATE_SURFACE:
4740 case GET_ACTIVE_CONFIG:
4741 case GET_BUILT_IN_DISPLAY:
4742 case GET_DISPLAY_COLOR_MODES:
4743 case GET_DISPLAY_CONFIGS:
4744 case GET_DISPLAY_STATS:
4745 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4746 // Calling setTransactionState is safe, because you need to have been
4747 // granted a reference to Client* and Handle* to do anything with it.
4748 case SET_TRANSACTION_STATE:
4749 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004750 case CREATE_SCOPED_CONNECTION:
Ady Abraham2a6ab2a2018-10-26 14:25:30 -07004751 case IS_COLOR_MANAGEMET_USED:
Peiyong Lin0256f722018-08-31 15:45:10 -07004752 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004753 return OK;
4754 }
4755 case CAPTURE_LAYERS:
4756 case CAPTURE_SCREEN: {
4757 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004758 IPCThreadState* ipc = IPCThreadState::self();
4759 const int pid = ipc->getCallingPid();
4760 const int uid = ipc->getCallingUid();
4761 if ((uid != AID_GRAPHICS) &&
4762 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4763 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4764 return PERMISSION_DENIED;
4765 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004766 return OK;
4767 }
4768 // The following codes are deprecated and should never be allowed to access SF.
4769 case CONNECT_DISPLAY_UNUSED:
4770 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4771 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4772 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004773 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004774 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004775
4776 // These codes are used for the IBinder protocol to either interrogate the recipient
4777 // side of the transaction for its canonical interface descriptor or to dump its state.
4778 // We let them pass by default.
4779 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4780 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4781 code == IBinder::SYSPROPS_TRANSACTION) {
4782 return OK;
4783 }
Peiyong Lin3b44a032018-10-24 18:18:12 -07004784 // Numbers from 1000 to 1030 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004785 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin3b44a032018-10-24 18:18:12 -07004786 if (code >= 1000 && code <= 1030) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004787 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4788 return OK;
4789 }
4790 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4791 return PERMISSION_DENIED;
4792#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004793}
4794
Ana Krulec13be8ad2018-08-21 02:43:56 +00004795status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4796 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004797 status_t credentialCheck = CheckTransactCodeCredentials(code);
4798 if (credentialCheck != OK) {
4799 return credentialCheck;
4800 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004801
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004802 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4803 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004804 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004805 IPCThreadState* ipc = IPCThreadState::self();
4806 const int uid = ipc->getCallingUid();
4807 if (CC_UNLIKELY(uid != AID_SYSTEM
4808 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004809 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004810 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004811 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004812 return PERMISSION_DENIED;
4813 }
4814 int n;
4815 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004816 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004817 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004818 return NO_ERROR;
4819 case 1002: // SHOW_UPDATES
4820 n = data.readInt32();
4821 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004822 invalidateHwcGeometry();
4823 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004824 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004825 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004826 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004827 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004828 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004829 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004830 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004831 setTransactionFlags(
4832 eTransactionNeeded|
4833 eDisplayTransactionNeeded|
4834 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004835 return NO_ERROR;
4836 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004837 case 1006:{ // send empty update
4838 signalRefresh();
4839 return NO_ERROR;
4840 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004841 case 1008: // toggle use of hw composer
4842 n = data.readInt32();
4843 mDebugDisableHWC = n ? 1 : 0;
4844 invalidateHwcGeometry();
4845 repaintEverything();
4846 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004847 case 1009: // toggle use of transform hint
4848 n = data.readInt32();
4849 mDebugDisableTransformHint = n ? 1 : 0;
4850 invalidateHwcGeometry();
4851 repaintEverything();
4852 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004853 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004854 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004855 reply->writeInt32(0);
4856 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004857 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004858 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004859 return NO_ERROR;
4860 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004861 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004862 if (!display) {
4863 return NAME_NOT_FOUND;
4864 }
4865
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004866 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004867 return NO_ERROR;
4868 }
4869 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004870 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004871 // daltonize
4872 n = data.readInt32();
4873 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004874 case 1:
4875 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4876 break;
4877 case 2:
4878 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4879 break;
4880 case 3:
4881 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4882 break;
4883 default:
4884 mDaltonizer.setType(ColorBlindnessType::None);
4885 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004886 }
4887 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004888 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004889 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004890 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004891 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004892
4893 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004894 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004895 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004896 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004897 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004898 // apply a color matrix
4899 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004900 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004901 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004902 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004903 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004904 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004905 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004906 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004907 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004908 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004909 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004910
4911 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4912 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004913 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004914 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4915 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4916 }
4917
Chia-I Wu28f320b2018-05-03 11:02:56 -07004918 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004919 return NO_ERROR;
4920 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004921 // This is an experimental interface
4922 // Needs to be shifted to proper binder interface when we productize
4923 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004924 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07004925 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07004926 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004927 return NO_ERROR;
4928 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004929 case 1017: {
4930 n = data.readInt32();
4931 mForceFullDamage = static_cast<bool>(n);
4932 return NO_ERROR;
4933 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004934 case 1018: { // Modify Choreographer's phase offset
4935 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004936 if (mUseScheduler) {
4937 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
4938 } else {
4939 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4940 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004941 return NO_ERROR;
4942 }
4943 case 1019: { // Modify SurfaceFlinger's phase offset
4944 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004945 if (mUseScheduler) {
4946 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
4947 } else {
4948 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4949 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004950 return NO_ERROR;
4951 }
Irvel468051e2016-06-13 16:44:44 -07004952 case 1020: { // Layer updates interceptor
4953 n = data.readInt32();
4954 if (n) {
4955 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004956 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004957 }
4958 else{
4959 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004960 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004961 }
4962 return NO_ERROR;
4963 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004964 case 1021: { // Disable HWC virtual displays
4965 n = data.readInt32();
4966 mUseHwcVirtualDisplays = !n;
4967 return NO_ERROR;
4968 }
Romain Guy0147a172017-06-01 13:53:56 -07004969 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004970 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004971 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004972
Chia-I Wu28f320b2018-05-03 11:02:56 -07004973 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004974 return NO_ERROR;
4975 }
Romain Guy54f154a2017-10-24 21:40:32 +01004976 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004977 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004978 invalidateHwcGeometry();
4979 repaintEverything();
4980 return NO_ERROR;
4981 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004982 // Deprecate, use 1030 to check whether the device is color managed.
4983 case 1024: {
4984 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004985 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004986 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004987 n = data.readInt32();
4988 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004989 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004990 mTracing.enable();
4991 doTracing("tracing.enable");
4992 reply->writeInt32(NO_ERROR);
4993 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004994 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004995 status_t err = mTracing.disable();
4996 reply->writeInt32(err);
4997 }
4998 return NO_ERROR;
4999 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005000 case 1026: { // Get layer tracing status
5001 reply->writeBool(mTracing.isEnabled());
5002 return NO_ERROR;
5003 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005004 // Is a DisplayColorSetting supported?
5005 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005006 const auto display = getDefaultDisplayDevice();
5007 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005008 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005009 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005010
5011 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5012 switch (setting) {
5013 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005014 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005015 break;
5016 case DisplayColorSetting::UNMANAGED:
5017 reply->writeBool(true);
5018 break;
5019 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005020 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005021 break;
5022 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005023 reply->writeBool(
5024 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005025 break;
5026 }
5027 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005028 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005029 // Is VrFlinger active?
5030 case 1028: {
5031 Mutex::Autolock _l(mStateLock);
5032 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5033 return NO_ERROR;
5034 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005035 // Is device color managed?
5036 case 1030: {
5037 reply->writeBool(useColorManagement);
5038 return NO_ERROR;
5039 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005040 }
5041 }
5042 return err;
5043}
5044
Steven Thomas6d8110b2017-08-31 18:24:21 -07005045void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005046 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005047 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005048}
5049
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005050// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5051class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005052public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005053 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5054 ~WindowDisconnector() {
5055 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005056 }
5057
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005058private:
5059 ANativeWindow* mWindow;
5060 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005061};
5062
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005063status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005064 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5065 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005066 uint32_t reqWidth, uint32_t reqHeight,
5067 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005068 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005069 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005070
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005071 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005072
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005073 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5074
Chia-I Wu20261cb2018-08-23 12:55:44 -07005075 sp<DisplayDevice> display;
5076 {
5077 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005078
Chia-I Wu20261cb2018-08-23 12:55:44 -07005079 display = getDisplayDeviceLocked(displayToken);
5080 if (!display) return BAD_VALUE;
5081
Chia-I Wucb023152018-08-28 12:57:23 -07005082 // set the requested width/height to the logical display viewport size
5083 // by default
5084 if (reqWidth == 0 || reqHeight == 0) {
5085 reqWidth = uint32_t(display->getViewport().width());
5086 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005087 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005088 }
5089
Peiyong Lin0e003c92018-09-17 11:09:51 -07005090 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5091 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005092
5093 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005094 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005095 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5096 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005097}
5098
5099status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005100 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5101 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005102 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005103 ATRACE_CALL();
5104
5105 class LayerRenderArea : public RenderArea {
5106 public:
Robert Carr578038f2018-03-09 12:25:24 -08005107 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005108 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5109 bool childrenOnly)
5110 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005111 mLayer(layer),
5112 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005113 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005114 mFlinger(flinger),
5115 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005116 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005117 Rect getBounds() const override {
5118 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005119 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005120 }
Marissa Wall61c58622018-07-18 10:12:20 -07005121 int getHeight() const override {
5122 return mLayer->getActiveHeight(mLayer->getDrawingState());
5123 }
5124 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005125 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005126 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005127 Rect getSourceCrop() const override {
5128 if (mCrop.isEmpty()) {
5129 return getBounds();
5130 } else {
5131 return mCrop;
5132 }
5133 }
Robert Carr578038f2018-03-09 12:25:24 -08005134 class ReparentForDrawing {
5135 public:
5136 const sp<Layer>& oldParent;
5137 const sp<Layer>& newParent;
5138
5139 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5140 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005141 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005142 }
Robert Carr15eae092018-03-23 13:43:53 -07005143 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005144 };
5145
5146 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005147 const Rect sourceCrop = getSourceCrop();
5148 // no need to check rotation because there is none
5149 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5150 sourceCrop.height() != getReqHeight();
5151
Robert Carr578038f2018-03-09 12:25:24 -08005152 if (!mChildrenOnly) {
5153 mTransform = mLayer->getTransform().inverse();
5154 drawLayers();
5155 } else {
5156 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005157 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005158 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5159 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005160
5161 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5162 drawLayers();
5163 }
5164 }
chaviwa76b2712017-09-20 12:02:26 -07005165
chaviwa76b2712017-09-20 12:02:26 -07005166 private:
chaviw7206d492017-11-10 16:16:12 -08005167 const sp<Layer> mLayer;
5168 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005169
5170 // In the "childrenOnly" case we reparent the children to a screenshot
5171 // layer which has no properties set and which does not draw.
5172 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005173 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005174 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005175
5176 SurfaceFlinger* mFlinger;
5177 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005178 };
5179
5180 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5181 auto parent = layerHandle->owner.promote();
5182
Jorim Jaggi10c985e2018-10-23 11:17:45 +00005183 if (parent == nullptr || parent->isPendingRemoval()) {
chaviw7206d492017-11-10 16:16:12 -08005184 ALOGE("captureLayers called with a removed parent");
5185 return NAME_NOT_FOUND;
5186 }
5187
Robert Carr578038f2018-03-09 12:25:24 -08005188 const int uid = IPCThreadState::self()->getCallingUid();
5189 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5190 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5191 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5192 return PERMISSION_DENIED;
5193 }
5194
chaviw7206d492017-11-10 16:16:12 -08005195 Rect crop(sourceCrop);
5196 if (sourceCrop.width() <= 0) {
5197 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005198 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005199 }
5200
5201 if (sourceCrop.height() <= 0) {
5202 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005203 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005204 }
5205
5206 int32_t reqWidth = crop.width() * frameScale;
5207 int32_t reqHeight = crop.height() * frameScale;
5208
Chia-I Wu20261cb2018-08-23 12:55:44 -07005209 // really small crop or frameScale
5210 if (reqWidth <= 0) {
5211 reqWidth = 1;
5212 }
5213 if (reqHeight <= 0) {
5214 reqHeight = 1;
5215 }
5216
Peiyong Lin0e003c92018-09-17 11:09:51 -07005217 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005218
Robert Carr578038f2018-03-09 12:25:24 -08005219 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005220 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5221 if (!layer->isVisible()) {
5222 return;
Robert Carr578038f2018-03-09 12:25:24 -08005223 } else if (childrenOnly && layer == parent.get()) {
5224 return;
chaviwa76b2712017-09-20 12:02:26 -07005225 }
5226 visitor(layer);
5227 });
5228 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005229 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005230}
5231
5232status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5233 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005234 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005235 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005236 bool useIdentityTransform) {
5237 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005238
Peiyong Lin0e003c92018-09-17 11:09:51 -07005239 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005240 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5241 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005242 *outBuffer =
5243 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5244 static_cast<android_pixel_format>(reqPixelFormat), 1,
5245 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005246
5247 // This mutex protects syncFd and captureResult for communication of the return values from the
5248 // main thread back to this Binder thread
5249 std::mutex captureMutex;
5250 std::condition_variable captureCondition;
5251 std::unique_lock<std::mutex> captureLock(captureMutex);
5252 int syncFd = -1;
5253 std::optional<status_t> captureResult;
5254
Robert Carr03480e22018-01-04 16:02:06 -08005255 const int uid = IPCThreadState::self()->getCallingUid();
5256 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5257
Dominik Laskowski8c001672018-05-30 16:52:06 -07005258 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005259 // If there is a refresh pending, bug out early and tell the binder thread to try again
5260 // after the refresh.
5261 if (mRefreshPending) {
5262 ATRACE_NAME("Skipping screenshot for now");
5263 std::unique_lock<std::mutex> captureLock(captureMutex);
5264 captureResult = std::make_optional<status_t>(EAGAIN);
5265 captureCondition.notify_one();
5266 return;
5267 }
5268
5269 status_t result = NO_ERROR;
5270 int fd = -1;
5271 {
5272 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005273 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005274 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5275 useIdentityTransform, forSystem, &fd);
5276 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005277 }
5278
5279 {
5280 std::unique_lock<std::mutex> captureLock(captureMutex);
5281 syncFd = fd;
5282 captureResult = std::make_optional<status_t>(result);
5283 captureCondition.notify_one();
5284 }
5285 });
5286
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005287 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005288 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005289 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005290 while (*captureResult == EAGAIN) {
5291 captureResult.reset();
5292 result = postMessageAsync(message);
5293 if (result != NO_ERROR) {
5294 return result;
5295 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005296 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005297 }
5298 result = *captureResult;
5299 }
5300
5301 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005302 sync_wait(syncFd, -1);
5303 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005304 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005305
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005306 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005307}
5308
chaviwa76b2712017-09-20 12:02:26 -07005309void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005310 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005311 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005312 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005313
Lloyd Pique144e1162017-12-20 16:44:52 -08005314 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005315
chaviwa76b2712017-09-20 12:02:26 -07005316 const auto reqWidth = renderArea.getReqWidth();
5317 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005318 const auto sourceCrop = renderArea.getSourceCrop();
5319 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005320
Peiyong Lin0e003c92018-09-17 11:09:51 -07005321 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005322 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005323
Mathias Agopian180f10d2013-04-10 22:55:41 -07005324 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005325 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005326
5327 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005328 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005329 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005330
chaviw50da5042018-04-09 13:49:37 -07005331 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005332 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005333 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005334
chaviwa76b2712017-09-20 12:02:26 -07005335 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005336 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005337 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005338 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005339 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005340}
5341
chaviwa76b2712017-09-20 12:02:26 -07005342status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5343 TraverseLayersFunction traverseLayers,
5344 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005345 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005346 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005347 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005348 ATRACE_CALL();
5349
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005350 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005351
5352 traverseLayers([&](Layer* layer) {
5353 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5354 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005355
Robert Carr03480e22018-01-04 16:02:06 -08005356 // We allow the system server to take screenshots of secure layers for
5357 // use in situations like the Screen-rotation animation and place
5358 // the impetus on WindowManager to not persist them.
5359 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005360 ALOGW("FB is protected: PERMISSION_DENIED");
5361 return PERMISSION_DENIED;
5362 }
5363
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005364 // this binds the given EGLImage as a framebuffer for the
5365 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005366 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005367 if (bufferBond.getStatus() != NO_ERROR) {
5368 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005369 return INVALID_OPERATION;
5370 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005371
Dan Stozaabcda352017-06-01 14:37:39 -07005372 // this will in fact render into our dequeued buffer
5373 // via an FBO, which means we didn't have to create
5374 // an EGLSurface and therefore we're not
5375 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005376 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005377
Alec Mouri492bc572018-09-11 21:40:04 +00005378 base::unique_fd syncFd = getRenderEngine().flush();
5379 if (syncFd < 0) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005380 getRenderEngine().finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005381 }
Alec Mouri492bc572018-09-11 21:40:04 +00005382 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005383
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005384 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005385}
5386
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005387// ---------------------------------------------------------------------------
5388
Dan Stoza412903f2017-04-27 13:42:17 -07005389void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5390 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005391}
5392
Dan Stoza412903f2017-04-27 13:42:17 -07005393void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5394 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005395}
5396
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005397void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005398 const LayerVector::Visitor& visitor) {
5399 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005400 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005401 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005402 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005403 continue;
5404 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005405 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005406 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005407 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005408 return;
5409 }
chaviwa76b2712017-09-20 12:02:26 -07005410 if (!layer->isVisible()) {
5411 return;
5412 }
5413 visitor(layer);
5414 });
5415 }
5416}
5417
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005418}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005419
Lloyd Pique074e8122018-07-26 12:57:23 -07005420
Mathias Agopian3f844832013-08-07 21:24:32 -07005421#if defined(__gl_h_)
5422#error "don't include gl/gl.h in this file"
5423#endif
5424
5425#if defined(__gl2_h_)
5426#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005427#endif