blob: b97429e8433385f8511bb52ca829dec2b3d421a7 [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>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070050
51#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"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070081#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070082#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070083#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070084#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
Mathias Agopian875d8e12013-06-07 15:35:48 -070086#include "RenderEngine/RenderEngine.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070087#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070088#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070089#include "Scheduler/EventControlThread.h"
90#include "Scheduler/EventThread.h"
91
Mathias Agopianff2ed702013-09-01 21:36:12 -070092#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070093
Jiyong Park4b20c2e2017-01-14 19:45:11 +090094#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080095#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
96#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090097#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090098
chaviw1d044282017-09-27 12:19:28 -070099#include <layerproto/LayerProtoParser.h>
100
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800101#define DISPLAY_COUNT 1
102
Mathias Agopianfee2b462013-07-03 12:34:01 -0700103/*
104 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
105 * black pixels.
106 */
107#define DEBUG_SCREENSHOTS false
108
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800109namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700110
Jaesoo Lee43518572017-01-23 19:03:16 +0900111using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900112using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700113using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700114using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700115using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700116using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900117
Steven Thomasb02664d2017-07-26 18:48:28 -0700118namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700119
120#pragma clang diagnostic push
121#pragma clang diagnostic error "-Wswitch-enum"
122
123bool isWideColorMode(const ColorMode colorMode) {
124 switch (colorMode) {
125 case ColorMode::DISPLAY_P3:
126 case ColorMode::ADOBE_RGB:
127 case ColorMode::DCI_P3:
128 case ColorMode::BT2020:
129 case ColorMode::BT2100_PQ:
130 case ColorMode::BT2100_HLG:
131 return true;
132 case ColorMode::NATIVE:
133 case ColorMode::STANDARD_BT601_625:
134 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
135 case ColorMode::STANDARD_BT601_525:
136 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
137 case ColorMode::STANDARD_BT709:
138 case ColorMode::SRGB:
139 return false;
140 }
141 return false;
142}
143
144#pragma clang diagnostic pop
145
Steven Thomasb02664d2017-07-26 18:48:28 -0700146class ConditionalLock {
147public:
148 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
149 if (lock) {
150 mMutex.lock();
151 }
152 }
153 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
154private:
155 Mutex& mMutex;
156 bool mLocked;
157};
Peiyong Linfca547f2018-07-09 13:03:33 -0700158
Steven Thomasb02664d2017-07-26 18:48:28 -0700159} // namespace anonymous
160
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800161// ---------------------------------------------------------------------------
162
Mathias Agopian99b49842011-06-27 16:05:52 -0700163const String16 sHardwareTest("android.permission.HARDWARE_TEST");
164const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
165const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
166const String16 sDump("android.permission.DUMP");
167
168// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800169int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
170int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700171int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700172bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800173uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800174bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800175bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800176int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800177// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600178bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700179
Kalle Raitaa099a242017-01-11 11:17:29 -0800180
181std::string getHwcServiceName() {
182 char value[PROPERTY_VALUE_MAX] = {};
183 property_get("debug.sf.hwc_service_name", value, "default");
184 ALOGI("Using HWComposer service: '%s'", value);
185 return std::string(value);
186}
187
188bool useTrebleTestingOverride() {
189 char value[PROPERTY_VALUE_MAX] = {};
190 property_get("debug.sf.treble_testing_override", value, "false");
191 ALOGI("Treble testing override: '%s'", value);
192 return std::string(value) == "true";
193}
194
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800195std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
196 switch(displayColorSetting) {
197 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700198 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800199 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700200 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800201 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700202 return std::string("Enhanced");
203 default:
204 return std::string("Unknown ") +
205 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800206 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800207}
208
Lloyd Pique99d3da52018-01-22 17:48:03 -0800209NativeWindowSurface::~NativeWindowSurface() = default;
210
211namespace impl {
212
213class NativeWindowSurface final : public android::NativeWindowSurface {
214public:
215 static std::unique_ptr<android::NativeWindowSurface> create(
216 const sp<IGraphicBufferProducer>& producer) {
217 return std::make_unique<NativeWindowSurface>(producer);
218 }
219
220 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
221 : surface(new Surface(producer, false)) {}
222
223 ~NativeWindowSurface() override = default;
224
225private:
226 sp<ANativeWindow> getNativeWindow() const override { return surface; }
227
228 void preallocateBuffers() override { surface->allocateBuffers(); }
229
230 sp<Surface> surface;
231};
232
233} // namespace impl
234
David Sodmanbc815282017-11-05 18:57:52 -0800235SurfaceFlingerBE::SurfaceFlingerBE()
236 : mHwcServiceName(getHwcServiceName()),
237 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800238 mFrameBuckets(),
239 mTotalTime(0),
240 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800241 mComposerSequenceId(0) {
242}
243
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800244SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800245 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800246 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700247 mTransactionPending(false),
248 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700249 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700250 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700251 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800252 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700253 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800254 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800255 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800256 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800257 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800258 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700259 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700260 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700261 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700262 mDebugInSwapBuffers(0),
263 mLastSwapBufferTime(0),
264 mDebugInTransaction(0),
265 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700266 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700267 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700268 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800269 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800270 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800271 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700272 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800273 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800274 mCreateBufferQueue(&BufferQueue::createBufferQueue),
275 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800276
277SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800278 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800279
280 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
281 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
282
283 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
284 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
285
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800286 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
287 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700289 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
290 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
291
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700292 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
293 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
294
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800295 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
296 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
297
Steven Thomas050b2c82017-03-06 11:45:16 -0800298 // Vr flinger is only enabled on Daydream ready devices.
299 useVrFlinger = getBool< ISurfaceFlingerConfigs,
300 &ISurfaceFlingerConfigs::useVrFlinger>(false);
301
Fabien Sanglard1971b632017-03-10 14:50:03 -0800302 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
303 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
304
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600305 hasWideColorDisplay =
306 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
307
Iris Chang7501ed62018-04-30 14:45:42 +0800308 V1_1::DisplayOrientation primaryDisplayOrientation =
309 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
310 V1_1::DisplayOrientation::ORIENTATION_0);
311
312 switch (primaryDisplayOrientation) {
313 case V1_1::DisplayOrientation::ORIENTATION_90:
314 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
315 break;
316 case V1_1::DisplayOrientation::ORIENTATION_180:
317 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
318 break;
319 case V1_1::DisplayOrientation::ORIENTATION_270:
320 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
321 break;
322 default:
323 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
324 break;
325 }
326 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
327
Lloyd Pique41be5d22018-06-21 13:11:48 -0700328 // Note: We create a local temporary with the real DispSync implementation
329 // type temporarily so we can initialize it with the configured values,
330 // before storing it for more generic use using the interface type.
331 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
332 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
333 SurfaceFlinger::dispSyncPresentTimeOffset);
334 mPrimaryDispSync = std::move(primaryDispSync);
Saurabh Shahf4174532017-07-13 10:45:07 -0700335
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800336 // debugging stuff...
337 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700338
Mathias Agopianb4b17302013-03-20 18:36:41 -0700339 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700340 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700341
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800342 property_get("debug.sf.showupdates", value, "0");
343 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700344
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700345 property_get("debug.sf.ddms", value, "0");
346 mDebugDDMS = atoi(value);
347 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700348 if (!startDdmConnection()) {
349 // start failed, and DDMS debugging not enabled
350 mDebugDDMS = 0;
351 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700352 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700353 ALOGI_IF(mDebugRegion, "showupdates enabled");
354 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700355
356 property_get("debug.sf.disable_backpressure", value, "0");
357 mPropagateBackpressure = !atoi(value);
358 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700359
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800360 property_get("debug.sf.enable_hwc_vds", value, "0");
361 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800362 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800363
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800364 property_get("ro.sf.disable_triple_buffer", value, "1");
365 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800366 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700367
Yiwei Zhang243b3782018-05-15 17:40:04 -0700368 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700369 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
370 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
371
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200372 property_get("debug.sf.early_phase_offset_ns", value, "-1");
373 const int earlySfOffsetNs = atoi(value);
374
375 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
376 const int earlyGlSfOffsetNs = atoi(value);
377
378 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
379 const int earlyAppOffsetNs = atoi(value);
380
381 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
382 const int earlyGlAppOffsetNs = atoi(value);
383
384 const VSyncModulator::Offsets earlyOffsets =
385 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
386 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
387 const VSyncModulator::Offsets earlyGlOffsets =
388 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
389 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
390 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
391 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700392
Romain Guy11d63f42017-07-20 12:47:14 -0700393 // We should be reading 'persist.sys.sf.color_saturation' here
394 // but since /data may be encrypted, we need to wait until after vold
395 // comes online to attempt to read the property. The property is
396 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800397
398 if (useTrebleTestingOverride()) {
399 // Without the override SurfaceFlinger cannot connect to HIDL
400 // services that are not listed in the manifests. Considered
401 // deriving the setting from the set service name, but it
402 // would be brittle if the name that's not 'default' is used
403 // for production purposes later on.
404 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
405 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800406}
407
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800408void SurfaceFlinger::onFirstRef()
409{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800410 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800411}
412
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800413SurfaceFlinger::~SurfaceFlinger()
414{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800415}
416
Dan Stozac7014012014-02-14 15:03:43 -0800417void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800418{
419 // the window manager died on us. prepare its eulogy.
420
Andy McFadden13a082e2012-08-24 10:16:42 -0700421 // restore initial conditions (default device unblank, etc)
422 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800423
424 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700425 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800426}
427
Robert Carr1db73f62016-12-21 12:58:51 -0800428static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700429 status_t err = client->initCheck();
430 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800431 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800432 }
Robert Carr1db73f62016-12-21 12:58:51 -0800433 return nullptr;
434}
435
436sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
437 return initClient(new Client(this));
438}
439
440sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
441 const sp<IGraphicBufferProducer>& gbp) {
442 if (authenticateSurfaceTexture(gbp) == false) {
443 return nullptr;
444 }
445 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
446 if (layer == nullptr) {
447 return nullptr;
448 }
449
450 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800451}
452
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700453sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
454 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700455{
456 class DisplayToken : public BBinder {
457 sp<SurfaceFlinger> flinger;
458 virtual ~DisplayToken() {
459 // no more references, this display must be terminated
460 Mutex::Autolock _l(flinger->mStateLock);
461 flinger->mCurrentState.displays.removeItem(this);
462 flinger->setTransactionFlags(eDisplayTransactionNeeded);
463 }
464 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700465 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700466 : flinger(flinger) {
467 }
468 };
469
470 sp<BBinder> token = new DisplayToken(this);
471
472 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700473 DisplayDeviceState info;
474 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700475 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700476 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700477 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800478 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700479 return token;
480}
481
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700482void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700483 Mutex::Autolock _l(mStateLock);
484
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700485 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700486 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700487 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700488 return;
489 }
490
491 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700492 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700493 ALOGE("destroyDisplay called for non-virtual display");
494 return;
495 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700496 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700497 mCurrentState.displays.removeItemsAt(idx);
498 setTransactionFlags(eDisplayTransactionNeeded);
499}
500
Mathias Agopiane57f2922012-08-09 16:29:12 -0700501sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700502 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700503 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800504 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700505 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700506 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700507}
508
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800509void SurfaceFlinger::bootFinished()
510{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700511 if (mStartPropertySetThread->join() != NO_ERROR) {
512 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800513 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800514 const nsecs_t now = systemTime();
515 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000516 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700517
518 // wait patiently for the window manager death
519 const String16 name("window");
520 sp<IBinder> window(defaultServiceManager()->getService(name));
521 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700522 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700523 }
524
Steven Thomas050b2c82017-03-06 11:45:16 -0800525 if (mVrFlinger) {
526 mVrFlinger->OnBootFinished();
527 }
528
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700529 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700530 // formerly we would just kill the process, but we now ask it to exit so it
531 // can choose where to stop the animation.
532 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700533
534 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
535 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
536 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700537
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800538 postMessageAsync(new LambdaMessage([this] {
539 readPersistentProperties();
540 mBootStage = BootStage::FINISHED;
541 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800542}
543
Dan Stoza436ccf32018-06-21 12:10:12 -0700544uint32_t SurfaceFlinger::getNewTexture() {
545 {
546 std::lock_guard lock(mTexturePoolMutex);
547 if (!mTexturePool.empty()) {
548 uint32_t name = mTexturePool.back();
549 mTexturePool.pop_back();
550 ATRACE_INT("TexturePoolSize", mTexturePool.size());
551 return name;
552 }
553
554 // The pool was too small, so increase it for the future
555 ++mTexturePoolSize;
556 }
557
558 // The pool was empty, so we need to get a new texture name directly using a
559 // blocking call to the main thread
560 uint32_t name = 0;
561 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
562 return name;
563}
564
Mathias Agopian3f844832013-08-07 21:24:32 -0700565void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700566 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700567}
568
Lloyd Piquee83f9312018-02-01 12:53:17 -0800569class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700570public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800571 InjectVSyncSource() = default;
572 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700573
Lloyd Piquee83f9312018-02-01 12:53:17 -0800574 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700575 std::lock_guard<std::mutex> lock(mCallbackMutex);
576 mCallback = callback;
577 }
578
Lloyd Piquee83f9312018-02-01 12:53:17 -0800579 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700580 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700581 if (mCallback) {
582 mCallback->onVSyncEvent(when);
583 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700584 }
585
Lloyd Piquee83f9312018-02-01 12:53:17 -0800586 void setVSyncEnabled(bool) override {}
587 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700588
589private:
590 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800591 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700592};
593
Wei Wangf9b05ee2017-07-19 20:59:39 -0700594// Do not call property_set on main thread which will be blocked by init
595// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700596void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700597 ALOGI( "SurfaceFlinger's main thread ready to run. "
598 "Initializing graphics H/W...");
599
Thierry Strudel2924d012017-08-14 15:19:37 -0700600 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900601
Steven Thomasb02664d2017-07-26 18:48:28 -0700602 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800603
Steven Thomasb02664d2017-07-26 18:48:28 -0700604 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800605 mEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700606 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
607 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800608 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700609 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800610 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800611 "appEventThread");
612 mSfEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700613 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800614 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800615
Lloyd Pique24b0a482018-03-09 18:52:26 -0800616 mSFEventThread =
617 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700618 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800619 [this](nsecs_t timestamp) {
620 mInterceptor->saveVSyncEvent(timestamp);
621 },
622 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800623 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200624 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800625
Steven Thomasb02664d2017-07-26 18:48:28 -0700626 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800627 getBE().mRenderEngine =
628 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
629 hasWideColorDisplay
630 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
631 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800632 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700633
634 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
635 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800636 getBE().mHwc.reset(
637 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700638 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800639 // Process any initial hotplug and resulting display changes.
640 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700641 const auto display = getDefaultDisplayDeviceLocked();
642 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
643 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
644 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800645
Lloyd Piquefcd86612017-12-14 17:15:36 -0800646 // make the default display GLContext current so that we can create textures
647 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700648 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800649
Steven Thomas050b2c82017-03-06 11:45:16 -0800650 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700651 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700652 // This callback is called from the vr flinger dispatch thread. We
653 // need to call signalTransaction(), which requires holding
654 // mStateLock when we're not on the main thread. Acquiring
655 // mStateLock from the vr flinger dispatch thread might trigger a
656 // deadlock in surface flinger (see b/66916578), so post a message
657 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700658 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700659 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
660 mVrFlingerRequestsDisplay = requestDisplay;
661 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700662 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800663 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700664 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
665 getHwComposer()
666 .getHwcDisplayId(display->getId())
667 .value_or(0),
668 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800669 if (!mVrFlinger) {
670 ALOGE("Failed to start vrflinger");
671 }
672 }
673
Lloyd Pique379adc12018-01-22 17:31:47 -0800674 mEventControlThread = std::make_unique<impl::EventControlThread>(
675 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700676
Mathias Agopian92a979a2012-08-02 18:32:23 -0700677 // initialize our drawing state
678 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700679
Andy McFadden13a082e2012-08-24 10:16:42 -0700680 // set initial conditions (e.g. unblank default device)
681 initializeDisplays();
682
David Sodmanbc815282017-11-05 18:57:52 -0800683 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700684
Wei Wangf9b05ee2017-07-19 20:59:39 -0700685 // Inform native graphics APIs whether the present timestamp is supported:
686 if (getHwComposer().hasCapability(
687 HWC2::Capability::PresentFenceIsNotReliable)) {
688 mStartPropertySetThread = new StartPropertySetThread(false);
689 } else {
690 mStartPropertySetThread = new StartPropertySetThread(true);
691 }
692
693 if (mStartPropertySetThread->Start() != NO_ERROR) {
694 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800695 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800696
Chia-I Wud49d6692018-06-27 07:17:41 +0800697 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
698 // is used to saturate legacy sRGB content. However, to make sure the same color under
699 // Display P3 will be saturated to the same color, we intentionally break the API spec
700 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
701 // such saturation matrix on Display P3 is understood fully, the API should always return
702 // identify matrix.
703 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
704 Dataspace::SRGB_LINEAR);
705
706 // we will apply this on Display P3.
707 if (mEnhancedSaturationMatrix != mat4()) {
708 ColorSpace srgb(ColorSpace::sRGB());
709 ColorSpace displayP3(ColorSpace::DisplayP3());
710 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
711 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
712 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
713 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800714
Dan Stoza9e56aa02015-11-02 13:00:03 -0800715 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700716}
717
Romain Guy11d63f42017-07-20 12:47:14 -0700718void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700719 Mutex::Autolock _l(mStateLock);
720
Romain Guy11d63f42017-07-20 12:47:14 -0700721 char value[PROPERTY_VALUE_MAX];
722
723 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800724 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700725 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800726 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100727
728 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700729 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700730}
731
Mathias Agopiana67e4182012-06-19 17:26:12 -0700732void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800733 // Start boot animation service by setting a property mailbox
734 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700735 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800736 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700737 if (mStartPropertySetThread->join() != NO_ERROR) {
738 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800739 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700740}
741
Mathias Agopian875d8e12013-06-07 15:35:48 -0700742size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800743 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700744}
745
Mathias Agopian875d8e12013-06-07 15:35:48 -0700746size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800747 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700748}
749
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800750// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800751
Jamie Gennis582270d2011-08-17 18:19:00 -0700752bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800753 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800754 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800755 return authenticateSurfaceTextureLocked(bufferProducer);
756}
757
758bool SurfaceFlinger::authenticateSurfaceTextureLocked(
759 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800760 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800761 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800762}
763
Brian Anderson6b376712017-04-04 10:51:39 -0700764status_t SurfaceFlinger::getSupportedFrameTimestamps(
765 std::vector<FrameEvent>* outSupported) const {
766 *outSupported = {
767 FrameEvent::REQUESTED_PRESENT,
768 FrameEvent::ACQUIRE,
769 FrameEvent::LATCH,
770 FrameEvent::FIRST_REFRESH_START,
771 FrameEvent::LAST_REFRESH_START,
772 FrameEvent::GPU_COMPOSITION_DONE,
773 FrameEvent::DEQUEUE_READY,
774 FrameEvent::RELEASE,
775 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700776 ConditionalLock _l(mStateLock,
777 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700778 if (!getHwComposer().hasCapability(
779 HWC2::Capability::PresentFenceIsNotReliable)) {
780 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
781 }
782 return NO_ERROR;
783}
784
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700785status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
786 Vector<DisplayInfo>* configs) {
787 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700788 return BAD_VALUE;
789 }
790
Jesse Hall692c7232012-11-08 15:41:56 -0800791 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700792 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
793 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700794 type = i;
795 break;
796 }
797 }
798
799 if (type < 0) {
800 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700801 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700802
Mathias Agopian8b736f12012-08-13 17:54:26 -0700803 // TODO: Not sure if display density should handled by SF any longer
804 class Density {
805 static int getDensityFromProperty(char const* propName) {
806 char property[PROPERTY_VALUE_MAX];
807 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800808 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700809 density = atoi(property);
810 }
811 return density;
812 }
813 public:
814 static int getEmuDensity() {
815 return getDensityFromProperty("qemu.sf.lcd_density"); }
816 static int getBuildDensity() {
817 return getDensityFromProperty("ro.sf.lcd_density"); }
818 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700819
Dan Stoza7f7da322014-05-02 15:26:25 -0700820 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700821
Steven Thomas6d8110b2017-08-31 18:24:21 -0700822 ConditionalLock _l(mStateLock,
823 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800824 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700825 DisplayInfo info = DisplayInfo();
826
Dan Stoza9e56aa02015-11-02 13:00:03 -0800827 float xdpi = hwConfig->getDpiX();
828 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700829
830 if (type == DisplayDevice::DISPLAY_PRIMARY) {
831 // The density of the device is provided by a build property
832 float density = Density::getBuildDensity() / 160.0f;
833 if (density == 0) {
834 // the build doesn't provide a density -- this is wrong!
835 // use xdpi instead
836 ALOGE("ro.sf.lcd_density must be defined as a build property");
837 density = xdpi / 160.0f;
838 }
839 if (Density::getEmuDensity()) {
840 // if "qemu.sf.lcd_density" is specified, it overrides everything
841 xdpi = ydpi = density = Density::getEmuDensity();
842 density /= 160.0f;
843 }
844 info.density = density;
845
846 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700847 const auto display = getDefaultDisplayDeviceLocked();
848 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700849 } else {
850 // TODO: where should this value come from?
851 static const int TV_DENSITY = 213;
852 info.density = TV_DENSITY / 160.0f;
853 info.orientation = 0;
854 }
855
Dan Stoza9e56aa02015-11-02 13:00:03 -0800856 info.w = hwConfig->getWidth();
857 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700858 info.xdpi = xdpi;
859 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800860 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900861 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800862
Andy McFadden91b2ca82014-06-13 14:04:23 -0700863 // This is how far in advance a buffer must be queued for
864 // presentation at a given time. If you want a buffer to appear
865 // on the screen at time N, you must submit the buffer before
866 // (N - presentationDeadline).
867 //
868 // Normally it's one full refresh period (to give SF a chance to
869 // latch the buffer), but this can be reduced by configuring a
870 // DispSync offset. Any additional delays introduced by the hardware
871 // composer or panel must be accounted for here.
872 //
873 // We add an additional 1ms to allow for processing time and
874 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800875 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800876 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700877
878 // All non-virtual displays are currently considered secure.
879 info.secure = true;
880
Iris Chang7501ed62018-04-30 14:45:42 +0800881 if (type == DisplayDevice::DISPLAY_PRIMARY &&
882 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
883 std::swap(info.w, info.h);
884 }
885
Michael Wright28f24d02016-07-12 13:30:53 -0700886 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700887 }
888
Dan Stoza7f7da322014-05-02 15:26:25 -0700889 return NO_ERROR;
890}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700891
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700892status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
893 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700894 return BAD_VALUE;
895 }
896
897 // FIXME for now we always return stats for the primary display
898 memset(stats, 0, sizeof(*stats));
Lloyd Pique41be5d22018-06-21 13:11:48 -0700899 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
900 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700901 return NO_ERROR;
902}
903
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700904int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
905 const auto display = getDisplayDevice(displayToken);
906 if (!display) {
907 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800908 return BAD_VALUE;
909 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700910
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700911 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700912}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700913
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700914void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
915 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700916 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700917 return;
918 }
919
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700920 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700921 ALOGW("Trying to set config for virtual display");
922 return;
923 }
924
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700925 display->setActiveConfig(mode);
926 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700927}
928
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700929status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700930 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700931 Vector<DisplayInfo> configs;
932 getDisplayConfigs(displayToken, &configs);
933 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
934 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
935 configs.size());
936 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700937 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700938 const auto display = getDisplayDevice(displayToken);
939 if (!display) {
940 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
941 displayToken.get());
942 } else if (display->isVirtual()) {
943 ALOGW("Attempt to set active config %d for virtual display", mode);
944 } else {
945 setActiveConfigInternal(display, mode);
946 }
947 }));
948
Mathias Agopian888c8222012-08-04 21:10:38 -0700949 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700950}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700951status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
952 Vector<ColorMode>* outColorModes) {
953 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700954 return BAD_VALUE;
955 }
956
Michael Wright28f24d02016-07-12 13:30:53 -0700957 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700958 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
959 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700960 type = i;
961 break;
962 }
963 }
964
965 if (type < 0) {
966 return type;
967 }
968
Peiyong Lina52f0292018-03-14 17:26:31 -0700969 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700970 {
971 ConditionalLock _l(mStateLock,
972 std::this_thread::get_id() != mMainThreadId);
973 modes = getHwComposer().getColorModes(type);
974 }
Michael Wright28f24d02016-07-12 13:30:53 -0700975 outColorModes->clear();
976 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
977
978 return NO_ERROR;
979}
980
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700981ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
982 if (const auto display = getDisplayDevice(displayToken)) {
983 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700984 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700985 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700986}
987
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700988void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
989 Dataspace dataSpace, RenderIntent renderIntent) {
990 ColorMode currentMode = display->getActiveColorMode();
991 Dataspace currentDataSpace = display->getCompositionDataSpace();
992 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -0700993
Peiyong Lin38e9a562018-04-10 16:24:20 -0700994 if (mode == currentMode && dataSpace == currentDataSpace &&
995 renderIntent == currentRenderIntent) {
996 return;
997 }
998
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700999 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001000 ALOGW("Trying to set config for virtual display");
1001 return;
1002 }
1003
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001004 display->setActiveColorMode(mode);
1005 display->setCompositionDataSpace(dataSpace);
1006 display->setActiveRenderIntent(renderIntent);
1007 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001008
1009 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001010 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1011 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001012}
1013
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001014status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001015 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001016 Vector<ColorMode> modes;
1017 getDisplayColorModes(displayToken, &modes);
1018 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1019 if (mode < ColorMode::NATIVE || !exists) {
1020 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1021 decodeColorMode(mode).c_str(), mode, displayToken.get());
1022 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001023 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001024 const auto display = getDisplayDevice(displayToken);
1025 if (!display) {
1026 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1027 decodeColorMode(mode).c_str(), mode, displayToken.get());
1028 } else if (display->isVirtual()) {
1029 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1030 decodeColorMode(mode).c_str(), mode);
1031 } else {
1032 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1033 RenderIntent::COLORIMETRIC);
1034 }
1035 }));
1036
Michael Wright28f24d02016-07-12 13:30:53 -07001037 return NO_ERROR;
1038}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001039
Svetoslavd85084b2014-03-20 10:28:31 -07001040status_t SurfaceFlinger::clearAnimationFrameStats() {
1041 Mutex::Autolock _l(mStateLock);
1042 mAnimFrameTracker.clearStats();
1043 return NO_ERROR;
1044}
1045
1046status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1047 Mutex::Autolock _l(mStateLock);
1048 mAnimFrameTracker.getStats(outStats);
1049 return NO_ERROR;
1050}
1051
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001052status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1053 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001054 Mutex::Autolock _l(mStateLock);
1055
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001056 const auto display = getDisplayDeviceLocked(displayToken);
1057 if (!display) {
1058 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001059 return BAD_VALUE;
1060 }
1061
Peiyong Linfb069302018-04-25 14:34:31 -07001062 // At this point the DisplayDeivce should already be set up,
1063 // meaning the luminance information is already queried from
1064 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001065 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001066 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1067 capabilities.getDesiredMaxLuminance(),
1068 capabilities.getDesiredMaxAverageLuminance(),
1069 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001070
1071 return NO_ERROR;
1072}
1073
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001074status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001075 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001076 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001077
Chia-I Wu90f669f2017-10-05 14:24:41 -07001078 if (mInjectVSyncs == enable) {
1079 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001080 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001081
1082 if (enable) {
1083 ALOGV("VSync Injections enabled");
1084 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001085 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001086 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001087 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001088 impl::EventThread::InterceptVSyncsCallback(),
1089 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001090 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001091 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001092 } else {
1093 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001094 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001095 }
1096
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001097 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001098 }));
1099
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001100 return NO_ERROR;
1101}
1102
1103status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001104 Mutex::Autolock _l(mStateLock);
1105
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001106 if (!mInjectVSyncs) {
1107 ALOGE("VSync Injections not enabled");
1108 return BAD_VALUE;
1109 }
1110 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1111 ALOGV("Injecting VSync inside SurfaceFlinger");
1112 mVSyncInjector->onInjectSyncEvent(when);
1113 }
1114 return NO_ERROR;
1115}
1116
Lloyd Pique755e3192018-01-31 16:46:15 -08001117status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1118 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001119 // Try to acquire a lock for 1s, fail gracefully
1120 const status_t err = mStateLock.timedLock(s2ns(1));
1121 const bool locked = (err == NO_ERROR);
1122 if (!locked) {
1123 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1124 return TIMED_OUT;
1125 }
1126
1127 outLayers->clear();
1128 mCurrentState.traverseInZOrder([&](Layer* layer) {
1129 outLayers->push_back(layer->getLayerDebugInfo());
1130 });
1131
1132 mStateLock.unlock();
1133 return NO_ERROR;
1134}
1135
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001136// ----------------------------------------------------------------------------
1137
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001138sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1139 ISurfaceComposer::VsyncSource vsyncSource) {
1140 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1141 return mSFEventThread->createEventConnection();
1142 } else {
1143 return mEventThread->createEventConnection();
1144 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001145}
1146
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001147// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001148
1149void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001150 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001151}
1152
1153void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001154 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001155}
1156
1157void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001158 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001159}
1160
1161void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001162 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001163 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001164}
1165
1166status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001167 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001168 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001169}
1170
1171status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001172 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001173 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001174 if (res == NO_ERROR) {
1175 msg->wait();
1176 }
1177 return res;
1178}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001179
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001180void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001181 do {
1182 waitForEvent();
1183 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001184}
1185
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001186void SurfaceFlinger::enableHardwareVsync() {
1187 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001188 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001189 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001190 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001191 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001192 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001193}
1194
Jesse Hall948fe0c2013-10-14 12:56:09 -07001195void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001196 Mutex::Autolock _l(mHWVsyncLock);
1197
Jesse Hall948fe0c2013-10-14 12:56:09 -07001198 if (makeAvailable) {
1199 mHWVsyncAvailable = true;
1200 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001201 // Hardware vsync is not currently available, so abort the resync
1202 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001203 return;
1204 }
1205
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001206 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1207 if (!getHwComposer().isConnected(displayId)) {
1208 return;
1209 }
1210
1211 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001212 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001213
Lloyd Pique41be5d22018-06-21 13:11:48 -07001214 mPrimaryDispSync->reset();
1215 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001216
1217 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001218 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001219 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001220 mPrimaryHWVsyncEnabled = true;
1221 }
1222}
1223
Jesse Hall948fe0c2013-10-14 12:56:09 -07001224void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001225 Mutex::Autolock _l(mHWVsyncLock);
1226 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001227 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001228 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001229 mPrimaryHWVsyncEnabled = false;
1230 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001231 if (makeUnavailable) {
1232 mHWVsyncAvailable = false;
1233 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001234}
1235
Tim Murray4a4e4a22016-04-19 16:29:23 +00001236void SurfaceFlinger::resyncWithRateLimit() {
1237 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001238
1239 // No explicit locking is needed here since EventThread holds a lock while calling this method
1240 static nsecs_t sLastResyncAttempted = 0;
1241 const nsecs_t now = systemTime();
1242 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001243 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001244 }
Dan Stoza57164302017-05-08 14:03:54 -07001245 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001246}
1247
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001248void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1249 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001250 ATRACE_NAME("SF onVsync");
1251
Steven Thomas3cfac282017-02-06 12:29:30 -08001252 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001253 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001254 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001255 return;
1256 }
1257
1258 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001259 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001260 return;
1261 }
1262
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001263 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1264 // For now, we don't do anything with external display vsyncs.
1265 return;
1266 }
1267
Jamie Gennisd1700752013-10-14 12:22:52 -07001268 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001269
Jamie Gennisd1700752013-10-14 12:22:52 -07001270 { // Scope for the lock
1271 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001272 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001273 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001274 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001275 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001276
1277 if (needsHwVsync) {
1278 enableHardwareVsync();
1279 } else {
1280 disableHardwareVsync(false);
1281 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001282}
1283
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001284void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001285 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1286 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001287}
1288
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001289void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001290 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001291 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001292 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001293
Lloyd Piqueba04e622017-12-14 17:11:26 -08001294 // Ignore events that do not have the right sequenceId.
1295 if (sequenceId != getBE().mComposerSequenceId) {
1296 return;
1297 }
1298
Steven Thomasb02664d2017-07-26 18:48:28 -07001299 // Only lock if we're not on the main thread. This function is normally
1300 // called on a hwbinder thread, but for the primary display it's called on
1301 // the main thread with the state lock already held, so don't attempt to
1302 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001303 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001304
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001305 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001306
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001307 if (std::this_thread::get_id() == mMainThreadId) {
1308 // Process all pending hot plug events immediately if we are on the main thread.
1309 processDisplayHotplugEventsLocked();
1310 }
1311
Lloyd Piqueba04e622017-12-14 17:11:26 -08001312 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001313}
1314
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001315void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001316 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001317 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001318 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001319 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001320 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001321}
1322
Dan Stoza9e56aa02015-11-02 13:00:03 -08001323void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001324 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001325 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001326 getHwComposer().setVsyncEnabled(disp,
1327 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001328}
1329
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001330// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001331void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001332 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001333 // Clear the drawing state so that the logic inside of
1334 // handleTransactionLocked will fire. It will determine the delta between
1335 // mCurrentState and mDrawingState and re-apply all changes when we make the
1336 // transition.
1337 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001338 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001339 mDisplays.clear();
1340}
1341
Steven Thomas050b2c82017-03-06 11:45:16 -08001342void SurfaceFlinger::updateVrFlinger() {
1343 if (!mVrFlinger)
1344 return;
1345 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001346 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001347 return;
1348 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001349
David Sodman105b7dc2017-11-04 20:28:14 -07001350 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001351 ALOGE("Vr flinger is only supported for remote hardware composer"
1352 " service connections. Ignoring request to transition to vr"
1353 " flinger.");
1354 mVrFlingerRequestsDisplay = false;
1355 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001356 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001357
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001358 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001359
Steven Thomas0123ac62018-07-12 11:32:34 -07001360 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001361 LOG_ALWAYS_FATAL_IF(!display);
1362 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001363 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1364 // called below. Clear the reference now so we don't accidentally use it
1365 // later.
1366 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001367
Steven Thomasb02664d2017-07-26 18:48:28 -07001368 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001369 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001370 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001371
Steven Thomasb02664d2017-07-26 18:48:28 -07001372 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001373 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001374 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1375 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001376 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001377
David Sodman105b7dc2017-11-04 20:28:14 -07001378 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1379 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001380
1381 if (vrFlingerRequestsDisplay) {
1382 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001383 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001384
1385 mVisibleRegionsDirty = true;
1386 invalidateHwcGeometry();
1387
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001388 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001389 display = getDefaultDisplayDeviceLocked();
1390 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001391 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001392
Steven Thomasb02664d2017-07-26 18:48:28 -07001393 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001394 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001395 const nsecs_t period = activeConfig->getVsyncPeriod();
1396 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001397
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001398 // The present fences returned from vr_hwc are not an accurate
1399 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001400 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1401 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001402
Steven Thomasb02664d2017-07-26 18:48:28 -07001403 // Use phase of 0 since phase is not known.
1404 // Use latency of 0, which will snap to the ideal latency.
1405 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001406
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001407 resyncToHardwareVsync(false);
1408
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001409 android_atomic_or(1, &mRepaintEverything);
1410 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001411}
1412
Mathias Agopian4fec8732012-06-29 14:12:52 -07001413void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001414 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001415 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001416 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001417 bool frameMissed = !mHadClientComposition &&
1418 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001419 (mPreviousPresentFence->getSignalTime() ==
1420 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001421 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001422 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001423 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001424 mTimeStats.incrementMissedFrames();
1425 if (mPropagateBackpressure) {
1426 signalLayerUpdate();
1427 break;
1428 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001429 }
Dan Stoza50182882016-07-08 12:02:20 -07001430
Steven Thomas050b2c82017-03-06 11:45:16 -08001431 // Now that we're going to make it to the handleMessageTransaction()
1432 // call below it's safe to call updateVrFlinger(), which will
1433 // potentially trigger a display handoff.
1434 updateVrFlinger();
1435
Dan Stoza6b9454d2014-11-07 16:00:59 -08001436 bool refreshNeeded = handleMessageTransaction();
1437 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001438 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001439 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001440 // Signal a refresh if a transaction modified the window state,
1441 // a new buffer was latched, or if HWC has requested a full
1442 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001443 signalRefresh();
1444 }
1445 break;
1446 }
1447 case MessageQueue::REFRESH: {
1448 handleMessageRefresh();
1449 break;
1450 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001451 }
1452}
1453
Dan Stoza6b9454d2014-11-07 16:00:59 -08001454bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001455 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001456 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001457 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001458 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001459 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001460 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001461}
1462
Dan Stoza6b9454d2014-11-07 16:00:59 -08001463bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001464 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001465 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001466}
1467
1468void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001469 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001470
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001471 mRefreshPending = false;
1472
David Sodman2b406362017-12-15 13:33:47 -08001473 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001474 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001475 calculateWorkingSet();
David Sodman2b406362017-12-15 13:33:47 -08001476 beginFrame();
1477 prepareFrame();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001478 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001479 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001480 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001481 doComposition();
David Sodman2b406362017-12-15 13:33:47 -08001482 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001483
Dan Stozabfbffeb2016-07-21 14:49:33 -07001484 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001485 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001486 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001487 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001488 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001489 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001490
Dan Stoza9e56aa02015-11-02 13:00:03 -08001491 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001492}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001493
David Sodman79bba0e2018-08-05 18:07:49 -07001494void SurfaceFlinger::calculateWorkingSet() {
1495 ATRACE_CALL();
1496 ALOGV(__FUNCTION__);
1497
David Sodman79bba0e2018-08-05 18:07:49 -07001498 // build the h/w work list
1499 if (CC_UNLIKELY(mGeometryInvalid)) {
1500 mGeometryInvalid = false;
1501 for (const auto& [token, display] : mDisplays) {
1502 const auto displayId = display->getId();
1503 if (displayId >= 0) {
1504 const Vector<sp<Layer>>& currentLayers(
1505 display->getVisibleLayersSortedByZ());
1506 for (size_t i = 0; i < currentLayers.size(); i++) {
1507 const auto& layer = currentLayers[i];
1508
1509 if (!layer->hasHwcLayer(displayId)) {
1510 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1511 layer->forceClientComposition(displayId);
1512 continue;
1513 }
1514 }
1515
1516 layer->setGeometry(display, i);
1517 if (mDebugDisableHWC || mDebugRegion) {
1518 layer->forceClientComposition(displayId);
1519 }
1520 }
1521 }
1522 }
1523 }
1524
1525 // Set the per-frame data
1526 for (const auto& [token, display] : mDisplays) {
1527 const auto displayId = display->getId();
1528 if (displayId < 0) {
1529 continue;
1530 }
1531
1532 if (mDrawingState.colorMatrixChanged) {
1533 display->setColorTransform(mDrawingState.colorMatrix);
1534 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1535 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1536 "display %d: %d", displayId, result);
1537 }
1538 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1539 if (layer->isHdrY410()) {
1540 layer->forceClientComposition(displayId);
1541 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1542 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1543 !display->hasHDR10Support()) {
1544 layer->forceClientComposition(displayId);
1545 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1546 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1547 !display->hasHLGSupport()) {
1548 layer->forceClientComposition(displayId);
1549 }
1550
1551 if (layer->getForceClientComposition(displayId)) {
1552 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1553 layer->setCompositionType(displayId, HWC2::Composition::Client);
1554 continue;
1555 }
1556
1557 layer->setPerFrameData(display);
1558 }
1559
1560 if (hasWideColorDisplay) {
1561 ColorMode colorMode;
1562 Dataspace dataSpace;
1563 RenderIntent renderIntent;
1564 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1565 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1566 }
1567 }
1568
1569 mDrawingState.colorMatrixChanged = false;
David Sodman79bba0e2018-08-05 18:07:49 -07001570}
1571
Mathias Agopiancd60f992012-08-16 16:28:27 -07001572void SurfaceFlinger::doDebugFlashRegions()
1573{
1574 // is debugging enabled
1575 if (CC_LIKELY(!mDebugRegion))
1576 return;
1577
1578 const bool repaintEverything = mRepaintEverything;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001579 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001580 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001581 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001582 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001583 if (!dirtyRegion.isEmpty()) {
1584 // redraw the whole screen
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001585 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001586
1587 // and draw the dirty region
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001588 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001589 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001590 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1591
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001592 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001593 }
1594 }
1595 }
1596
1597 postFramebuffer();
1598
1599 if (mDebugRegion > 1) {
1600 usleep(mDebugRegion * 1000);
1601 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001602
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001603 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001604 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001605 continue;
1606 }
1607
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001608 status_t result = display->prepareFrame(*getBE().mHwc);
1609 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001610 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001611 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001612}
1613
Adrian Roos1e1a1282017-11-01 19:05:31 +01001614void SurfaceFlinger::doTracing(const char* where) {
1615 ATRACE_CALL();
1616 ATRACE_NAME(where);
1617 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001618 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001619 }
1620}
1621
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001622void SurfaceFlinger::logLayerStats() {
1623 ATRACE_CALL();
1624 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001625 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001626 if (display->isPrimary()) {
1627 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001628 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001629 }
1630 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001631
1632 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001633 }
1634}
1635
David Sodman2b406362017-12-15 13:33:47 -08001636void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001637{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001638 ATRACE_CALL();
1639 ALOGV("preComposition");
1640
David Sodman2b406362017-12-15 13:33:47 -08001641 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1642
Mathias Agopiancd60f992012-08-16 16:28:27 -07001643 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001644 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001645 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001646 needExtraInvalidate = true;
1647 }
Robert Carr2047fae2016-11-28 14:09:09 -08001648 });
1649
Mathias Agopiancd60f992012-08-16 16:28:27 -07001650 if (needExtraInvalidate) {
1651 signalLayerUpdate();
1652 }
1653}
1654
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001655void SurfaceFlinger::updateCompositorTiming(
1656 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1657 std::shared_ptr<FenceTime>& presentFenceTime) {
1658 // Update queue of past composite+present times and determine the
1659 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001660 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001661 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001662 while (!getBE().mCompositePresentTimes.empty()) {
1663 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001664 // Cached values should have been updated before calling this method,
1665 // which helps avoid duplicate syscalls.
1666 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1667 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1668 break;
1669 }
1670 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001671 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001672 }
1673
1674 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001675 while (getBE().mCompositePresentTimes.size() > 16) {
1676 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001677 }
1678
Brian Andersond0010582017-03-07 13:20:31 -08001679 setCompositorTimingSnapped(
1680 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1681}
1682
1683void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1684 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001685 // Integer division and modulo round toward 0 not -inf, so we need to
1686 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001687 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001688 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1689 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1690
Brian Andersond0010582017-03-07 13:20:31 -08001691 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1692 if (idealLatency <= 0) {
1693 idealLatency = vsyncInterval;
1694 }
1695
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001696 // Snap the latency to a value that removes scheduling jitter from the
1697 // composition and present times, which often have >1ms of jitter.
1698 // Reducing jitter is important if an app attempts to extrapolate
1699 // something (such as user input) to an accurate diasplay time.
1700 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1701 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001702 nsecs_t bias = vsyncInterval / 2;
1703 int64_t extraVsyncs =
1704 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1705 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1706 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001707
David Sodman99974d22017-11-28 12:04:33 -08001708 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1709 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1710 getBE().mCompositorTiming.interval = vsyncInterval;
1711 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001712}
1713
David Sodman2b406362017-12-15 13:33:47 -08001714void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001715{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001716 ATRACE_CALL();
1717 ALOGV("postComposition");
1718
Brian Anderson3546a3f2016-07-14 11:51:14 -07001719 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001720 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001721 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001722 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001723 }
1724
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001725 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001726 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001727
David Sodman73beded2017-11-15 11:56:06 -08001728 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001729 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001730 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001731 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001732 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001733 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001734 } else {
1735 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1736 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001737
David Sodman73beded2017-11-15 11:56:06 -08001738 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001739 mPreviousPresentFence =
1740 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1741 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001742 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001743
Lloyd Pique41be5d22018-06-21 13:11:48 -07001744 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1745 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001746
David Sodman2b406362017-12-15 13:33:47 -08001747 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001748 // when we started doing work for this frame, but that should be okay
1749 // since updateCompositorTiming has snapping logic.
1750 updateCompositorTiming(
David Sodman2b406362017-12-15 13:33:47 -08001751 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001752 CompositorTiming compositorTiming;
1753 {
David Sodman99974d22017-11-28 12:04:33 -08001754 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1755 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001756 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001757
Robert Carr2047fae2016-11-28 14:09:09 -08001758 mDrawingState.traverseInZOrder([&](Layer* layer) {
1759 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001760 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001761 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001762 recordBufferingStats(layer->getName().string(),
1763 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001764 }
Robert Carr2047fae2016-11-28 14:09:09 -08001765 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001766
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001767 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001768 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001769 enableHardwareVsync();
1770 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001771 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001772 }
1773 }
1774
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001775 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001776 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001777 enableHardwareVsync();
1778 }
1779 }
1780
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001781 if (mAnimCompositionPending) {
1782 mAnimCompositionPending = false;
1783
Brian Anderson4e606e32017-03-16 15:34:57 -07001784 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001785 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001786 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001787 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001788 // The HWC doesn't support present fences, so use the refresh
1789 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001790 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001791 mAnimFrameTracker.setActualPresentTime(presentTime);
1792 }
1793 mAnimFrameTracker.advanceFrame();
1794 }
Dan Stozab90cf072015-03-05 11:05:59 -08001795
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001796 mTimeStats.incrementTotalFrames();
1797 if (mHadClientComposition) {
1798 mTimeStats.incrementClientCompositionFrames();
1799 }
1800
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001801 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001802 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001803 return;
1804 }
1805
1806 nsecs_t currentTime = systemTime();
1807 if (mHasPoweredOff) {
1808 mHasPoweredOff = false;
1809 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001810 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001811 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001812 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1813 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001814 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001815 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001816 }
David Sodman4a36e932017-11-07 14:29:47 -08001817 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001818 }
David Sodman4a36e932017-11-07 14:29:47 -08001819 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001820
1821 {
1822 std::lock_guard lock(mTexturePoolMutex);
1823 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1824 if (refillCount > 0) {
1825 const size_t offset = mTexturePool.size();
1826 mTexturePool.resize(mTexturePoolSize);
1827 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1828 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1829 }
1830 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001831}
1832
1833void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001834 ATRACE_CALL();
1835 ALOGV("rebuildLayerStacks");
1836
Mathias Agopiancd60f992012-08-16 16:28:27 -07001837 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001838 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001839 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001840 mVisibleRegionsDirty = false;
1841 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001842
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001843 for (const auto& pair : mDisplays) {
1844 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001845 Region opaqueRegion;
1846 Region dirtyRegion;
1847 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001848 Vector<sp<Layer>> layersNeedingFences;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001849 const Transform& tr = display->getTransform();
1850 const Rect bounds = display->getBounds();
1851 if (display->isPoweredOn()) {
1852 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001853
Jeff Sharkey76488112017-02-27 14:15:18 -07001854 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001855 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001856 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001857 Region drawRegion(tr.transform(
1858 layer->visibleNonTransparentRegion));
1859 drawRegion.andSelf(bounds);
1860 if (!drawRegion.isEmpty()) {
1861 layersSortedByZ.add(layer);
1862 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001863 // Clear out the HWC layer if this layer was
1864 // previously visible, but no longer is
1865 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001866 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001867 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001868 // WM changes display->layerStack upon sleep/awake.
1869 // Here we make sure we delete the HWC layers even if
1870 // WM changed their layer stack.
1871 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001872 }
1873
1874 // If a layer is not going to get a release fence because
1875 // it is invisible, but it is also going to release its
1876 // old buffer, add it to the list of layers needing
1877 // fences.
1878 if (hwcLayerDestroyed) {
1879 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1880 mLayersWithQueuedFrames.cend(), layer);
1881 if (found != mLayersWithQueuedFrames.cend()) {
1882 layersNeedingFences.add(layer);
1883 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001884 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001885 });
1886 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001887 display->setVisibleLayersSortedByZ(layersSortedByZ);
1888 display->setLayersNeedingFences(layersNeedingFences);
1889 display->undefinedRegion.set(bounds);
1890 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1891 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001892 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001893 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001894}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001895
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001896// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001897// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001898// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001899// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001900// The returned HDR data space is one of
1901// - Dataspace::UNKNOWN
1902// - Dataspace::BT2020_HLG
1903// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001904Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1905 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001906 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001907 *outHdrDataSpace = Dataspace::UNKNOWN;
1908
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001909 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001910 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001911 case Dataspace::V0_SCRGB:
1912 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001913 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001914 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001915 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001916 case Dataspace::BT2020_PQ:
1917 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001918 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001919 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001920 case Dataspace::BT2020_HLG:
1921 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001922 // When there's mixed PQ content and HLG content, we set the HDR
1923 // data space to be BT2020_PQ and convert HLG to PQ.
1924 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1925 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001926 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001927 break;
1928 default:
1929 break;
1930 }
Romain Guy54f154a2017-10-24 21:40:32 +01001931 }
1932
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001933 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001934}
1935
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001936// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001937void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1938 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001939 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1940 *outMode = ColorMode::NATIVE;
1941 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001942 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001943 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001944 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001945
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001946 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001947 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001948
Peiyong Lindfde5112018-06-05 10:58:41 -07001949 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001950 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001951 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001952 if (isHdr) {
1953 bestDataSpace = hdrDataSpace;
1954 }
1955
Chia-I Wu0d711262018-05-21 15:19:35 -07001956 RenderIntent intent;
1957 switch (mDisplayColorSetting) {
1958 case DisplayColorSetting::MANAGED:
1959 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001960 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001961 break;
1962 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001963 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001964 break;
1965 default: // vendor display color setting
1966 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1967 break;
1968 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001969
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001970 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001971}
1972
David Sodman2b406362017-12-15 13:33:47 -08001973void SurfaceFlinger::beginFrame()
1974{
1975 for (const auto& [token, display] : mDisplays) {
1976 bool dirty = !display->getDirtyRegion(mRepaintEverything).isEmpty();
1977 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
1978 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
1979
1980 // If nothing has changed (!dirty), don't recompose.
1981 // If something changed, but we don't currently have any visible layers,
1982 // and didn't when we last did a composition, then skip it this time.
1983 // The second rule does two things:
1984 // - When all layers are removed from a display, we'll emit one black
1985 // frame, then nothing more until we get new layers.
1986 // - When a display is created with a private layer stack, we won't
1987 // emit any black frames until a layer is added to the layer stack.
1988 bool mustRecompose = dirty && !(empty && wasEmpty);
1989
1990 ALOGV_IF(display->isVirtual(), "Display %d: %s composition (%sdirty %sempty %swasEmpty)",
1991 display->getId(), mustRecompose ? "doing" : "skipping", dirty ? "+" : "-",
1992 empty ? "+" : "-", wasEmpty ? "+" : "-");
1993
1994 display->beginFrame(mustRecompose);
1995
1996 if (mustRecompose) {
1997 display->lastCompositionHadVisibleLayers = !empty;
1998 }
1999 }
2000}
2001
2002void SurfaceFlinger::prepareFrame()
2003{
2004 for (const auto& [token, display] : mDisplays) {
2005 if (!display->isPoweredOn()) {
2006 continue;
2007 }
2008
2009 status_t result = display->prepareFrame(*getBE().mHwc);
2010 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
2011 display->getId(), result, strerror(-result));
2012 }
2013}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002014
Mathias Agopiancd60f992012-08-16 16:28:27 -07002015void SurfaceFlinger::doComposition() {
2016 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002017 ALOGV("doComposition");
2018
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002019 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002020 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002021 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002022 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002023 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002024
2025 // repaint the framebuffer (if needed)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002026 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002027
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002028 display->dirtyRegion.clear();
2029 display->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002030 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002031 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002032 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002033}
2034
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002035void SurfaceFlinger::postFramebuffer()
2036{
Mathias Agopian841cde52012-03-01 15:44:37 -08002037 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002038 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002039
Mathias Agopiana44b0412011-10-16 18:46:35 -07002040 const nsecs_t now = systemTime();
2041 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002042
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002043 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002044 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002045 continue;
2046 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07002047 const auto displayId = display->getId();
2048 if (displayId >= 0) {
2049 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002050 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002051 display->onSwapBuffersCompleted();
2052 display->makeCurrent();
2053 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002054 sp<Fence> releaseFence = Fence::NO_FENCE;
2055
Chia-I Wu7b549592017-11-15 09:14:57 -08002056 // The layer buffer from the previous frame (if any) is released
2057 // by HWC only when the release fence from this frame (if any) is
2058 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002059 auto hwcLayer = layer->getHwcLayer(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002060 if (displayId >= 0) {
2061 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
2062 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002063
2064 // If the layer was client composited in the previous frame, we
2065 // need to merge with the previous client target acquire fence.
2066 // Since we do not track that, always merge with the current
2067 // client target acquire fence when it is available, even though
2068 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002069 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002070 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002071 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002072 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002073
David Sodmanb8af7922017-12-21 15:17:55 -08002074 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002075 }
Chia-I Wu83806892017-11-16 10:50:20 -08002076
2077 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002078 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002079 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002080 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002081 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002082 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002083 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002084 }
2085 }
2086
Dominik Laskowski7e045462018-05-30 13:02:02 -07002087 if (displayId >= 0) {
2088 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002089 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002090 }
2091
Mathias Agopiana44b0412011-10-16 18:46:35 -07002092 mLastSwapBufferTime = systemTime() - now;
2093 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002094
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002095 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002096 const auto display = getDefaultDisplayDeviceLocked();
2097 if (display && getHwComposer().isConnected(display->getId())) {
2098 const uint32_t flipCount = display->getPageFlipCount();
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002099 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2100 logFrameStats();
2101 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002102 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002103}
2104
Mathias Agopian87baae12012-07-31 12:38:26 -07002105void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002106{
Mathias Agopian841cde52012-03-01 15:44:37 -08002107 ATRACE_CALL();
2108
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002109 // here we keep a copy of the drawing state (that is the state that's
2110 // going to be overwritten by handleTransactionLocked()) outside of
2111 // mStateLock so that the side-effects of the State assignment
2112 // don't happen with mStateLock held (which can cause deadlocks).
2113 State drawingState(mDrawingState);
2114
Mathias Agopianca4d3602011-05-19 15:38:14 -07002115 Mutex::Autolock _l(mStateLock);
2116 const nsecs_t now = systemTime();
2117 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002118
Mathias Agopianca4d3602011-05-19 15:38:14 -07002119 // Here we're guaranteed that some transaction flags are set
2120 // so we can call handleTransactionLocked() unconditionally.
2121 // We call getTransactionFlags(), which will also clear the flags,
2122 // with mStateLock held to guarantee that mCurrentState won't change
2123 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002124
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002125 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002126 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002127 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002128
Mathias Agopianca4d3602011-05-19 15:38:14 -07002129 mLastTransactionTime = systemTime() - now;
2130 mDebugInTransaction = 0;
2131 invalidateHwcGeometry();
2132 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002133}
2134
Dominik Laskowski7e045462018-05-30 13:02:02 -07002135DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002136 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002137 // Figure out whether the event is for the primary display or an
2138 // external display by matching the Hwc display id against one for a
2139 // connected display. If we did not find a match, we then check what
2140 // displays are not already connected to determine the type. If we don't
2141 // have a connected primary display, we assume the new display is meant to
2142 // be the primary display, and then if we don't have an external display,
2143 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002144 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2145 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002146 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002147 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002148 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002149 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002150 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002151 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002152 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002153 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002154 return DisplayDevice::DISPLAY_EXTERNAL;
2155 }
2156
2157 return DisplayDevice::DISPLAY_ID_INVALID;
2158}
2159
Lloyd Piqueba04e622017-12-14 17:11:26 -08002160void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2161 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002162 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002163 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002164 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002165 continue;
2166 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002167
2168 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2169 ALOGE("External displays are not supported by the vr hardware composer.");
2170 continue;
2171 }
2172
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002173 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002174 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002175 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002176 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002177 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002178
2179 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002180 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002181 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002182 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002183 DisplayDeviceState info;
2184 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002185 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2186 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002187 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002188 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002189 mInterceptor->saveDisplayCreation(info);
2190 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002191 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002192 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002193
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002194 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002195 if (idx >= 0) {
2196 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002197 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002198 mCurrentState.displays.removeItemsAt(idx);
2199 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002200 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002201 }
2202
2203 processDisplayChangesLocked();
2204 }
2205
2206 mPendingHotplugEvents.clear();
2207}
2208
Lloyd Pique99d3da52018-01-22 17:48:03 -08002209sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002210 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002211 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002212 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002213 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002214 HdrCapabilities hdrCapabilities;
2215 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002216
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002217 if (hasWideColorDisplay && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002218 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002219 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002220 if (isWideColorMode(colorMode)) {
2221 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002222 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002223
Dominik Laskowski7e045462018-05-30 13:02:02 -07002224 std::vector<RenderIntent> renderIntents =
2225 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002226 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002227 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002228
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002229 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2230 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2231 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002232
2233 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2234 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2235
2236 /*
2237 * Create our display's surface
2238 */
2239 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2240 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002241 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002242 renderSurface->setNativeWindow(nativeWindow.get());
2243 const int displayWidth = renderSurface->queryWidth();
2244 const int displayHeight = renderSurface->queryHeight();
2245
2246 // Make sure that composition can never be stalled by a virtual display
2247 // consumer that isn't processing buffers fast enough. We have to do this
2248 // in two places:
2249 // * Here, in case the display is composed entirely by HWC.
2250 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2251 // window's swap interval in eglMakeCurrent, so they'll override the
2252 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002253 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002254 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2255 }
2256
2257 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002258 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002259
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002260 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002261 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2262 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2263 displayHeight, hasWideColorGamut, hdrCapabilities,
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002264 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002265
2266 if (maxFrameBufferAcquiredBuffers >= 3) {
2267 nativeWindowSurface->preallocateBuffers();
2268 }
2269
2270 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002271 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2272 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002273 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002274 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002275 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002276 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002277 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002278 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002279 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002280 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002281 display->setLayerStack(state.layerStack);
2282 display->setProjection(state.orientation, state.viewport, state.frame);
2283 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002284
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002285 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002286}
2287
Lloyd Pique347200f2017-12-14 17:00:15 -08002288void SurfaceFlinger::processDisplayChangesLocked() {
2289 // here we take advantage of Vector's copy-on-write semantics to
2290 // improve performance by skipping the transaction entirely when
2291 // know that the lists are identical
2292 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2293 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2294 if (!curr.isIdenticalTo(draw)) {
2295 mVisibleRegionsDirty = true;
2296 const size_t cc = curr.size();
2297 size_t dc = draw.size();
2298
2299 // find the displays that were removed
2300 // (ie: in drawing state but not in current state)
2301 // also handle displays that changed
2302 // (ie: displays that are in both lists)
2303 for (size_t i = 0; i < dc;) {
2304 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2305 if (j < 0) {
2306 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002307 // Call makeCurrent() on the primary display so we can
2308 // be sure that nothing associated with this display
2309 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002310 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2311 defaultDisplay->makeCurrent();
2312 }
2313 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2314 display->disconnect(getHwComposer());
2315 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002316 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2317 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2318 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2319 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2320 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002321 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002322 } else {
2323 // this display is in both lists. see if something changed.
2324 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002325 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002326 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2327 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2328 if (state_binder != draw_binder) {
2329 // changing the surface is like destroying and
2330 // recreating the DisplayDevice, so we just remove it
2331 // from the drawing state, so that it get re-added
2332 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002333 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2334 display->disconnect(getHwComposer());
2335 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002336 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002337 mDrawingState.displays.removeItemsAt(i);
2338 dc--;
2339 // at this point we must loop to the next item
2340 continue;
2341 }
2342
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002343 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002344 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002345 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002346 }
2347 if ((state.orientation != draw[i].orientation) ||
2348 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002349 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002350 }
2351 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002352 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002353 }
2354 }
2355 }
2356 ++i;
2357 }
2358
2359 // find displays that were added
2360 // (ie: in current state but not in drawing state)
2361 for (size_t i = 0; i < cc; i++) {
2362 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2363 const DisplayDeviceState& state(curr[i]);
2364
2365 sp<DisplaySurface> dispSurface;
2366 sp<IGraphicBufferProducer> producer;
2367 sp<IGraphicBufferProducer> bqProducer;
2368 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002369 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002370
Dominik Laskowski7e045462018-05-30 13:02:02 -07002371 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002372 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002373 // Virtual displays without a surface are dormant:
2374 // they have external state (layer stack, projection,
2375 // etc.) but no internal state (i.e. a DisplayDevice).
2376 if (state.surface != nullptr) {
2377 // Allow VR composer to use virtual displays.
2378 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2379 int width = 0;
2380 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2381 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2382 int height = 0;
2383 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2384 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2385 int intFormat = 0;
2386 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2387 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002388 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002389
Dominik Laskowski7e045462018-05-30 13:02:02 -07002390 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2391 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002392 }
2393
2394 // TODO: Plumb requested format back up to consumer
2395
2396 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002397 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002398 bqProducer, bqConsumer,
2399 state.displayName);
2400
2401 dispSurface = vds;
2402 producer = vds;
2403 }
2404 } else {
2405 ALOGE_IF(state.surface != nullptr,
2406 "adding a supported display, but rendering "
2407 "surface is provided (%p), ignoring it",
2408 state.surface.get());
2409
Dominik Laskowski7e045462018-05-30 13:02:02 -07002410 displayId = state.type;
2411 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002412 producer = bqProducer;
2413 }
2414
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002415 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002416 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002417 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002418 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002419 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002420 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002421 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2422 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2423 true);
2424 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2425 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2426 true);
2427 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002428 }
2429 }
2430 }
2431 }
2432 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002433
2434 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002435}
2436
Mathias Agopian87baae12012-07-31 12:38:26 -07002437void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002438{
Dan Stoza7dde5992015-05-22 09:51:44 -07002439 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002440 mCurrentState.traverseInZOrder([](Layer* layer) {
2441 layer->notifyAvailableFrames();
2442 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002443
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002444 /*
2445 * Traversal of the children
2446 * (perform the transaction for each of them if needed)
2447 */
2448
Mathias Agopian3559b072012-08-15 13:46:03 -07002449 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002450 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002451 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002452 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002453
2454 const uint32_t flags = layer->doTransaction(0);
2455 if (flags & Layer::eVisibleRegion)
2456 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002457 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002458 }
2459
2460 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002461 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002462 */
2463
Mathias Agopiane57f2922012-08-09 16:29:12 -07002464 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002465 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002466 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002467 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002468
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002469 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002470 // The transform hint might have changed for some layers
2471 // (either because a display has changed, or because a layer
2472 // as changed).
2473 //
2474 // Walk through all the layers in currentLayers,
2475 // and update their transform hint.
2476 //
2477 // If a layer is visible only on a single display, then that
2478 // display is used to calculate the hint, otherwise we use the
2479 // default display.
2480 //
2481 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2482 // the hint is set before we acquire a buffer from the surface texture.
2483 //
2484 // NOTE: layer transactions have taken place already, so we use their
2485 // drawing state. However, SurfaceFlinger's own transaction has not
2486 // happened yet, so we must use the current state layer list
2487 // (soon to become the drawing state list).
2488 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002489 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002490 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002491 bool first = true;
2492 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002493 // NOTE: we rely on the fact that layers are sorted by
2494 // layerStack first (so we don't have to traverse the list
2495 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002496 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002497 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002498 currentlayerStack = layerStack;
2499 // figure out if this layerstack is mirrored
2500 // (more than one display) if so, pick the default display,
2501 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002502 hintDisplay = nullptr;
2503 for (const auto& [token, display] : mDisplays) {
2504 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2505 if (hintDisplay) {
2506 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002507 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002508 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002509 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002510 }
2511 }
2512 }
2513 }
Chet Haase91d25932013-04-11 15:24:55 -07002514
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002515 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002516 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2517 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002518
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002519 // could be null when this layer is using a layerStack
2520 // that is not visible on any display. Also can occur at
2521 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002522 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002523 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002524
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002525 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002526 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002527 if (hintDisplay) {
2528 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002529 }
Robert Carr2047fae2016-11-28 14:09:09 -08002530
2531 first = false;
2532 });
Mathias Agopian84300952012-11-21 16:02:13 -08002533 }
2534
2535
Mathias Agopian3559b072012-08-15 13:46:03 -07002536 /*
2537 * Perform our own transaction if needed
2538 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002539
2540 if (mLayersAdded) {
2541 mLayersAdded = false;
2542 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002543 mVisibleRegionsDirty = true;
2544 }
2545
2546 // some layers might have been removed, so
2547 // we need to update the regions they're exposing.
2548 if (mLayersRemoved) {
2549 mLayersRemoved = false;
2550 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002551 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002552 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002553 // this layer is not visible anymore
2554 // TODO: we could traverse the tree from front to back and
2555 // compute the actual visible region
2556 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002557 Region visibleReg;
2558 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002559 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002560 }
Robert Carr2047fae2016-11-28 14:09:09 -08002561 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002562 }
2563
2564 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002565
2566 updateCursorAsync();
2567}
2568
2569void SurfaceFlinger::updateCursorAsync()
2570{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002571 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002572 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002573 continue;
2574 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002575
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002576 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2577 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002578 }
2579 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002580}
2581
2582void SurfaceFlinger::commitTransaction()
2583{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002584 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002585 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002586 for (const auto& l : mLayersPendingRemoval) {
2587 recordBufferingStats(l->getName().string(),
2588 l->getOccupancyHistory(true));
2589 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002590 }
2591 mLayersPendingRemoval.clear();
2592 }
2593
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002594 // If this transaction is part of a window animation then the next frame
2595 // we composite should be considered an animation as well.
2596 mAnimCompositionPending = mAnimTransactionPending;
2597
Mathias Agopian4fec8732012-06-29 14:12:52 -07002598 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002599 // clear the "changed" flags in current state
2600 mCurrentState.colorMatrixChanged = false;
2601
Robert Carr1f0a16a2016-10-24 16:27:39 -07002602 mDrawingState.traverseInZOrder([](Layer* layer) {
2603 layer->commitChildList();
2604 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002605 mTransactionPending = false;
2606 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002607 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002608}
2609
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002610void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2611 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002612 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002613 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002614
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002615 Region aboveOpaqueLayers;
2616 Region aboveCoveredLayers;
2617 Region dirty;
2618
Mathias Agopian87baae12012-07-31 12:38:26 -07002619 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002620
Robert Carr2047fae2016-11-28 14:09:09 -08002621 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002622 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002623 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002624
Jesse Hall01e29052013-02-19 16:13:35 -08002625 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002626 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002627 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002628 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002629
Mathias Agopianab028732010-03-16 16:41:46 -07002630 /*
2631 * opaqueRegion: area of a surface that is fully opaque.
2632 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002633 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002634
2635 /*
2636 * visibleRegion: area of a surface that is visible on screen
2637 * and not fully transparent. This is essentially the layer's
2638 * footprint minus the opaque regions above it.
2639 * Areas covered by a translucent surface are considered visible.
2640 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002641 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002642
2643 /*
2644 * coveredRegion: area of a surface that is covered by all
2645 * visible regions above it (which includes the translucent areas).
2646 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002647 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002648
Jesse Halla8026d22012-09-25 13:25:04 -07002649 /*
2650 * transparentRegion: area of a surface that is hinted to be completely
2651 * transparent. This is only used to tell when the layer has no visible
2652 * non-transparent regions and can be removed from the layer list. It
2653 * does not affect the visibleRegion of this layer or any layers
2654 * beneath it. The hint may not be correct if apps don't respect the
2655 * SurfaceView restrictions (which, sadly, some don't).
2656 */
2657 Region transparentRegion;
2658
Mathias Agopianab028732010-03-16 16:41:46 -07002659
2660 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002661 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002662 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002663 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002664 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002665 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002666 if (!visibleRegion.isEmpty()) {
2667 // Remove the transparent area from the visible region
2668 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002669 if (tr.preserveRects()) {
2670 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002671 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002672 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002673 // transformation too complex, can't do the
2674 // transparent region optimization.
2675 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002676 }
Mathias Agopianab028732010-03-16 16:41:46 -07002677 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002678
Mathias Agopianab028732010-03-16 16:41:46 -07002679 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002680 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002681 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002682 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2683 // the opaque region is the layer's footprint
2684 opaqueRegion = visibleRegion;
2685 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002686 }
2687 }
2688
Robert Carre5f4f692018-01-12 13:12:28 -08002689 if (visibleRegion.isEmpty()) {
2690 layer->clearVisibilityRegions();
2691 return;
2692 }
2693
Mathias Agopianab028732010-03-16 16:41:46 -07002694 // Clip the covered region to the visible region
2695 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2696
2697 // Update aboveCoveredLayers for next (lower) layer
2698 aboveCoveredLayers.orSelf(visibleRegion);
2699
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002700 // subtract the opaque region covered by the layers above us
2701 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002702
2703 // compute this layer's dirty region
2704 if (layer->contentDirty) {
2705 // we need to invalidate the whole region
2706 dirty = visibleRegion;
2707 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002708 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002709 layer->contentDirty = false;
2710 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002711 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002712 * the exposed region consists of two components:
2713 * 1) what's VISIBLE now and was COVERED before
2714 * 2) what's EXPOSED now less what was EXPOSED before
2715 *
2716 * note that (1) is conservative, we start with the whole
2717 * visible region but only keep what used to be covered by
2718 * something -- which mean it may have been exposed.
2719 *
2720 * (2) handles areas that were not covered by anything but got
2721 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002722 */
Mathias Agopianab028732010-03-16 16:41:46 -07002723 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002724 const Region oldVisibleRegion = layer->visibleRegion;
2725 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002726 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2727 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002728 }
2729 dirty.subtractSelf(aboveOpaqueLayers);
2730
2731 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002732 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002733
Mathias Agopianab028732010-03-16 16:41:46 -07002734 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002735 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002736
Jesse Halla8026d22012-09-25 13:25:04 -07002737 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002738 layer->setVisibleRegion(visibleRegion);
2739 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002740 layer->setVisibleNonTransparentRegion(
2741 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002742 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002743
Mathias Agopian87baae12012-07-31 12:38:26 -07002744 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002745}
2746
Chia-I Wuab0c3192017-08-01 11:29:00 -07002747void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002748 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002749 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2750 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002751 }
2752 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002753}
2754
Dan Stoza6b9454d2014-11-07 16:00:59 -08002755bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002756{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002757 ALOGV("handlePageFlip");
2758
Brian Andersond6927fb2016-07-23 23:37:30 -07002759 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002760
Mathias Agopian4fec8732012-06-29 14:12:52 -07002761 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002762 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002763 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002764
2765 // Store the set of layers that need updates. This set must not change as
2766 // buffers are being latched, as this could result in a deadlock.
2767 // Example: Two producers share the same command stream and:
2768 // 1.) Layer 0 is latched
2769 // 2.) Layer 0 gets a new frame
2770 // 2.) Layer 1 gets a new frame
2771 // 3.) Layer 1 is latched.
2772 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2773 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002774 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002775 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002776 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07002777 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002778 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002779 } else {
2780 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002781 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002782 } else {
2783 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002784 }
Robert Carr2047fae2016-11-28 14:09:09 -08002785 });
2786
Dan Stoza9e56aa02015-11-02 13:00:03 -08002787 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002788 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002789 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002790 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002791 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002792 newDataLatched = true;
2793 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002794 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002795
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002796 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002797
2798 // If we will need to wake up at some time in the future to deal with a
2799 // queued frame that shouldn't be displayed during this vsync period, wake
2800 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002801 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002802 signalLayerUpdate();
2803 }
2804
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002805 // enter boot animation on first buffer latch
2806 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2807 ALOGI("Enter boot animation");
2808 mBootStage = BootStage::BOOTANIMATION;
2809 }
2810
Dan Stoza6b9454d2014-11-07 16:00:59 -08002811 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002812 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002813}
2814
Mathias Agopianad456f92011-01-13 17:53:01 -08002815void SurfaceFlinger::invalidateHwcGeometry()
2816{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002817 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002818}
2819
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002820void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2821 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002822 // We only need to actually compose the display if:
2823 // 1) It is being handled by hardware composer, which may need this to
2824 // keep its virtual display state machine in sync, or
2825 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002826 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002827 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002828 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002829 return;
2830 }
2831
Dan Stoza9e56aa02015-11-02 13:00:03 -08002832 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002833 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002834
2835 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002836 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002837}
2838
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002839bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002840 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002841
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002842 const Region bounds(display->bounds());
2843 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002844 const auto displayId = display->getId();
2845 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002846 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002847
Chia-I Wu8e50e692018-05-04 10:12:37 -07002848 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002849 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002850
Dan Stoza9e56aa02015-11-02 13:00:03 -08002851 if (hasClientComposition) {
2852 ALOGV("hasClientComposition");
2853
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002854 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002855 if (display->hasWideColorGamut()) {
2856 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002857 }
2858 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002859 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002860 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002861
Dominik Laskowski7e045462018-05-30 13:02:02 -07002862 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002863 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2864 HWC2::Capability::SkipClientColorTransform);
2865
Chia-I Wud49d6692018-06-27 07:17:41 +08002866 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002867 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2868 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08002869 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002870 }
2871
Chia-I Wud49d6692018-06-27 07:17:41 +08002872 // The current enhanced saturation matrix is designed to enhance Display P3,
2873 // thus we only apply this matrix when the render intent is not colorimetric
2874 // and the output color space is Display P3.
2875 needsEnhancedColorMatrix =
2876 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2877 outputDataspace == Dataspace::DISPLAY_P3);
2878 if (needsEnhancedColorMatrix) {
2879 colorMatrix *= mEnhancedSaturationMatrix;
2880 }
2881
2882 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002883
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002884 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002885 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002886 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002887 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002888
2889 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002890 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2891 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2892 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002893 }
2894 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002895 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002896
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002897 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002898 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002899 // when using overlays, we assume a fully transparent framebuffer
2900 // NOTE: we could reduce how much we need to clear, for instance
2901 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002902 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002903 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002904 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002905 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002906 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002907 // we're left with the letterbox region
2908 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002909 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07002910
2911 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002912 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07002913
Mathias Agopianb9494d52012-04-18 02:28:45 -07002914 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002915 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002916 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002917 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002918 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002919 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002920
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002921 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002922 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002923 // scissor on the main display. It should never be needed
2924 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002925 const Rect& bounds = display->getBounds();
2926 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07002927 if (scissor != bounds) {
2928 // scissor doesn't match the screen's dimensions, so we
2929 // need to clear everything outside of it and enable
2930 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002931
Mathias Agopianf45c5102012-10-24 16:29:17 -07002932 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002933 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002934 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002935 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002936 }
2937 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002938 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002939
Mathias Agopian85d751c2012-08-29 16:59:24 -07002940 /*
2941 * and then, render the layers targeted at the framebuffer
2942 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002943
Dan Stoza9e56aa02015-11-02 13:00:03 -08002944 ALOGV("Rendering client layers");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002945 const Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002946 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002947 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002948 const Region clip(bounds.intersect(
2949 displayTransform.transform(layer->visibleRegion)));
2950 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002951 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002952 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002953 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002954 case HWC2::Composition::Cursor:
2955 case HWC2::Composition::Device:
2956 case HWC2::Composition::Sideband:
2957 case HWC2::Composition::SolidColor: {
2958 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002959 if (layer->getClearClientTarget(displayId) && !firstLayer &&
Rajavenu Kyatham2eae6d32018-04-10 12:34:05 +05302960 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
2961 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002962 // never clear the very first layer since we're
2963 // guaranteed the FB is already cleared
2964 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002965 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002966 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002967 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002968 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002969 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002970 break;
2971 }
2972 default:
2973 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002974 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002975 } else {
2976 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002977 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002978 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002979 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002980
Chia-I Wud49d6692018-06-27 07:17:41 +08002981 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002982 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002983 }
2984
Mathias Agopianf45c5102012-10-24 16:29:17 -07002985 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002986 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002987 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002988}
2989
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002990void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
2991 const Region& region) const {
2992 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002993 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002994 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002995}
2996
Dan Stoza7d89d062015-04-30 13:29:25 -07002997status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002998 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002999 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003000 const sp<Layer>& lbc,
3001 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003002{
Dan Stoza7d89d062015-04-30 13:29:25 -07003003 // add this layer to the current state list
3004 {
3005 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003006 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003007 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3008 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003009 return NO_MEMORY;
3010 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003011 if (parent == nullptr) {
3012 mCurrentState.layersSortedByZ.add(lbc);
3013 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003014 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003015 ALOGE("addClientLayer called with a removed parent");
3016 return NAME_NOT_FOUND;
3017 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003018 parent->addChild(lbc);
3019 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003020
Yiwei Zhang243b3782018-05-15 17:40:04 -07003021 if (gbc != nullptr) {
3022 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3023 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3024 mMaxGraphicBufferProducerListSize,
3025 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3026 mGraphicBufferProducerList.size(),
3027 mMaxGraphicBufferProducerListSize, mNumLayers);
3028 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003029 mLayersAdded = true;
3030 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003031 }
3032
Mathias Agopian96f08192010-06-02 23:28:45 -07003033 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003034 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003035
Dan Stoza7d89d062015-04-30 13:29:25 -07003036 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003037}
3038
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003039status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003040 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003041 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3042}
Robert Carr7f9b8992017-03-10 11:08:39 -08003043
chaviwca27f252018-02-06 16:46:39 -08003044status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3045 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003046 if (layer->isPendingRemoval()) {
3047 return NO_ERROR;
3048 }
3049
Robert Carr1f0a16a2016-10-24 16:27:39 -07003050 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003051 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003052 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003053 if (topLevelOnly) {
3054 return NO_ERROR;
3055 }
3056
Chia-I Wu98f1c102017-05-30 14:54:08 -07003057 sp<Layer> ancestor = p;
3058 while (ancestor->getParent() != nullptr) {
3059 ancestor = ancestor->getParent();
3060 }
3061 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3062 ALOGE("removeLayer called with a layer whose parent has been removed");
3063 return NAME_NOT_FOUND;
3064 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003065
3066 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003067 } else {
3068 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003069 }
3070
Robert Carr136e2f62017-02-08 17:54:29 -08003071 // As a matter of normal operation, the LayerCleaner will produce a second
3072 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3073 // so we will succeed in promoting it, but it's already been removed
3074 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3075 // otherwise something has gone wrong and we are leaking the layer.
3076 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003077 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3078 layer->getName().string(),
3079 (p != nullptr) ? p->getName().string() : "no-parent");
3080 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003081 } else if (index < 0) {
3082 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003083 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003084
Chia-I Wuc6657022017-08-15 11:18:17 -07003085 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003086 mLayersPendingRemoval.add(layer);
3087 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003088 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003089 setTransactionFlags(eTransactionNeeded);
3090 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003091}
3092
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003093uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003094 return android_atomic_release_load(&mTransactionFlags);
3095}
3096
Mathias Agopian3f844832013-08-07 21:24:32 -07003097uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003098 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3099}
3100
Mathias Agopian3f844832013-08-07 21:24:32 -07003101uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003102 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3103}
3104
3105uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3106 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003107 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003108 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003109 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003110 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003111 }
3112 return old;
3113}
3114
chaviwca27f252018-02-06 16:46:39 -08003115bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3116 for (const ComposerState& state : states) {
3117 // Here we need to check that the interface we're given is indeed
3118 // one of our own. A malicious client could give us a nullptr
3119 // IInterface, or one of its own or even one of our own but a
3120 // different type. All these situations would cause us to crash.
3121 if (state.client == nullptr) {
3122 return true;
3123 }
3124
3125 sp<IBinder> binder = IInterface::asBinder(state.client);
3126 if (binder == nullptr) {
3127 return true;
3128 }
3129
3130 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3131 return true;
3132 }
3133 }
3134 return false;
3135}
3136
Mathias Agopian8b33f032012-07-24 20:43:54 -07003137void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003138 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003139 const Vector<DisplayState>& displays,
3140 uint32_t flags)
3141{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003142 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003143 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003144 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003145
chaviwca27f252018-02-06 16:46:39 -08003146 if (containsAnyInvalidClientState(states)) {
3147 return;
3148 }
3149
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003150 if (flags & eAnimation) {
3151 // For window updates that are part of an animation we must wait for
3152 // previous animation "frames" to be handled.
3153 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003154 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003155 if (CC_UNLIKELY(err != NO_ERROR)) {
3156 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003157 // caller after a few seconds.
3158 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3159 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003160 mAnimTransactionPending = false;
3161 break;
3162 }
3163 }
3164 }
3165
chaviwca27f252018-02-06 16:46:39 -08003166 for (const DisplayState& display : displays) {
3167 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003168 }
3169
chaviwca27f252018-02-06 16:46:39 -08003170 for (const ComposerState& state : states) {
3171 transactionFlags |= setClientStateLocked(state);
3172 }
3173
3174 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3175 // as destroyed should only occur after setting all other states. This is to allow for a
3176 // child re-parent to happen before marking its original parent as destroyed (which would
3177 // then mark the child as destroyed).
3178 for (const ComposerState& state : states) {
3179 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003180 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003181
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003182 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3183 // anyway. This can be used as a flush mechanism for previous async transactions.
3184 // Empty animation transaction can be used to simulate back-pressure, so also force a
3185 // transaction for empty animation transactions.
3186 if (transactionFlags == 0 &&
3187 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003188 transactionFlags = eTransactionNeeded;
3189 }
3190
Mathias Agopian386aa982011-11-07 21:58:03 -08003191 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003192 if (mInterceptor->isEnabled()) {
3193 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003194 }
Irvel468051e2016-06-13 16:44:44 -07003195
Mathias Agopian386aa982011-11-07 21:58:03 -08003196 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003197 const auto start = (flags & eEarlyWakeup)
3198 ? VSyncModulator::TransactionStart::EARLY
3199 : VSyncModulator::TransactionStart::NORMAL;
3200 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003201
3202 // if this is a synchronous transaction, wait for it to take effect
3203 // before returning.
3204 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003205 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003206 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003207 if (flags & eAnimation) {
3208 mAnimTransactionPending = true;
3209 }
3210 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003211 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3212 if (CC_UNLIKELY(err != NO_ERROR)) {
3213 // just in case something goes wrong in SF, return to the
3214 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003215 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3216 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003217 break;
3218 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003219 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003220 }
3221}
3222
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003223uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3224 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3225 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003226
Mathias Agopiane57f2922012-08-09 16:29:12 -07003227 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003228 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3229
3230 const uint32_t what = s.what;
3231 if (what & DisplayState::eSurfaceChanged) {
3232 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3233 state.surface = s.surface;
3234 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003235 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003236 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003237 if (what & DisplayState::eLayerStackChanged) {
3238 if (state.layerStack != s.layerStack) {
3239 state.layerStack = s.layerStack;
3240 flags |= eDisplayTransactionNeeded;
3241 }
3242 }
3243 if (what & DisplayState::eDisplayProjectionChanged) {
3244 if (state.orientation != s.orientation) {
3245 state.orientation = s.orientation;
3246 flags |= eDisplayTransactionNeeded;
3247 }
3248 if (state.frame != s.frame) {
3249 state.frame = s.frame;
3250 flags |= eDisplayTransactionNeeded;
3251 }
3252 if (state.viewport != s.viewport) {
3253 state.viewport = s.viewport;
3254 flags |= eDisplayTransactionNeeded;
3255 }
3256 }
3257 if (what & DisplayState::eDisplaySizeChanged) {
3258 if (state.width != s.width) {
3259 state.width = s.width;
3260 flags |= eDisplayTransactionNeeded;
3261 }
3262 if (state.height != s.height) {
3263 state.height = s.height;
3264 flags |= eDisplayTransactionNeeded;
3265 }
3266 }
3267
Mathias Agopiane57f2922012-08-09 16:29:12 -07003268 return flags;
3269}
3270
Robert Carrd4ae7f32018-06-07 16:10:57 -07003271bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3272 IPCThreadState* ipc = IPCThreadState::self();
3273 const int pid = ipc->getCallingPid();
3274 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003275 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulecfbe2c002018-08-09 22:32:45 +00003276 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003277 return false;
3278 }
3279 return true;
3280}
3281
chaviwca27f252018-02-06 16:46:39 -08003282uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3283 const layer_state_t& s = composerState.state;
3284 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3285
Mathias Agopian13127d82013-03-05 17:47:11 -08003286 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003287 if (layer == nullptr) {
3288 return 0;
3289 }
3290
3291 if (layer->isPendingRemoval()) {
3292 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3293 return 0;
3294 }
3295
3296 uint32_t flags = 0;
3297
3298 const uint32_t what = s.what;
3299 bool geometryAppliesWithResize =
3300 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003301
3302 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3303 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003304 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003305 layer->pushPendingState();
3306 }
3307
chaviw8b3871a2017-11-01 17:41:01 -07003308 if (what & layer_state_t::ePositionChanged) {
3309 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3310 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003311 }
chaviw8b3871a2017-11-01 17:41:01 -07003312 }
3313 if (what & layer_state_t::eLayerChanged) {
3314 // NOTE: index needs to be calculated before we update the state
3315 const auto& p = layer->getParent();
3316 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003317 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003318 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003319 mCurrentState.layersSortedByZ.removeAt(idx);
3320 mCurrentState.layersSortedByZ.add(layer);
3321 // we need traversal (state changed)
3322 // AND transaction (list changed)
3323 flags |= eTransactionNeeded|eTraversalNeeded;
3324 }
chaviw8b3871a2017-11-01 17:41:01 -07003325 } else {
3326 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003327 flags |= eTransactionNeeded|eTraversalNeeded;
3328 }
3329 }
chaviw8b3871a2017-11-01 17:41:01 -07003330 }
3331 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003332 // NOTE: index needs to be calculated before we update the state
3333 const auto& p = layer->getParent();
3334 if (p == nullptr) {
3335 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3336 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3337 mCurrentState.layersSortedByZ.removeAt(idx);
3338 mCurrentState.layersSortedByZ.add(layer);
3339 // we need traversal (state changed)
3340 // AND transaction (list changed)
3341 flags |= eTransactionNeeded|eTraversalNeeded;
3342 }
3343 } else {
3344 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3345 flags |= eTransactionNeeded|eTraversalNeeded;
3346 }
chaviw8b3871a2017-11-01 17:41:01 -07003347 }
3348 }
3349 if (what & layer_state_t::eSizeChanged) {
3350 if (layer->setSize(s.w, s.h)) {
3351 flags |= eTraversalNeeded;
3352 }
3353 }
3354 if (what & layer_state_t::eAlphaChanged) {
3355 if (layer->setAlpha(s.alpha))
3356 flags |= eTraversalNeeded;
3357 }
3358 if (what & layer_state_t::eColorChanged) {
3359 if (layer->setColor(s.color))
3360 flags |= eTraversalNeeded;
3361 }
3362 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003363 // TODO: b/109894387
3364 //
3365 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3366 // rotation. To see the problem observe that if we have a square parent, and a child
3367 // of the same size, then we rotate the child 45 degrees around it's center, the child
3368 // must now be cropped to a non rectangular 8 sided region.
3369 //
3370 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3371 // private API, and the WindowManager only uses rotation in one case, which is on a top
3372 // level layer in which cropping is not an issue.
3373 //
3374 // However given that abuse of rotation matrices could lead to surfaces extending outside
3375 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3376 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3377 // transformations.
3378 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003379 flags |= eTraversalNeeded;
3380 }
3381 if (what & layer_state_t::eTransparentRegionChanged) {
3382 if (layer->setTransparentRegionHint(s.transparentRegion))
3383 flags |= eTraversalNeeded;
3384 }
3385 if (what & layer_state_t::eFlagsChanged) {
3386 if (layer->setFlags(s.flags, s.mask))
3387 flags |= eTraversalNeeded;
3388 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003389 if (what & layer_state_t::eCropChanged_legacy) {
3390 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003391 flags |= eTraversalNeeded;
3392 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003393 if (what & layer_state_t::eFinalCropChanged_legacy) {
3394 if (layer->setFinalCrop_legacy(s.finalCrop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003395 flags |= eTraversalNeeded;
3396 }
3397 if (what & layer_state_t::eLayerStackChanged) {
3398 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3399 // We only allow setting layer stacks for top level layers,
3400 // everything else inherits layer stack from its parent.
3401 if (layer->hasParent()) {
3402 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3403 layer->getName().string());
3404 } else if (idx < 0) {
3405 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3406 "that also does not appear in the top level layer list. Something"
3407 " has gone wrong.", layer->getName().string());
3408 } else if (layer->setLayerStack(s.layerStack)) {
3409 mCurrentState.layersSortedByZ.removeAt(idx);
3410 mCurrentState.layersSortedByZ.add(layer);
3411 // we need traversal (state changed)
3412 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003413 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003414 }
3415 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003416 if (what & layer_state_t::eDeferTransaction_legacy) {
3417 if (s.barrierHandle_legacy != nullptr) {
3418 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3419 } else if (s.barrierGbp_legacy != nullptr) {
3420 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003421 if (authenticateSurfaceTextureLocked(gbp)) {
3422 const auto& otherLayer =
3423 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003424 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003425 } else {
3426 ALOGE("Attempt to defer transaction to to an"
3427 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003428 }
3429 }
chaviw8b3871a2017-11-01 17:41:01 -07003430 // We don't trigger a traversal here because if no other state is
3431 // changed, we don't want this to cause any more work
3432 }
3433 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003434 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003435 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003436 if (!hadParent) {
3437 mCurrentState.layersSortedByZ.remove(layer);
3438 }
chaviw8b3871a2017-11-01 17:41:01 -07003439 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003440 }
chaviw8b3871a2017-11-01 17:41:01 -07003441 }
3442 if (what & layer_state_t::eReparentChildren) {
3443 if (layer->reparentChildren(s.reparentHandle)) {
3444 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003445 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003446 }
chaviw8b3871a2017-11-01 17:41:01 -07003447 if (what & layer_state_t::eDetachChildren) {
3448 layer->detachChildren();
3449 }
3450 if (what & layer_state_t::eOverrideScalingModeChanged) {
3451 layer->setOverrideScalingMode(s.overrideScalingMode);
3452 // We don't trigger a traversal here because if no other state is
3453 // changed, we don't want this to cause any more work
3454 }
Marissa Wall61c58622018-07-18 10:12:20 -07003455 if (what & layer_state_t::eTransformChanged) {
3456 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3457 }
3458 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3459 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3460 flags |= eTraversalNeeded;
3461 }
3462 if (what & layer_state_t::eCropChanged) {
3463 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3464 }
3465 if (what & layer_state_t::eBufferChanged) {
3466 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3467 }
3468 if (what & layer_state_t::eAcquireFenceChanged) {
3469 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3470 }
3471 if (what & layer_state_t::eDataspaceChanged) {
3472 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3473 }
3474 if (what & layer_state_t::eHdrMetadataChanged) {
3475 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3476 }
3477 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3478 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3479 }
3480 if (what & layer_state_t::eApiChanged) {
3481 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3482 }
3483 if (what & layer_state_t::eSidebandStreamChanged) {
3484 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3485 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003486 return flags;
3487}
3488
chaviwca27f252018-02-06 16:46:39 -08003489void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3490 const layer_state_t& state = composerState.state;
3491 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3492
3493 sp<Layer> layer(client->getLayerUser(state.surface));
3494 if (layer == nullptr) {
3495 return;
3496 }
3497
3498 if (layer->isPendingRemoval()) {
3499 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3500 return;
3501 }
3502
3503 if (state.what & layer_state_t::eDestroySurface) {
3504 removeLayerLocked(mStateLock, layer);
3505 }
3506}
3507
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003508status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003509 const String8& name,
3510 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003511 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003512 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003513 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003514{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003515 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003516 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003517 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003518 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003519 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003520
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003521 status_t result = NO_ERROR;
3522
3523 sp<Layer> layer;
3524
Cody Northropbc755282017-03-31 12:00:08 -06003525 String8 uniqueName = getUniqueLayerName(name);
3526
Mathias Agopian3165cc22012-08-08 19:42:09 -07003527 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003528 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003529 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3530 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003531
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003532 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003533 case ISurfaceComposerClient::eFXSurfaceBufferState:
3534 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3535 break;
chaviw13fdc492017-06-27 12:40:18 -07003536 case ISurfaceComposerClient::eFXSurfaceColor:
3537 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003538 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003539 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003540 break;
3541 default:
3542 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003543 break;
3544 }
3545
Dan Stoza7d89d062015-04-30 13:29:25 -07003546 if (result != NO_ERROR) {
3547 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003548 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003549
Chia-I Wuab0c3192017-08-01 11:29:00 -07003550 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3551 // TODO b/64227542
3552 if (windowType == 441731) {
3553 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3554 layer->setPrimaryDisplayOnly();
3555 }
3556
Albert Chaulk479c60c2017-01-27 14:21:34 -05003557 layer->setInfo(windowType, ownerUid);
3558
Robert Carr1f0a16a2016-10-24 16:27:39 -07003559 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003560 if (result != NO_ERROR) {
3561 return result;
3562 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003563 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003564
3565 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003566 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003567}
3568
Cody Northropbc755282017-03-31 12:00:08 -06003569String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3570{
3571 bool matchFound = true;
3572 uint32_t dupeCounter = 0;
3573
3574 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3575 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3576
Dan Stoza436ccf32018-06-21 12:10:12 -07003577 // Grab the state lock since we're accessing mCurrentState
3578 Mutex::Autolock lock(mStateLock);
3579
Cody Northropbc755282017-03-31 12:00:08 -06003580 // Loop over layers until we're sure there is no matching name
3581 while (matchFound) {
3582 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003583 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003584 if (layer->getName() == uniqueName) {
3585 matchFound = true;
3586 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3587 }
3588 });
3589 }
3590
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003591 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3592 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003593
3594 return uniqueName;
3595}
3596
Marissa Wallfd668622018-05-10 10:21:13 -07003597status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3598 uint32_t w, uint32_t h, uint32_t flags,
3599 PixelFormat& format, sp<IBinder>* handle,
3600 sp<IGraphicBufferProducer>* gbp,
3601 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003602 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003603 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003604 case PIXEL_FORMAT_TRANSPARENT:
3605 case PIXEL_FORMAT_TRANSLUCENT:
3606 format = PIXEL_FORMAT_RGBA_8888;
3607 break;
3608 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003609 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003610 break;
3611 }
3612
Marissa Wallfd668622018-05-10 10:21:13 -07003613 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3614 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003615 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003616 *handle = layer->getHandle();
3617 *gbp = layer->getProducer();
3618 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003619 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003620
Marissa Wallfd668622018-05-10 10:21:13 -07003621 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003622 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003623}
3624
Marissa Wall61c58622018-07-18 10:12:20 -07003625status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3626 uint32_t w, uint32_t h, uint32_t flags,
3627 sp<IBinder>* handle, sp<Layer>* outLayer) {
3628 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3629 *handle = layer->getHandle();
3630 *outLayer = layer;
3631
3632 return NO_ERROR;
3633}
3634
chaviw13fdc492017-06-27 12:40:18 -07003635status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003636 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003637 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003638{
chaviw13fdc492017-06-27 12:40:18 -07003639 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003640 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003641 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003642}
3643
Mathias Agopianac9fa422013-02-11 16:40:36 -08003644status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003645{
Robert Carr9524cb32017-02-13 11:32:32 -08003646 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003647 status_t err = NO_ERROR;
3648 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003649 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003650 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003651 err = removeLayer(l);
3652 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3653 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003654 }
3655 return err;
3656}
3657
Mathias Agopian13127d82013-03-05 17:47:11 -08003658status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003659{
Mathias Agopian67106042013-03-14 19:18:13 -07003660 // called by ~LayerCleaner() when all references to the IBinder (handle)
3661 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003662 sp<Layer> l = layer.promote();
3663 if (l == nullptr) {
3664 // The layer has already been removed, carry on
3665 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003666 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003667 // If we have a parent, then we can continue to live as long as it does.
3668 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003669}
3670
Mathias Agopianb60314a2012-04-10 22:09:54 -07003671// ---------------------------------------------------------------------------
3672
Andy McFadden13a082e2012-08-24 10:16:42 -07003673void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003674 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3675 if (!displayToken) return;
3676
Jesse Hall01e29052013-02-19 16:13:35 -08003677 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003678 Vector<ComposerState> state;
3679 Vector<DisplayState> displays;
3680 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003681 d.what = DisplayState::eDisplayProjectionChanged |
3682 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003683 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003684 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003685 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003686 d.frame.makeInvalid();
3687 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003688 d.width = 0;
3689 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003690 displays.add(d);
3691 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003692
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003693 const auto display = getDisplayDevice(displayToken);
3694 if (!display) return;
3695
3696 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3697
3698 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003699 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003700 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003701
Brian Andersond0010582017-03-07 13:20:31 -08003702 // Use phase of 0 since phase is not known.
3703 // Use latency of 0, which will snap to the ideal latency.
3704 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003705}
3706
3707void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003708 // Async since we may be called from the main thread.
3709 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003710}
3711
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003712void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3713 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003714 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003715 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003716
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003717 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003718 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003719 return;
3720 }
3721
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003722 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003723 ALOGW("Trying to set power mode for virtual display");
3724 return;
3725 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003726
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003727 display->setPowerMode(mode);
3728
Lloyd Pique4dccc412018-01-22 17:21:36 -08003729 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003730 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003731 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003732 if (idx < 0) {
3733 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3734 return;
3735 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003736 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003737 }
3738
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003739 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003740 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003741 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003742 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003743 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003744 // FIXME: eventthread only knows about the main display right now
3745 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003746 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003747 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003748
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003749 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003750 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003751 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003752
3753 struct sched_param param = {0};
3754 param.sched_priority = 1;
3755 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3756 ALOGW("Couldn't set SCHED_FIFO on display on");
3757 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003758 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003759 // Turn off the display
3760 struct sched_param param = {0};
3761 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3762 ALOGW("Couldn't set SCHED_OTHER on display off");
3763 }
3764
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003765 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003766 disableHardwareVsync(true); // also cancels any in-progress resync
3767
Mathias Agopiancde87a32012-09-13 14:09:01 -07003768 // FIXME: eventthread only knows about the main display right now
3769 mEventThread->onScreenReleased();
3770 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003771
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003772 getHwComposer().setPowerMode(type, mode);
3773 mVisibleRegionsDirty = true;
3774 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003775 } else if (mode == HWC_POWER_MODE_DOZE ||
3776 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003777 // Update display while dozing
3778 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003779 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003780 // FIXME: eventthread only knows about the main display right now
3781 mEventThread->onScreenAcquired();
3782 resyncToHardwareVsync(true);
3783 }
3784 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3785 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003786 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003787 disableHardwareVsync(true); // also cancels any in-progress resync
3788 // FIXME: eventthread only knows about the main display right now
3789 mEventThread->onScreenReleased();
3790 }
3791 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003792 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003793 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003794 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003795 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003796
3797 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003798}
3799
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003800void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003801 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003802 const auto display = getDisplayDevice(displayToken);
3803 if (!display) {
3804 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3805 displayToken.get());
3806 } else if (display->isVirtual()) {
3807 ALOGW("Attempt to set power mode %d for virtual display", mode);
3808 } else {
3809 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003810 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003811 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003812}
3813
3814// ---------------------------------------------------------------------------
3815
Lloyd Pique755e3192018-01-31 16:46:15 -08003816status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3817 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003818 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003819
Mathias Agopianbd115332013-04-18 16:41:04 -07003820 IPCThreadState* ipc = IPCThreadState::self();
3821 const int pid = ipc->getCallingPid();
3822 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003823
Mathias Agopianbd115332013-04-18 16:41:04 -07003824 if ((uid != AID_SHELL) &&
3825 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003826 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003827 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003828 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003829 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003830 // (this would indicate SF is stuck, but we want to be able to
3831 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003832 status_t err = mStateLock.timedLock(s2ns(1));
3833 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003834 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003835 result.appendFormat(
3836 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3837 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003838 }
3839
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003840 bool dumpAll = true;
3841 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003842 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003843
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003844 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003845 if ((index < numArgs) &&
3846 (args[index] == String16("--list"))) {
3847 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003848 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003849 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003850 }
3851
3852 if ((index < numArgs) &&
3853 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003854 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003855 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003856 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003857 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003858
3859 if ((index < numArgs) &&
3860 (args[index] == String16("--latency-clear"))) {
3861 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003862 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003863 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003864 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003865
3866 if ((index < numArgs) &&
3867 (args[index] == String16("--dispsync"))) {
3868 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07003869 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07003870 dumpAll = false;
3871 }
Dan Stozab90cf072015-03-05 11:05:59 -08003872
3873 if ((index < numArgs) &&
3874 (args[index] == String16("--static-screen"))) {
3875 index++;
3876 dumpStaticScreenStats(result);
3877 dumpAll = false;
3878 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003879
3880 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003881 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003882 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003883 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003884 dumpAll = false;
3885 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003886
3887 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3888 index++;
3889 dumpWideColorInfo(result);
3890 dumpAll = false;
3891 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003892
3893 if ((index < numArgs) &&
3894 (args[index] == String16("--enable-layer-stats"))) {
3895 index++;
3896 mLayerStats.enable();
3897 dumpAll = false;
3898 }
3899
3900 if ((index < numArgs) &&
3901 (args[index] == String16("--disable-layer-stats"))) {
3902 index++;
3903 mLayerStats.disable();
3904 dumpAll = false;
3905 }
3906
3907 if ((index < numArgs) &&
3908 (args[index] == String16("--clear-layer-stats"))) {
3909 index++;
3910 mLayerStats.clear();
3911 dumpAll = false;
3912 }
3913
3914 if ((index < numArgs) &&
3915 (args[index] == String16("--dump-layer-stats"))) {
3916 index++;
3917 mLayerStats.dump(result);
3918 dumpAll = false;
3919 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003920
3921 if ((index < numArgs) &&
3922 (args[index] == String16("--display-identification"))) {
3923 index++;
3924 dumpDisplayIdentificationData(result);
3925 dumpAll = false;
3926 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003927
3928 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3929 index++;
3930 mTimeStats.parseArgs(asProto, args, index, result);
3931 dumpAll = false;
3932 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003933 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003934
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003935 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003936 if (asProto) {
3937 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3938 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3939 } else {
3940 dumpAllLocked(args, index, result);
3941 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003942 }
3943
Mathias Agopian9795c422009-08-26 16:36:26 -07003944 if (locked) {
3945 mStateLock.unlock();
3946 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003947 }
3948 write(fd, result.string(), result.size());
3949 return NO_ERROR;
3950}
3951
Dan Stozac7014012014-02-14 15:03:43 -08003952void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3953 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003954{
Robert Carr2047fae2016-11-28 14:09:09 -08003955 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003956 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003957 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003958}
3959
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003960void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003961 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003962{
3963 String8 name;
3964 if (index < args.size()) {
3965 name = String8(args[index]);
3966 index++;
3967 }
3968
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003969 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
3970 getHwComposer().isConnected(displayId)) {
3971 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
3972 const nsecs_t period = activeConfig->getVsyncPeriod();
3973 result.appendFormat("%" PRId64 "\n", period);
3974 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003975
3976 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003977 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003978 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003979 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003980 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003981 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003982 }
Robert Carr2047fae2016-11-28 14:09:09 -08003983 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003984 }
3985}
3986
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003987void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003988 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003989{
3990 String8 name;
3991 if (index < args.size()) {
3992 name = String8(args[index]);
3993 index++;
3994 }
3995
Robert Carr2047fae2016-11-28 14:09:09 -08003996 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003997 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003998 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003999 }
Robert Carr2047fae2016-11-28 14:09:09 -08004000 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004001
Svetoslavd85084b2014-03-20 10:28:31 -07004002 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004003}
4004
Jamie Gennis6547ff42013-07-16 20:12:42 -07004005// This should only be called from the main thread. Otherwise it would need
4006// the lock and should use mCurrentState rather than mDrawingState.
4007void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004008 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004009 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004010 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004011
4012 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4013}
4014
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004015void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004016{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004017 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004018
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004019 if (isLayerTripleBufferingDisabled())
4020 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004021
4022 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004023 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004024 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004025 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004026 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4027 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004028 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004029}
4030
Dan Stozab90cf072015-03-05 11:05:59 -08004031void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4032{
4033 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004034 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4035 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004036 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004037 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004038 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4039 b + 1, bucketTimeSec, percent);
4040 }
David Sodman4a36e932017-11-07 14:29:47 -08004041 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004042 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004043 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004044 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004045 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004046}
4047
Dan Stozae77c7662016-05-13 11:37:28 -07004048void SurfaceFlinger::recordBufferingStats(const char* layerName,
4049 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004050 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4051 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004052 for (const auto& segment : history) {
4053 if (!segment.usedThirdBuffer) {
4054 stats.twoBufferTime += segment.totalTime;
4055 }
4056 if (segment.occupancyAverage < 1.0f) {
4057 stats.doubleBufferedTime += segment.totalTime;
4058 } else if (segment.occupancyAverage < 2.0f) {
4059 stats.tripleBufferedTime += segment.totalTime;
4060 }
4061 ++stats.numSegments;
4062 stats.totalTime += segment.totalTime;
4063 }
4064}
4065
Brian Andersond6927fb2016-07-23 23:37:30 -07004066void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4067 result.appendFormat("Layer frame timestamps:\n");
4068
4069 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4070 const size_t count = currentLayers.size();
4071 for (size_t i=0 ; i<count ; i++) {
4072 currentLayers[i]->dumpFrameEvents(result);
4073 }
4074}
4075
Dan Stozae77c7662016-05-13 11:37:28 -07004076void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4077 result.append("Buffering stats:\n");
4078 result.append(" [Layer name] <Active time> <Two buffer> "
4079 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004080 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004081 typedef std::tuple<std::string, float, float, float> BufferTuple;
4082 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004083 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004084 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004085 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004086 if (stats.numSegments == 0) {
4087 continue;
4088 }
4089 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4090 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4091 stats.totalTime;
4092 float doubleBufferRatio = static_cast<float>(
4093 stats.doubleBufferedTime) / stats.totalTime;
4094 float tripleBufferRatio = static_cast<float>(
4095 stats.tripleBufferedTime) / stats.totalTime;
4096 sorted.insert({activeTime, {name, twoBufferRatio,
4097 doubleBufferRatio, tripleBufferRatio}});
4098 }
4099 for (const auto& sortedPair : sorted) {
4100 float activeTime = sortedPair.first;
4101 const BufferTuple& values = sortedPair.second;
4102 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4103 std::get<0>(values).c_str(), activeTime,
4104 std::get<1>(values), std::get<2>(values),
4105 std::get<3>(values));
4106 }
4107 result.append("\n");
4108}
4109
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004110void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004111 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004112 const int32_t displayId = display->getId();
4113 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4114 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004115 continue;
4116 }
4117
Dominik Laskowski7e045462018-05-30 13:02:02 -07004118 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004119 uint8_t port;
4120 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004121 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004122 result.append("no identification data\n");
4123 continue;
4124 }
4125
4126 if (!isEdid(data)) {
4127 result.append("unknown identification data: ");
4128 for (uint8_t byte : data) {
4129 result.appendFormat("%x ", byte);
4130 }
4131 result.append("\n");
4132 continue;
4133 }
4134
4135 const auto edid = parseEdid(data);
4136 if (!edid) {
4137 result.append("invalid EDID: ");
4138 for (uint8_t byte : data) {
4139 result.appendFormat("%x ", byte);
4140 }
4141 result.append("\n");
4142 continue;
4143 }
4144
4145 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4146 result.append(edid->displayName.data(), edid->displayName.length());
4147 result.append("\"\n");
4148 }
4149 result.append("\n");
4150}
4151
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004152void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4153 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004154 result.appendFormat("DisplayColorSetting: %s\n",
4155 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004156
4157 // TODO: print out if wide-color mode is active or not
4158
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004159 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004160 const int32_t displayId = display->getId();
4161 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004162 continue;
4163 }
4164
Dominik Laskowski7e045462018-05-30 13:02:02 -07004165 result.appendFormat("Display %d color modes:\n", displayId);
4166 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004167 for (auto&& mode : modes) {
4168 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4169 }
4170
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004171 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004172 result.appendFormat(" Current color mode: %s (%d)\n",
4173 decodeColorMode(currentMode).c_str(), currentMode);
4174 }
4175 result.append("\n");
4176}
4177
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004178LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004179 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004180 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4181 const State& state = useDrawing ? mDrawingState : mCurrentState;
4182 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004183 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004184 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004185 });
4186
4187 return layersProto;
4188}
4189
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004190LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004191 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004192
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004193 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004194 resolution->set_w(display.getWidth());
4195 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004196
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004197 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4198 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4199 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004200
Dominik Laskowski7e045462018-05-30 13:02:02 -07004201 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004202 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004203 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004204 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004205 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004206 }
4207 });
4208
4209 return layersProto;
4210}
4211
Mathias Agopian74d211a2013-04-22 16:55:35 +02004212void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4213 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004214{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004215 bool colorize = false;
4216 if (index < args.size()
4217 && (args[index] == String16("--color"))) {
4218 colorize = true;
4219 index++;
4220 }
4221
4222 Colorizer colorizer(colorize);
4223
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004224 // figure out if we're stuck somewhere
4225 const nsecs_t now = systemTime();
4226 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4227 const nsecs_t inTransaction(mDebugInTransaction);
4228 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4229 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4230
4231 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004232 * Dump library configuration.
4233 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004234
4235 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004236 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004237 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004238 appendSfConfigString(result);
4239 appendUiConfigString(result);
4240 appendGuiConfigString(result);
4241 result.append("\n");
4242
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004243 result.append("\nDisplay identification data:\n");
4244 dumpDisplayIdentificationData(result);
4245
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004246 result.append("\nWide-Color information:\n");
4247 dumpWideColorInfo(result);
4248
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004249 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004250 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004251 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004252 result.append(SyncFeatures::getInstance().toString());
4253 result.append("\n");
4254
Andy McFadden41d67d72014-04-25 16:58:34 -07004255 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004256 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004257 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004258
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004259 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4260 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004261 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4262 getHwComposer().isConnected(displayId)) {
4263 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004264 result.appendFormat("Display %d: "
4265 "app phase %" PRId64 " ns, "
4266 "sf phase %" PRId64 " ns, "
4267 "early app phase %" PRId64 " ns, "
4268 "early sf phase %" PRId64 " ns, "
4269 "early app gl phase %" PRId64 " ns, "
4270 "early sf gl phase %" PRId64 " ns, "
4271 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4272 displayId,
4273 vsyncPhaseOffsetNs,
4274 sfVsyncPhaseOffsetNs,
4275 appEarlyOffset,
4276 sfEarlyOffset,
4277 appEarlyGlOffset,
4278 sfEarlyOffset,
4279 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004280 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004281 result.append("\n");
4282
Dan Stozab90cf072015-03-05 11:05:59 -08004283 // Dump static screen stats
4284 result.append("\n");
4285 dumpStaticScreenStats(result);
4286 result.append("\n");
4287
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004288 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4289
Dan Stozae77c7662016-05-13 11:37:28 -07004290 dumpBufferingStats(result);
4291
Andy McFadden4803b742012-09-24 19:07:20 -07004292 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004293 * Dump the visible layer list
4294 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004295 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004296 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004297 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4298 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004299 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004300
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004301 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004302 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004303 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004304 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004305
4306 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004307 * Dump Display state
4308 */
4309
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004310 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004311 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004312 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004313 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004314 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004315 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004316 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004317
4318 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004319 * Dump SurfaceFlinger global state
4320 */
4321
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004322 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004323 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004324 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004325
Mathias Agopian888c8222012-08-04 21:10:38 -07004326 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004327 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004328
David Sodmanbc815282017-11-05 18:57:52 -08004329 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004330
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004331 if (display) {
4332 display->undefinedRegion.dump(result, "undefinedRegion");
4333 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4334 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004335 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004336 result.appendFormat(" last eglSwapBuffers() time: %f us\n"
4337 " last transaction time : %f us\n"
4338 " transaction-flags : %08x\n"
4339 " gpu_to_cpu_unsupported : %d\n",
4340 mLastSwapBufferTime / 1000.0, mLastTransactionTime / 1000.0,
4341 mTransactionFlags, !mGpuToCpuSupported);
4342
4343 if (display) {
4344 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4345 result.appendFormat(" refresh-rate : %f fps\n"
4346 " x-dpi : %f\n"
4347 " y-dpi : %f\n",
4348 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4349 activeConfig->getDpiY());
4350 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004351
Mathias Agopian74d211a2013-04-22 16:55:35 +02004352 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004353 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004354
Mathias Agopian74d211a2013-04-22 16:55:35 +02004355 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004356 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004357
4358 /*
4359 * VSYNC state
4360 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004361 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004362 result.append("\n");
4363
4364 /*
4365 * HWC layer minidump
4366 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004367 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004368 const int32_t displayId = display->getId();
4369 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004370 continue;
4371 }
4372
Dominik Laskowski7e045462018-05-30 13:02:02 -07004373 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004374 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004375 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004376 result.append("\n");
4377 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004378
4379 /*
4380 * Dump HWComposer state
4381 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004382 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004383 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004384 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004385 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004386 result.appendFormat(" h/w composer %s\n",
4387 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004388 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004389
4390 /*
4391 * Dump gralloc state
4392 */
4393 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4394 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004395
4396 /*
4397 * Dump VrFlinger state if in use.
4398 */
4399 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4400 result.append("VrFlinger state:\n");
4401 result.append(mVrFlinger->Dump().c_str());
4402 result.append("\n");
4403 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004404}
4405
Dominik Laskowski7e045462018-05-30 13:02:02 -07004406const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004407 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004408 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004409 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004410 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004411 }
4412 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004413
4414 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4415 static const Vector<sp<Layer>> empty;
4416 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004417}
4418
Keun young Park63f165f2012-08-31 10:53:36 -07004419bool SurfaceFlinger::startDdmConnection()
4420{
4421 void* libddmconnection_dso =
4422 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4423 if (!libddmconnection_dso) {
4424 return false;
4425 }
4426 void (*DdmConnection_start)(const char* name);
4427 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004428 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004429 if (!DdmConnection_start) {
4430 dlclose(libddmconnection_dso);
4431 return false;
4432 }
4433 (*DdmConnection_start)(getServiceName());
4434 return true;
4435}
4436
Chia-I Wu28f320b2018-05-03 11:02:56 -07004437void SurfaceFlinger::updateColorMatrixLocked() {
4438 mat4 colorMatrix;
4439 if (mGlobalSaturationFactor != 1.0f) {
4440 // Rec.709 luma coefficients
4441 float3 luminance{0.213f, 0.715f, 0.072f};
4442 luminance *= 1.0f - mGlobalSaturationFactor;
4443 mat4 saturationMatrix = mat4(
4444 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4445 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4446 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4447 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4448 );
4449 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4450 } else {
4451 colorMatrix = mClientColorMatrix * mDaltonizer();
4452 }
4453
4454 if (mCurrentState.colorMatrix != colorMatrix) {
4455 mCurrentState.colorMatrix = colorMatrix;
4456 mCurrentState.colorMatrixChanged = true;
4457 setTransactionFlags(eTransactionNeeded);
4458 }
4459}
4460
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004461status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulecfbe2c002018-08-09 22:32:45 +00004462#pragma clang diagnostic push
4463#pragma clang diagnostic error "-Wswitch-enum"
4464 switch (static_cast<ISurfaceComposerTag>(code)) {
4465 // These methods should at minimum make sure that the client requested
4466 // access to SF.
4467 case AUTHENTICATE_SURFACE:
Peiyong Line70e1292018-08-09 14:06:58 -07004468 case BOOT_FINISHED:
4469 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulecfbe2c002018-08-09 22:32:45 +00004470 case CREATE_CONNECTION:
4471 case CREATE_DISPLAY:
4472 case DESTROY_DISPLAY:
Peiyong Line70e1292018-08-09 14:06:58 -07004473 case ENABLE_VSYNC_INJECTIONS:
Ana Krulecfbe2c002018-08-09 22:32:45 +00004474 case GET_ACTIVE_COLOR_MODE:
4475 case GET_ANIMATION_FRAME_STATS:
4476 case GET_HDR_CAPABILITIES:
4477 case SET_ACTIVE_CONFIG:
4478 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004479 case INJECT_VSYNC:
Ana Krulecfbe2c002018-08-09 22:32:45 +00004480 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004481 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4482 IPCThreadState* ipc = IPCThreadState::self();
4483 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4484 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004485 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004486 }
Robert Carr1db73f62016-12-21 12:58:51 -08004487 return OK;
4488 }
Ana Krulecfbe2c002018-08-09 22:32:45 +00004489 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004490 IPCThreadState* ipc = IPCThreadState::self();
4491 const int pid = ipc->getCallingPid();
4492 const int uid = ipc->getCallingUid();
Ana Krulecfbe2c002018-08-09 22:32:45 +00004493 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4494 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004495 return PERMISSION_DENIED;
4496 }
Ana Krulecfbe2c002018-08-09 22:32:45 +00004497 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004498 }
Ana Krulecfbe2c002018-08-09 22:32:45 +00004499 // Used by apps to hook Choreographer to SurfaceFlinger.
4500 case CREATE_DISPLAY_EVENT_CONNECTION:
4501 // The following calls are currently used by clients that do not
4502 // request necessary permissions. However, they do not expose any secret
4503 // information, so it is OK to pass them.
4504 case GET_ACTIVE_CONFIG:
4505 case GET_BUILT_IN_DISPLAY:
4506 case GET_DISPLAY_COLOR_MODES:
4507 case GET_DISPLAY_CONFIGS:
4508 case GET_DISPLAY_STATS:
4509 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4510 // Calling setTransactionState is safe, because you need to have been
4511 // granted a reference to Client* and Handle* to do anything with it.
4512 case SET_TRANSACTION_STATE:
4513 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4514 case CREATE_SCOPED_CONNECTION: {
4515 return OK;
4516 }
4517 case CAPTURE_LAYERS:
4518 case CAPTURE_SCREEN: {
4519 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004520 IPCThreadState* ipc = IPCThreadState::self();
4521 const int pid = ipc->getCallingPid();
4522 const int uid = ipc->getCallingUid();
4523 if ((uid != AID_GRAPHICS) &&
4524 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4525 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4526 return PERMISSION_DENIED;
4527 }
Ana Krulecfbe2c002018-08-09 22:32:45 +00004528 return OK;
4529 }
4530 // The following codes are deprecated and should never be allowed to access SF.
4531 case CONNECT_DISPLAY_UNUSED:
4532 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4533 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4534 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004535 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004536 }
Ana Krulecfbe2c002018-08-09 22:32:45 +00004537
4538 // These codes are used for the IBinder protocol to either interrogate the recipient
4539 // side of the transaction for its canonical interface descriptor or to dump its state.
4540 // We let them pass by default.
4541 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4542 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4543 code == IBinder::SYSPROPS_TRANSACTION) {
4544 return OK;
4545 }
4546 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4547 // in onTransact verifies that the user is root, and has access to use SF.
4548 if (code >= 1000 && code <= 1029) {
4549 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4550 return OK;
4551 }
4552 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4553 return PERMISSION_DENIED;
4554#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004555}
4556
Ana Krulecfbe2c002018-08-09 22:32:45 +00004557status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4558 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004559 status_t credentialCheck = CheckTransactCodeCredentials(code);
4560 if (credentialCheck != OK) {
4561 return credentialCheck;
4562 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004563
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004564 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4565 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004566 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004567 IPCThreadState* ipc = IPCThreadState::self();
4568 const int uid = ipc->getCallingUid();
4569 if (CC_UNLIKELY(uid != AID_SYSTEM
4570 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004571 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004572 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004573 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004574 return PERMISSION_DENIED;
4575 }
4576 int n;
4577 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004578 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004579 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004580 return NO_ERROR;
4581 case 1002: // SHOW_UPDATES
4582 n = data.readInt32();
4583 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004584 invalidateHwcGeometry();
4585 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004586 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004587 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004588 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004589 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004590 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004591 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004592 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004593 setTransactionFlags(
4594 eTransactionNeeded|
4595 eDisplayTransactionNeeded|
4596 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004597 return NO_ERROR;
4598 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004599 case 1006:{ // send empty update
4600 signalRefresh();
4601 return NO_ERROR;
4602 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004603 case 1008: // toggle use of hw composer
4604 n = data.readInt32();
4605 mDebugDisableHWC = n ? 1 : 0;
4606 invalidateHwcGeometry();
4607 repaintEverything();
4608 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004609 case 1009: // toggle use of transform hint
4610 n = data.readInt32();
4611 mDebugDisableTransformHint = n ? 1 : 0;
4612 invalidateHwcGeometry();
4613 repaintEverything();
4614 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004615 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004616 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004617 reply->writeInt32(0);
4618 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004619 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004620 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004621 return NO_ERROR;
4622 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004623 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004624 if (!display) {
4625 return NAME_NOT_FOUND;
4626 }
4627
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004628 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004629 return NO_ERROR;
4630 }
4631 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004632 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004633 // daltonize
4634 n = data.readInt32();
4635 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004636 case 1:
4637 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4638 break;
4639 case 2:
4640 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4641 break;
4642 case 3:
4643 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4644 break;
4645 default:
4646 mDaltonizer.setType(ColorBlindnessType::None);
4647 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004648 }
4649 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004650 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004651 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004652 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004653 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004654
4655 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004656 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004657 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004658 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004659 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004660 // apply a color matrix
4661 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004662 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004663 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004664 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004665 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004666 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004667 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004668 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004669 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004670 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004671 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004672
4673 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4674 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004675 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004676 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4677 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4678 }
4679
Chia-I Wu28f320b2018-05-03 11:02:56 -07004680 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004681 return NO_ERROR;
4682 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004683 // This is an experimental interface
4684 // Needs to be shifted to proper binder interface when we productize
4685 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004686 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07004687 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004688 return NO_ERROR;
4689 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004690 case 1017: {
4691 n = data.readInt32();
4692 mForceFullDamage = static_cast<bool>(n);
4693 return NO_ERROR;
4694 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004695 case 1018: { // Modify Choreographer's phase offset
4696 n = data.readInt32();
4697 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4698 return NO_ERROR;
4699 }
4700 case 1019: { // Modify SurfaceFlinger's phase offset
4701 n = data.readInt32();
4702 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4703 return NO_ERROR;
4704 }
Irvel468051e2016-06-13 16:44:44 -07004705 case 1020: { // Layer updates interceptor
4706 n = data.readInt32();
4707 if (n) {
4708 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004709 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004710 }
4711 else{
4712 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004713 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004714 }
4715 return NO_ERROR;
4716 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004717 case 1021: { // Disable HWC virtual displays
4718 n = data.readInt32();
4719 mUseHwcVirtualDisplays = !n;
4720 return NO_ERROR;
4721 }
Romain Guy0147a172017-06-01 13:53:56 -07004722 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004723 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004724 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004725
Chia-I Wu28f320b2018-05-03 11:02:56 -07004726 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004727 return NO_ERROR;
4728 }
Romain Guy54f154a2017-10-24 21:40:32 +01004729 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004730 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004731 invalidateHwcGeometry();
4732 repaintEverything();
4733 return NO_ERROR;
4734 }
4735 case 1024: { // Is wide color gamut rendering/color management supported?
4736 reply->writeBool(hasWideColorDisplay);
4737 return NO_ERROR;
4738 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004739 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004740 n = data.readInt32();
4741 if (n) {
4742 ALOGV("LayerTracing enabled");
4743 mTracing.enable();
4744 doTracing("tracing.enable");
4745 reply->writeInt32(NO_ERROR);
4746 } else {
4747 ALOGV("LayerTracing disabled");
4748 status_t err = mTracing.disable();
4749 reply->writeInt32(err);
4750 }
4751 return NO_ERROR;
4752 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004753 case 1026: { // Get layer tracing status
4754 reply->writeBool(mTracing.isEnabled());
4755 return NO_ERROR;
4756 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004757 // Is a DisplayColorSetting supported?
4758 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004759 const auto display = getDefaultDisplayDevice();
4760 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004761 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004762 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004763
4764 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4765 switch (setting) {
4766 case DisplayColorSetting::MANAGED:
4767 reply->writeBool(hasWideColorDisplay);
4768 break;
4769 case DisplayColorSetting::UNMANAGED:
4770 reply->writeBool(true);
4771 break;
4772 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004773 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004774 break;
4775 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004776 reply->writeBool(
4777 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004778 break;
4779 }
4780 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004781 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004782 // Is VrFlinger active?
4783 case 1028: {
4784 Mutex::Autolock _l(mStateLock);
4785 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4786 return NO_ERROR;
4787 }
David Sodman6d46c1e2018-07-13 12:59:48 -07004788 case 1029: {
4789 // Code 1029 is an experimental feature that allows applications to
4790 // simulate a high frequency panel by setting a multiplier and divisor
4791 // on the VSYNC-sf clock. If either the multiplier or divisor are
4792 // 0, then the code will set both to 1 to return the VSYNC-sf clock
4793 // to it's normal frequency.
4794 int multiplier = data.readInt32();
4795 int divisor = data.readInt32();
4796
4797 if ((multiplier == 0) || (divisor == 0)) {
4798 multiplier = 1;
4799 divisor = 1;
4800 }
4801
4802 if ((multiplier == 1) && (divisor == 1)) {
4803 enableHardwareVsync();
4804 } else {
4805 disableHardwareVsync(true);
4806 }
4807 getBE().mHwc->getActiveConfig(DisplayDevice::DISPLAY_PRIMARY)
4808 ->scalePanelFrequency(multiplier, divisor);
4809 mPrimaryDispSync->scalePeriod(multiplier, divisor);
4810
4811 ATRACE_INT("PeriodMultiplier", multiplier);
4812 ATRACE_INT("PeriodDivisor", divisor);
4813 return NO_ERROR;
4814 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004815 }
4816 }
4817 return err;
4818}
4819
Steven Thomas6d8110b2017-08-31 18:24:21 -07004820void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004821 android_atomic_or(1, &mRepaintEverything);
4822 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004823}
4824
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004825// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4826class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004827public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004828 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4829 ~WindowDisconnector() {
4830 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004831 }
4832
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004833private:
4834 ANativeWindow* mWindow;
4835 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004836};
4837
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004838status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4839 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4840 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4841 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004842 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004843 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004844
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004845 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004846
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004847 const auto display = getDisplayDeviceLocked(displayToken);
4848 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004849
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004850 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004851
4852 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004853 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004854 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004855}
4856
4857status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004858 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004859 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004860 ATRACE_CALL();
4861
4862 class LayerRenderArea : public RenderArea {
4863 public:
Robert Carr578038f2018-03-09 12:25:24 -08004864 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4865 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004866 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004867 mLayer(layer),
4868 mCrop(crop),
4869 mFlinger(flinger),
4870 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004871 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004872 Rect getBounds() const override {
4873 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07004874 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07004875 }
Marissa Wall61c58622018-07-18 10:12:20 -07004876 int getHeight() const override {
4877 return mLayer->getActiveHeight(mLayer->getDrawingState());
4878 }
4879 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07004880 bool isSecure() const override { return false; }
4881 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004882 Rect getSourceCrop() const override {
4883 if (mCrop.isEmpty()) {
4884 return getBounds();
4885 } else {
4886 return mCrop;
4887 }
4888 }
Robert Carr578038f2018-03-09 12:25:24 -08004889 class ReparentForDrawing {
4890 public:
4891 const sp<Layer>& oldParent;
4892 const sp<Layer>& newParent;
4893
4894 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4895 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004896 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004897 }
Robert Carr15eae092018-03-23 13:43:53 -07004898 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004899 };
4900
4901 void render(std::function<void()> drawLayers) override {
4902 if (!mChildrenOnly) {
4903 mTransform = mLayer->getTransform().inverse();
4904 drawLayers();
4905 } else {
4906 Rect bounds = getBounds();
4907 screenshotParentLayer =
4908 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4909 bounds.getWidth(), bounds.getHeight(), 0);
4910
4911 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4912 drawLayers();
4913 }
4914 }
chaviwa76b2712017-09-20 12:02:26 -07004915
chaviwa76b2712017-09-20 12:02:26 -07004916 private:
chaviw7206d492017-11-10 16:16:12 -08004917 const sp<Layer> mLayer;
4918 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004919
4920 // In the "childrenOnly" case we reparent the children to a screenshot
4921 // layer which has no properties set and which does not draw.
4922 sp<ContainerLayer> screenshotParentLayer;
4923 Transform mTransform;
4924
4925 SurfaceFlinger* mFlinger;
4926 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004927 };
4928
4929 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4930 auto parent = layerHandle->owner.promote();
4931
chaviw7206d492017-11-10 16:16:12 -08004932 if (parent == nullptr || parent->isPendingRemoval()) {
4933 ALOGE("captureLayers called with a removed parent");
4934 return NAME_NOT_FOUND;
4935 }
4936
Robert Carr578038f2018-03-09 12:25:24 -08004937 const int uid = IPCThreadState::self()->getCallingUid();
4938 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4939 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4940 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4941 return PERMISSION_DENIED;
4942 }
4943
chaviw7206d492017-11-10 16:16:12 -08004944 Rect crop(sourceCrop);
4945 if (sourceCrop.width() <= 0) {
4946 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07004947 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08004948 }
4949
4950 if (sourceCrop.height() <= 0) {
4951 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07004952 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08004953 }
4954
4955 int32_t reqWidth = crop.width() * frameScale;
4956 int32_t reqHeight = crop.height() * frameScale;
4957
Robert Carr578038f2018-03-09 12:25:24 -08004958 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004959
Robert Carr578038f2018-03-09 12:25:24 -08004960 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004961 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4962 if (!layer->isVisible()) {
4963 return;
Robert Carr578038f2018-03-09 12:25:24 -08004964 } else if (childrenOnly && layer == parent.get()) {
4965 return;
chaviwa76b2712017-09-20 12:02:26 -07004966 }
4967 visitor(layer);
4968 });
4969 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004970 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004971}
4972
4973status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4974 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004975 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004976 bool useIdentityTransform) {
4977 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004978
Iris Chang7501ed62018-04-30 14:45:42 +08004979 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004980
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004981 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4982 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4983 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4984 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004985
4986 // This mutex protects syncFd and captureResult for communication of the return values from the
4987 // main thread back to this Binder thread
4988 std::mutex captureMutex;
4989 std::condition_variable captureCondition;
4990 std::unique_lock<std::mutex> captureLock(captureMutex);
4991 int syncFd = -1;
4992 std::optional<status_t> captureResult;
4993
Robert Carr03480e22018-01-04 16:02:06 -08004994 const int uid = IPCThreadState::self()->getCallingUid();
4995 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4996
Dominik Laskowski8c001672018-05-30 16:52:06 -07004997 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004998 // If there is a refresh pending, bug out early and tell the binder thread to try again
4999 // after the refresh.
5000 if (mRefreshPending) {
5001 ATRACE_NAME("Skipping screenshot for now");
5002 std::unique_lock<std::mutex> captureLock(captureMutex);
5003 captureResult = std::make_optional<status_t>(EAGAIN);
5004 captureCondition.notify_one();
5005 return;
5006 }
5007
5008 status_t result = NO_ERROR;
5009 int fd = -1;
5010 {
5011 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005012 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005013 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5014 useIdentityTransform, forSystem, &fd);
5015 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005016 }
5017
5018 {
5019 std::unique_lock<std::mutex> captureLock(captureMutex);
5020 syncFd = fd;
5021 captureResult = std::make_optional<status_t>(result);
5022 captureCondition.notify_one();
5023 }
5024 });
5025
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005026 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005027 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005028 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005029 while (*captureResult == EAGAIN) {
5030 captureResult.reset();
5031 result = postMessageAsync(message);
5032 if (result != NO_ERROR) {
5033 return result;
5034 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005035 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005036 }
5037 result = *captureResult;
5038 }
5039
5040 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005041 sync_wait(syncFd, -1);
5042 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005043 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005044
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005045 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005046}
5047
chaviwa76b2712017-09-20 12:02:26 -07005048void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5049 TraverseLayersFunction traverseLayers, bool yswap,
5050 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005051 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005052
Lloyd Pique144e1162017-12-20 16:44:52 -08005053 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005054
5055 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005056 const auto raWidth = renderArea.getWidth();
5057 const auto raHeight = renderArea.getHeight();
5058
5059 const auto reqWidth = renderArea.getReqWidth();
5060 const auto reqHeight = renderArea.getReqHeight();
5061 Rect sourceCrop = renderArea.getSourceCrop();
5062
Iris Chang7501ed62018-04-30 14:45:42 +08005063 bool filtering = false;
5064 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5065 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5066 static_cast<int32_t>(reqHeight) != raWidth;
5067 } else {
5068 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5069 static_cast<int32_t>(reqHeight) != raHeight;
5070 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005071
Dan Stozac1879002014-05-22 15:59:05 -07005072 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005073 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005074 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005075 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005076 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5077 Transform tr;
5078 uint32_t flags = 0x00;
5079 switch (mPrimaryDisplayOrientation) {
5080 case DisplayState::eOrientation90:
5081 flags = Transform::ROT_90;
5082 break;
5083 case DisplayState::eOrientation180:
5084 flags = Transform::ROT_180;
5085 break;
5086 case DisplayState::eOrientation270:
5087 flags = Transform::ROT_270;
5088 break;
5089 }
5090 tr.set(flags, raWidth, raHeight);
5091 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005092 }
5093
5094 // ensure that sourceCrop is inside screen
5095 if (sourceCrop.left < 0) {
5096 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5097 }
chaviwa76b2712017-09-20 12:02:26 -07005098 if (sourceCrop.right > raWidth) {
5099 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005100 }
5101 if (sourceCrop.top < 0) {
5102 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5103 }
chaviwa76b2712017-09-20 12:02:26 -07005104 if (sourceCrop.bottom > raHeight) {
5105 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005106 }
5107
Chia-I Wu36574d92018-05-16 10:54:36 -07005108 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5109 engine.setOutputDataSpace(Dataspace::SRGB);
5110 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005111
Mathias Agopian180f10d2013-04-10 22:55:41 -07005112 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005113 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005114
Iris Chang7501ed62018-04-30 14:45:42 +08005115 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5116 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5117 // convert hw orientation into flag presentation
5118 // here inverse transform needed
5119 uint8_t hw_rot_90 = 0x00;
5120 uint8_t hw_flip_hv = 0x00;
5121 switch (mPrimaryDisplayOrientation) {
5122 case DisplayState::eOrientation90:
5123 hw_rot_90 = Transform::ROT_90;
5124 hw_flip_hv = Transform::ROT_180;
5125 break;
5126 case DisplayState::eOrientation180:
5127 hw_flip_hv = Transform::ROT_180;
5128 break;
5129 case DisplayState::eOrientation270:
5130 hw_rot_90 = Transform::ROT_90;
5131 break;
5132 }
5133
5134 // transform flags operation
5135 // 1) flip H V if both have ROT_90 flag
5136 // 2) XOR these flags
5137 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5138 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5139 if (rotation_rot_90 & hw_rot_90) {
5140 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5141 }
5142 rotation = static_cast<Transform::orientation_flags>
5143 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5144 }
5145
Mathias Agopian180f10d2013-04-10 22:55:41 -07005146 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005147 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005148 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005149 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005150
chaviw50da5042018-04-09 13:49:37 -07005151 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005152 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005153 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005154
chaviwa76b2712017-09-20 12:02:26 -07005155 traverseLayers([&](Layer* layer) {
5156 if (filtering) layer->setFiltering(true);
David Sodmanca10ed22018-04-16 14:10:25 -07005157 layer->drawNow(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005158 if (filtering) layer->setFiltering(false);
5159 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005160}
5161
chaviwa76b2712017-09-20 12:02:26 -07005162status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5163 TraverseLayersFunction traverseLayers,
5164 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005165 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005166 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005167 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005168 ATRACE_CALL();
5169
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005170 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005171
5172 traverseLayers([&](Layer* layer) {
5173 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5174 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005175
Robert Carr03480e22018-01-04 16:02:06 -08005176 // We allow the system server to take screenshots of secure layers for
5177 // use in situations like the Screen-rotation animation and place
5178 // the impetus on WindowManager to not persist them.
5179 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005180 ALOGW("FB is protected: PERMISSION_DENIED");
5181 return PERMISSION_DENIED;
5182 }
5183
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005184 // this binds the given EGLImage as a framebuffer for the
5185 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005186 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005187 if (bufferBond.getStatus() != NO_ERROR) {
5188 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005189 return INVALID_OPERATION;
5190 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005191
Dan Stozaabcda352017-06-01 14:37:39 -07005192 // this will in fact render into our dequeued buffer
5193 // via an FBO, which means we didn't have to create
5194 // an EGLSurface and therefore we're not
5195 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005196 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005197
Dan Stozaabcda352017-06-01 14:37:39 -07005198 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005199 getRenderEngine().finish();
5200 *outSyncFd = -1;
5201
chaviwa76b2712017-09-20 12:02:26 -07005202 const auto reqWidth = renderArea.getReqWidth();
5203 const auto reqHeight = renderArea.getReqHeight();
5204
Dan Stozaabcda352017-06-01 14:37:39 -07005205 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5206 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005207 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005208 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005209 } else {
5210 base::unique_fd syncFd = getRenderEngine().flush();
5211 if (syncFd < 0) {
5212 getRenderEngine().finish();
5213 }
5214 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005215 }
5216
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005217 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005218}
5219
Mathias Agopiand5556842013-09-19 17:08:37 -07005220void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005221 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005222 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005223 for (size_t y = 0; y < h; y++) {
5224 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5225 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005226 if (p[x] != 0xFF000000) return;
5227 }
5228 }
chaviwa76b2712017-09-20 12:02:26 -07005229 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005230
Robert Carr2047fae2016-11-28 14:09:09 -08005231 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005232 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005233 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005234 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5235 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5236 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5237 static_cast<float>(state.color.a));
5238 i++;
5239 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005240 }
5241}
5242
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005243// ---------------------------------------------------------------------------
5244
Dan Stoza412903f2017-04-27 13:42:17 -07005245void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5246 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005247}
5248
Dan Stoza412903f2017-04-27 13:42:17 -07005249void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5250 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005251}
5252
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005253void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5254 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005255 const LayerVector::Visitor& visitor) {
5256 // We loop through the first level of layers without traversing,
5257 // as we need to interpret min/max layer Z in the top level Z space.
5258 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005259 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005260 continue;
5261 }
5262 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005263 // relative layers are traversed in Layer::traverseInZOrder
5264 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005265 continue;
5266 }
5267 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005268 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005269 return;
5270 }
chaviwa76b2712017-09-20 12:02:26 -07005271 if (!layer->isVisible()) {
5272 return;
5273 }
5274 visitor(layer);
5275 });
5276 }
5277}
5278
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005279}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005280
Lloyd Pique074e8122018-07-26 12:57:23 -07005281
Mathias Agopian3f844832013-08-07 21:24:32 -07005282#if defined(__gl_h_)
5283#error "don't include gl/gl.h in this file"
5284#endif
5285
5286#if defined(__gl2_h_)
5287#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005288#endif