blob: 337f89da676dbd427f56d9d5153182f8d40d1706 [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"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Steven Thomasb02664d2017-07-26 18:48:28 -070079#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070080#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include "Effects/Daltonizer.h"
Mathias Agopian875d8e12013-06-07 15:35:48 -070085#include "RenderEngine/RenderEngine.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070086#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070087#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070088#include "Scheduler/EventControlThread.h"
89#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070090#include "Scheduler/InjectVSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070091
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
Wei Wangf9b05ee2017-07-19 20:59:39 -0700569// Do not call property_set on main thread which will be blocked by init
570// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700571void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700572 ALOGI( "SurfaceFlinger's main thread ready to run. "
573 "Initializing graphics H/W...");
574
Thierry Strudel2924d012017-08-14 15:19:37 -0700575 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900576
Steven Thomasb02664d2017-07-26 18:48:28 -0700577 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800578
Steven Thomasb02664d2017-07-26 18:48:28 -0700579 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800580 mEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700581 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
582 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800583 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700584 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800585 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800586 "appEventThread");
587 mSfEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700588 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800589 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800590
Lloyd Pique24b0a482018-03-09 18:52:26 -0800591 mSFEventThread =
592 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700593 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800594 [this](nsecs_t timestamp) {
595 mInterceptor->saveVSyncEvent(timestamp);
596 },
597 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800598 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200599 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800600
Steven Thomasb02664d2017-07-26 18:48:28 -0700601 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800602 getBE().mRenderEngine =
603 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
604 hasWideColorDisplay
605 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
606 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800607 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700608
609 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
610 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800611 getBE().mHwc.reset(
612 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700613 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800614 // Process any initial hotplug and resulting display changes.
615 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700616 const auto display = getDefaultDisplayDeviceLocked();
617 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
618 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
619 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800620
Lloyd Piquefcd86612017-12-14 17:15:36 -0800621 // make the default display GLContext current so that we can create textures
622 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700623 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800624
Steven Thomas050b2c82017-03-06 11:45:16 -0800625 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700626 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700627 // This callback is called from the vr flinger dispatch thread. We
628 // need to call signalTransaction(), which requires holding
629 // mStateLock when we're not on the main thread. Acquiring
630 // mStateLock from the vr flinger dispatch thread might trigger a
631 // deadlock in surface flinger (see b/66916578), so post a message
632 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700633 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700634 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
635 mVrFlingerRequestsDisplay = requestDisplay;
636 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700637 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800638 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700639 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
640 getHwComposer()
641 .getHwcDisplayId(display->getId())
642 .value_or(0),
643 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800644 if (!mVrFlinger) {
645 ALOGE("Failed to start vrflinger");
646 }
647 }
648
Lloyd Pique379adc12018-01-22 17:31:47 -0800649 mEventControlThread = std::make_unique<impl::EventControlThread>(
650 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700651
Mathias Agopian92a979a2012-08-02 18:32:23 -0700652 // initialize our drawing state
653 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700654
Andy McFadden13a082e2012-08-24 10:16:42 -0700655 // set initial conditions (e.g. unblank default device)
656 initializeDisplays();
657
David Sodmanbc815282017-11-05 18:57:52 -0800658 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700659
Wei Wangf9b05ee2017-07-19 20:59:39 -0700660 // Inform native graphics APIs whether the present timestamp is supported:
661 if (getHwComposer().hasCapability(
662 HWC2::Capability::PresentFenceIsNotReliable)) {
663 mStartPropertySetThread = new StartPropertySetThread(false);
664 } else {
665 mStartPropertySetThread = new StartPropertySetThread(true);
666 }
667
668 if (mStartPropertySetThread->Start() != NO_ERROR) {
669 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800670 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800671
Chia-I Wud49d6692018-06-27 07:17:41 +0800672 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
673 // is used to saturate legacy sRGB content. However, to make sure the same color under
674 // Display P3 will be saturated to the same color, we intentionally break the API spec
675 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
676 // such saturation matrix on Display P3 is understood fully, the API should always return
677 // identify matrix.
678 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
679 Dataspace::SRGB_LINEAR);
680
681 // we will apply this on Display P3.
682 if (mEnhancedSaturationMatrix != mat4()) {
683 ColorSpace srgb(ColorSpace::sRGB());
684 ColorSpace displayP3(ColorSpace::DisplayP3());
685 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
686 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
687 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
688 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800689
Dan Stoza9e56aa02015-11-02 13:00:03 -0800690 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700691}
692
Romain Guy11d63f42017-07-20 12:47:14 -0700693void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700694 Mutex::Autolock _l(mStateLock);
695
Romain Guy11d63f42017-07-20 12:47:14 -0700696 char value[PROPERTY_VALUE_MAX];
697
698 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800699 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700700 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800701 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100702
703 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700704 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700705}
706
Mathias Agopiana67e4182012-06-19 17:26:12 -0700707void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800708 // Start boot animation service by setting a property mailbox
709 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700710 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800711 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700712 if (mStartPropertySetThread->join() != NO_ERROR) {
713 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800714 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700715}
716
Mathias Agopian875d8e12013-06-07 15:35:48 -0700717size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800718 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700719}
720
Mathias Agopian875d8e12013-06-07 15:35:48 -0700721size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800722 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700723}
724
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800725// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800726
Jamie Gennis582270d2011-08-17 18:19:00 -0700727bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800728 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800729 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800730 return authenticateSurfaceTextureLocked(bufferProducer);
731}
732
733bool SurfaceFlinger::authenticateSurfaceTextureLocked(
734 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800735 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800736 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800737}
738
Brian Anderson6b376712017-04-04 10:51:39 -0700739status_t SurfaceFlinger::getSupportedFrameTimestamps(
740 std::vector<FrameEvent>* outSupported) const {
741 *outSupported = {
742 FrameEvent::REQUESTED_PRESENT,
743 FrameEvent::ACQUIRE,
744 FrameEvent::LATCH,
745 FrameEvent::FIRST_REFRESH_START,
746 FrameEvent::LAST_REFRESH_START,
747 FrameEvent::GPU_COMPOSITION_DONE,
748 FrameEvent::DEQUEUE_READY,
749 FrameEvent::RELEASE,
750 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700751 ConditionalLock _l(mStateLock,
752 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700753 if (!getHwComposer().hasCapability(
754 HWC2::Capability::PresentFenceIsNotReliable)) {
755 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
756 }
757 return NO_ERROR;
758}
759
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700760status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
761 Vector<DisplayInfo>* configs) {
762 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700763 return BAD_VALUE;
764 }
765
Jesse Hall692c7232012-11-08 15:41:56 -0800766 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700767 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
768 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700769 type = i;
770 break;
771 }
772 }
773
774 if (type < 0) {
775 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700776 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700777
Mathias Agopian8b736f12012-08-13 17:54:26 -0700778 // TODO: Not sure if display density should handled by SF any longer
779 class Density {
780 static int getDensityFromProperty(char const* propName) {
781 char property[PROPERTY_VALUE_MAX];
782 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800783 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700784 density = atoi(property);
785 }
786 return density;
787 }
788 public:
789 static int getEmuDensity() {
790 return getDensityFromProperty("qemu.sf.lcd_density"); }
791 static int getBuildDensity() {
792 return getDensityFromProperty("ro.sf.lcd_density"); }
793 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700794
Dan Stoza7f7da322014-05-02 15:26:25 -0700795 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700796
Steven Thomas6d8110b2017-08-31 18:24:21 -0700797 ConditionalLock _l(mStateLock,
798 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800799 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700800 DisplayInfo info = DisplayInfo();
801
Dan Stoza9e56aa02015-11-02 13:00:03 -0800802 float xdpi = hwConfig->getDpiX();
803 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700804
805 if (type == DisplayDevice::DISPLAY_PRIMARY) {
806 // The density of the device is provided by a build property
807 float density = Density::getBuildDensity() / 160.0f;
808 if (density == 0) {
809 // the build doesn't provide a density -- this is wrong!
810 // use xdpi instead
811 ALOGE("ro.sf.lcd_density must be defined as a build property");
812 density = xdpi / 160.0f;
813 }
814 if (Density::getEmuDensity()) {
815 // if "qemu.sf.lcd_density" is specified, it overrides everything
816 xdpi = ydpi = density = Density::getEmuDensity();
817 density /= 160.0f;
818 }
819 info.density = density;
820
821 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700822 const auto display = getDefaultDisplayDeviceLocked();
823 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700824 } else {
825 // TODO: where should this value come from?
826 static const int TV_DENSITY = 213;
827 info.density = TV_DENSITY / 160.0f;
828 info.orientation = 0;
829 }
830
Dan Stoza9e56aa02015-11-02 13:00:03 -0800831 info.w = hwConfig->getWidth();
832 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700833 info.xdpi = xdpi;
834 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800835 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900836 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800837
Andy McFadden91b2ca82014-06-13 14:04:23 -0700838 // This is how far in advance a buffer must be queued for
839 // presentation at a given time. If you want a buffer to appear
840 // on the screen at time N, you must submit the buffer before
841 // (N - presentationDeadline).
842 //
843 // Normally it's one full refresh period (to give SF a chance to
844 // latch the buffer), but this can be reduced by configuring a
845 // DispSync offset. Any additional delays introduced by the hardware
846 // composer or panel must be accounted for here.
847 //
848 // We add an additional 1ms to allow for processing time and
849 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800850 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800851 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700852
853 // All non-virtual displays are currently considered secure.
854 info.secure = true;
855
Iris Chang7501ed62018-04-30 14:45:42 +0800856 if (type == DisplayDevice::DISPLAY_PRIMARY &&
857 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
858 std::swap(info.w, info.h);
859 }
860
Michael Wright28f24d02016-07-12 13:30:53 -0700861 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700862 }
863
Dan Stoza7f7da322014-05-02 15:26:25 -0700864 return NO_ERROR;
865}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700866
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700867status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
868 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700869 return BAD_VALUE;
870 }
871
872 // FIXME for now we always return stats for the primary display
873 memset(stats, 0, sizeof(*stats));
Lloyd Pique41be5d22018-06-21 13:11:48 -0700874 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
875 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700876 return NO_ERROR;
877}
878
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700879int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
880 const auto display = getDisplayDevice(displayToken);
881 if (!display) {
882 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800883 return BAD_VALUE;
884 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700885
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700886 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700887}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700888
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700889void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
890 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700891 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700892 return;
893 }
894
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700895 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700896 ALOGW("Trying to set config for virtual display");
897 return;
898 }
899
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700900 display->setActiveConfig(mode);
901 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700902}
903
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700904status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700905 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700906 Vector<DisplayInfo> configs;
907 getDisplayConfigs(displayToken, &configs);
908 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
909 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
910 configs.size());
911 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700912 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700913 const auto display = getDisplayDevice(displayToken);
914 if (!display) {
915 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
916 displayToken.get());
917 } else if (display->isVirtual()) {
918 ALOGW("Attempt to set active config %d for virtual display", mode);
919 } else {
920 setActiveConfigInternal(display, mode);
921 }
922 }));
923
Mathias Agopian888c8222012-08-04 21:10:38 -0700924 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700925}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700926status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
927 Vector<ColorMode>* outColorModes) {
928 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700929 return BAD_VALUE;
930 }
931
Michael Wright28f24d02016-07-12 13:30:53 -0700932 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700933 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
934 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700935 type = i;
936 break;
937 }
938 }
939
940 if (type < 0) {
941 return type;
942 }
943
Peiyong Lina52f0292018-03-14 17:26:31 -0700944 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700945 {
946 ConditionalLock _l(mStateLock,
947 std::this_thread::get_id() != mMainThreadId);
948 modes = getHwComposer().getColorModes(type);
949 }
Michael Wright28f24d02016-07-12 13:30:53 -0700950 outColorModes->clear();
951 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
952
953 return NO_ERROR;
954}
955
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700956ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
957 if (const auto display = getDisplayDevice(displayToken)) {
958 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700959 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700960 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700961}
962
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700963void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
964 Dataspace dataSpace, RenderIntent renderIntent) {
965 ColorMode currentMode = display->getActiveColorMode();
966 Dataspace currentDataSpace = display->getCompositionDataSpace();
967 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -0700968
Peiyong Lin38e9a562018-04-10 16:24:20 -0700969 if (mode == currentMode && dataSpace == currentDataSpace &&
970 renderIntent == currentRenderIntent) {
971 return;
972 }
973
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700974 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -0700975 ALOGW("Trying to set config for virtual display");
976 return;
977 }
978
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700979 display->setActiveColorMode(mode);
980 display->setCompositionDataSpace(dataSpace);
981 display->setActiveRenderIntent(renderIntent);
982 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800983
984 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700985 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
986 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -0700987}
988
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700989status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700990 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700991 Vector<ColorMode> modes;
992 getDisplayColorModes(displayToken, &modes);
993 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
994 if (mode < ColorMode::NATIVE || !exists) {
995 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
996 decodeColorMode(mode).c_str(), mode, displayToken.get());
997 return;
Michael Wright28f24d02016-07-12 13:30:53 -0700998 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700999 const auto display = getDisplayDevice(displayToken);
1000 if (!display) {
1001 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1002 decodeColorMode(mode).c_str(), mode, displayToken.get());
1003 } else if (display->isVirtual()) {
1004 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1005 decodeColorMode(mode).c_str(), mode);
1006 } else {
1007 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1008 RenderIntent::COLORIMETRIC);
1009 }
1010 }));
1011
Michael Wright28f24d02016-07-12 13:30:53 -07001012 return NO_ERROR;
1013}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001014
Svetoslavd85084b2014-03-20 10:28:31 -07001015status_t SurfaceFlinger::clearAnimationFrameStats() {
1016 Mutex::Autolock _l(mStateLock);
1017 mAnimFrameTracker.clearStats();
1018 return NO_ERROR;
1019}
1020
1021status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1022 Mutex::Autolock _l(mStateLock);
1023 mAnimFrameTracker.getStats(outStats);
1024 return NO_ERROR;
1025}
1026
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001027status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1028 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001029 Mutex::Autolock _l(mStateLock);
1030
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001031 const auto display = getDisplayDeviceLocked(displayToken);
1032 if (!display) {
1033 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001034 return BAD_VALUE;
1035 }
1036
Peiyong Linfb069302018-04-25 14:34:31 -07001037 // At this point the DisplayDeivce should already be set up,
1038 // meaning the luminance information is already queried from
1039 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001040 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001041 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1042 capabilities.getDesiredMaxLuminance(),
1043 capabilities.getDesiredMaxAverageLuminance(),
1044 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001045
1046 return NO_ERROR;
1047}
1048
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001049status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001050 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001051 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001052
Chia-I Wu90f669f2017-10-05 14:24:41 -07001053 if (mInjectVSyncs == enable) {
1054 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001055 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001056
1057 if (enable) {
1058 ALOGV("VSync Injections enabled");
1059 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001060 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001061 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001062 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001063 impl::EventThread::InterceptVSyncsCallback(),
1064 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001065 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001066 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001067 } else {
1068 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001069 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001070 }
1071
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001072 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001073 }));
1074
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001075 return NO_ERROR;
1076}
1077
1078status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001079 Mutex::Autolock _l(mStateLock);
1080
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001081 if (!mInjectVSyncs) {
1082 ALOGE("VSync Injections not enabled");
1083 return BAD_VALUE;
1084 }
1085 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1086 ALOGV("Injecting VSync inside SurfaceFlinger");
1087 mVSyncInjector->onInjectSyncEvent(when);
1088 }
1089 return NO_ERROR;
1090}
1091
Lloyd Pique755e3192018-01-31 16:46:15 -08001092status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1093 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001094 // Try to acquire a lock for 1s, fail gracefully
1095 const status_t err = mStateLock.timedLock(s2ns(1));
1096 const bool locked = (err == NO_ERROR);
1097 if (!locked) {
1098 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1099 return TIMED_OUT;
1100 }
1101
1102 outLayers->clear();
1103 mCurrentState.traverseInZOrder([&](Layer* layer) {
1104 outLayers->push_back(layer->getLayerDebugInfo());
1105 });
1106
1107 mStateLock.unlock();
1108 return NO_ERROR;
1109}
1110
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001111// ----------------------------------------------------------------------------
1112
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001113sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1114 ISurfaceComposer::VsyncSource vsyncSource) {
1115 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1116 return mSFEventThread->createEventConnection();
1117 } else {
1118 return mEventThread->createEventConnection();
1119 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001120}
1121
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001122// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001123
1124void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001125 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001126}
1127
1128void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001129 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001130}
1131
1132void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001133 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001134}
1135
1136void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001137 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001138 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001139}
1140
1141status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001142 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001143 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001144}
1145
1146status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001147 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001148 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001149 if (res == NO_ERROR) {
1150 msg->wait();
1151 }
1152 return res;
1153}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001154
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001155void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001156 do {
1157 waitForEvent();
1158 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001159}
1160
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001161void SurfaceFlinger::enableHardwareVsync() {
1162 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001163 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001164 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001165 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001166 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001167 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001168}
1169
Jesse Hall948fe0c2013-10-14 12:56:09 -07001170void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001171 Mutex::Autolock _l(mHWVsyncLock);
1172
Jesse Hall948fe0c2013-10-14 12:56:09 -07001173 if (makeAvailable) {
1174 mHWVsyncAvailable = true;
1175 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001176 // Hardware vsync is not currently available, so abort the resync
1177 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001178 return;
1179 }
1180
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001181 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1182 if (!getHwComposer().isConnected(displayId)) {
1183 return;
1184 }
1185
1186 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001187 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001188
Lloyd Pique41be5d22018-06-21 13:11:48 -07001189 mPrimaryDispSync->reset();
1190 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001191
1192 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001193 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001194 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001195 mPrimaryHWVsyncEnabled = true;
1196 }
1197}
1198
Jesse Hall948fe0c2013-10-14 12:56:09 -07001199void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001200 Mutex::Autolock _l(mHWVsyncLock);
1201 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001202 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001203 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001204 mPrimaryHWVsyncEnabled = false;
1205 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001206 if (makeUnavailable) {
1207 mHWVsyncAvailable = false;
1208 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001209}
1210
Tim Murray4a4e4a22016-04-19 16:29:23 +00001211void SurfaceFlinger::resyncWithRateLimit() {
1212 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001213
1214 // No explicit locking is needed here since EventThread holds a lock while calling this method
1215 static nsecs_t sLastResyncAttempted = 0;
1216 const nsecs_t now = systemTime();
1217 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001218 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001219 }
Dan Stoza57164302017-05-08 14:03:54 -07001220 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001221}
1222
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001223void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1224 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001225 ATRACE_NAME("SF onVsync");
1226
Steven Thomas3cfac282017-02-06 12:29:30 -08001227 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001228 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001229 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001230 return;
1231 }
1232
1233 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001234 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001235 return;
1236 }
1237
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001238 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1239 // For now, we don't do anything with external display vsyncs.
1240 return;
1241 }
1242
Jamie Gennisd1700752013-10-14 12:22:52 -07001243 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001244
Jamie Gennisd1700752013-10-14 12:22:52 -07001245 { // Scope for the lock
1246 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001247 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001248 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001249 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001250 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001251
1252 if (needsHwVsync) {
1253 enableHardwareVsync();
1254 } else {
1255 disableHardwareVsync(false);
1256 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001257}
1258
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001259void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001260 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1261 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001262}
1263
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001264void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001265 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001266 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001267 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001268
Lloyd Piqueba04e622017-12-14 17:11:26 -08001269 // Ignore events that do not have the right sequenceId.
1270 if (sequenceId != getBE().mComposerSequenceId) {
1271 return;
1272 }
1273
Steven Thomasb02664d2017-07-26 18:48:28 -07001274 // Only lock if we're not on the main thread. This function is normally
1275 // called on a hwbinder thread, but for the primary display it's called on
1276 // the main thread with the state lock already held, so don't attempt to
1277 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001278 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001279
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001280 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001281
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001282 if (std::this_thread::get_id() == mMainThreadId) {
1283 // Process all pending hot plug events immediately if we are on the main thread.
1284 processDisplayHotplugEventsLocked();
1285 }
1286
Lloyd Piqueba04e622017-12-14 17:11:26 -08001287 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001288}
1289
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001290void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001291 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001292 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001293 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001294 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001295 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001296}
1297
Dan Stoza9e56aa02015-11-02 13:00:03 -08001298void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001299 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001300 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001301 getHwComposer().setVsyncEnabled(disp,
1302 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001303}
1304
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001305// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001306void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001307 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001308 // Clear the drawing state so that the logic inside of
1309 // handleTransactionLocked will fire. It will determine the delta between
1310 // mCurrentState and mDrawingState and re-apply all changes when we make the
1311 // transition.
1312 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001313 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001314 mDisplays.clear();
1315}
1316
Steven Thomas050b2c82017-03-06 11:45:16 -08001317void SurfaceFlinger::updateVrFlinger() {
1318 if (!mVrFlinger)
1319 return;
1320 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001321 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001322 return;
1323 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001324
David Sodman105b7dc2017-11-04 20:28:14 -07001325 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001326 ALOGE("Vr flinger is only supported for remote hardware composer"
1327 " service connections. Ignoring request to transition to vr"
1328 " flinger.");
1329 mVrFlingerRequestsDisplay = false;
1330 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001331 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001332
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001333 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001334
Steven Thomas0123ac62018-07-12 11:32:34 -07001335 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001336 LOG_ALWAYS_FATAL_IF(!display);
1337 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001338 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1339 // called below. Clear the reference now so we don't accidentally use it
1340 // later.
1341 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001342
Steven Thomasb02664d2017-07-26 18:48:28 -07001343 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001344 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001345 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001346
Steven Thomasb02664d2017-07-26 18:48:28 -07001347 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001348 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001349 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1350 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001351 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001352
David Sodman105b7dc2017-11-04 20:28:14 -07001353 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1354 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001355
1356 if (vrFlingerRequestsDisplay) {
1357 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001358 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001359
1360 mVisibleRegionsDirty = true;
1361 invalidateHwcGeometry();
1362
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001363 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001364 display = getDefaultDisplayDeviceLocked();
1365 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001366 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001367
Steven Thomasb02664d2017-07-26 18:48:28 -07001368 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001369 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001370 const nsecs_t period = activeConfig->getVsyncPeriod();
1371 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001372
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001373 // The present fences returned from vr_hwc are not an accurate
1374 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001375 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1376 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001377
Steven Thomasb02664d2017-07-26 18:48:28 -07001378 // Use phase of 0 since phase is not known.
1379 // Use latency of 0, which will snap to the ideal latency.
1380 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001381
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001382 resyncToHardwareVsync(false);
1383
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001384 android_atomic_or(1, &mRepaintEverything);
1385 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001386}
1387
Mathias Agopian4fec8732012-06-29 14:12:52 -07001388void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001389 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001390 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001391 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001392 bool frameMissed = !mHadClientComposition &&
1393 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001394 (mPreviousPresentFence->getSignalTime() ==
1395 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001396 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001397 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001398 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001399 mTimeStats.incrementMissedFrames();
1400 if (mPropagateBackpressure) {
1401 signalLayerUpdate();
1402 break;
1403 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001404 }
Dan Stoza50182882016-07-08 12:02:20 -07001405
Steven Thomas050b2c82017-03-06 11:45:16 -08001406 // Now that we're going to make it to the handleMessageTransaction()
1407 // call below it's safe to call updateVrFlinger(), which will
1408 // potentially trigger a display handoff.
1409 updateVrFlinger();
1410
Dan Stoza6b9454d2014-11-07 16:00:59 -08001411 bool refreshNeeded = handleMessageTransaction();
1412 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001413 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001414 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001415 // Signal a refresh if a transaction modified the window state,
1416 // a new buffer was latched, or if HWC has requested a full
1417 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001418 signalRefresh();
1419 }
1420 break;
1421 }
1422 case MessageQueue::REFRESH: {
1423 handleMessageRefresh();
1424 break;
1425 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001426 }
1427}
1428
Dan Stoza6b9454d2014-11-07 16:00:59 -08001429bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001430 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001431 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001432 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001433 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001434 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001435 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001436}
1437
Dan Stoza6b9454d2014-11-07 16:00:59 -08001438bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001439 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001440 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001441}
1442
1443void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001444 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001445
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001446 mRefreshPending = false;
1447
David Sodman2b406362017-12-15 13:33:47 -08001448 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001449 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001450 calculateWorkingSet();
David Sodman2b406362017-12-15 13:33:47 -08001451 beginFrame();
1452 prepareFrame();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001453 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001454 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001455 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001456 doComposition();
David Sodman2b406362017-12-15 13:33:47 -08001457 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001458
Dan Stozabfbffeb2016-07-21 14:49:33 -07001459 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001460 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001461 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001462 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001463 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001464 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001465
Dan Stoza9e56aa02015-11-02 13:00:03 -08001466 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001467}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001468
David Sodman79bba0e2018-08-05 18:07:49 -07001469void SurfaceFlinger::calculateWorkingSet() {
1470 ATRACE_CALL();
1471 ALOGV(__FUNCTION__);
1472
David Sodman79bba0e2018-08-05 18:07:49 -07001473 // build the h/w work list
1474 if (CC_UNLIKELY(mGeometryInvalid)) {
1475 mGeometryInvalid = false;
1476 for (const auto& [token, display] : mDisplays) {
1477 const auto displayId = display->getId();
1478 if (displayId >= 0) {
1479 const Vector<sp<Layer>>& currentLayers(
1480 display->getVisibleLayersSortedByZ());
1481 for (size_t i = 0; i < currentLayers.size(); i++) {
1482 const auto& layer = currentLayers[i];
1483
1484 if (!layer->hasHwcLayer(displayId)) {
1485 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1486 layer->forceClientComposition(displayId);
1487 continue;
1488 }
1489 }
1490
1491 layer->setGeometry(display, i);
1492 if (mDebugDisableHWC || mDebugRegion) {
1493 layer->forceClientComposition(displayId);
1494 }
1495 }
1496 }
1497 }
1498 }
1499
1500 // Set the per-frame data
1501 for (const auto& [token, display] : mDisplays) {
1502 const auto displayId = display->getId();
1503 if (displayId < 0) {
1504 continue;
1505 }
1506
1507 if (mDrawingState.colorMatrixChanged) {
1508 display->setColorTransform(mDrawingState.colorMatrix);
1509 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1510 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1511 "display %d: %d", displayId, result);
1512 }
1513 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1514 if (layer->isHdrY410()) {
1515 layer->forceClientComposition(displayId);
1516 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1517 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1518 !display->hasHDR10Support()) {
1519 layer->forceClientComposition(displayId);
1520 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1521 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1522 !display->hasHLGSupport()) {
1523 layer->forceClientComposition(displayId);
1524 }
1525
1526 if (layer->getForceClientComposition(displayId)) {
1527 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1528 layer->setCompositionType(displayId, HWC2::Composition::Client);
1529 continue;
1530 }
1531
1532 layer->setPerFrameData(display);
1533 }
1534
1535 if (hasWideColorDisplay) {
1536 ColorMode colorMode;
1537 Dataspace dataSpace;
1538 RenderIntent renderIntent;
1539 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1540 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1541 }
1542 }
1543
1544 mDrawingState.colorMatrixChanged = false;
David Sodman79bba0e2018-08-05 18:07:49 -07001545}
1546
Mathias Agopiancd60f992012-08-16 16:28:27 -07001547void SurfaceFlinger::doDebugFlashRegions()
1548{
1549 // is debugging enabled
1550 if (CC_LIKELY(!mDebugRegion))
1551 return;
1552
1553 const bool repaintEverything = mRepaintEverything;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001554 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001555 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001556 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001557 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001558 if (!dirtyRegion.isEmpty()) {
1559 // redraw the whole screen
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001560 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001561
1562 // and draw the dirty region
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001563 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001564 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001565 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1566
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001567 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001568 }
1569 }
1570 }
1571
1572 postFramebuffer();
1573
1574 if (mDebugRegion > 1) {
1575 usleep(mDebugRegion * 1000);
1576 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001577
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001578 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001579 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001580 continue;
1581 }
1582
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001583 status_t result = display->prepareFrame(*getBE().mHwc);
1584 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001585 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001586 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001587}
1588
Adrian Roos1e1a1282017-11-01 19:05:31 +01001589void SurfaceFlinger::doTracing(const char* where) {
1590 ATRACE_CALL();
1591 ATRACE_NAME(where);
1592 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001593 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001594 }
1595}
1596
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001597void SurfaceFlinger::logLayerStats() {
1598 ATRACE_CALL();
1599 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001600 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001601 if (display->isPrimary()) {
1602 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001603 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001604 }
1605 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001606
1607 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001608 }
1609}
1610
David Sodman2b406362017-12-15 13:33:47 -08001611void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001612{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001613 ATRACE_CALL();
1614 ALOGV("preComposition");
1615
David Sodman2b406362017-12-15 13:33:47 -08001616 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1617
Mathias Agopiancd60f992012-08-16 16:28:27 -07001618 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001619 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001620 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001621 needExtraInvalidate = true;
1622 }
Robert Carr2047fae2016-11-28 14:09:09 -08001623 });
1624
Mathias Agopiancd60f992012-08-16 16:28:27 -07001625 if (needExtraInvalidate) {
1626 signalLayerUpdate();
1627 }
1628}
1629
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001630void SurfaceFlinger::updateCompositorTiming(
1631 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1632 std::shared_ptr<FenceTime>& presentFenceTime) {
1633 // Update queue of past composite+present times and determine the
1634 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001635 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001636 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001637 while (!getBE().mCompositePresentTimes.empty()) {
1638 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001639 // Cached values should have been updated before calling this method,
1640 // which helps avoid duplicate syscalls.
1641 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1642 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1643 break;
1644 }
1645 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001646 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001647 }
1648
1649 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001650 while (getBE().mCompositePresentTimes.size() > 16) {
1651 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001652 }
1653
Brian Andersond0010582017-03-07 13:20:31 -08001654 setCompositorTimingSnapped(
1655 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1656}
1657
1658void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1659 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001660 // Integer division and modulo round toward 0 not -inf, so we need to
1661 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001662 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001663 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1664 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1665
Brian Andersond0010582017-03-07 13:20:31 -08001666 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1667 if (idealLatency <= 0) {
1668 idealLatency = vsyncInterval;
1669 }
1670
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001671 // Snap the latency to a value that removes scheduling jitter from the
1672 // composition and present times, which often have >1ms of jitter.
1673 // Reducing jitter is important if an app attempts to extrapolate
1674 // something (such as user input) to an accurate diasplay time.
1675 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1676 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001677 nsecs_t bias = vsyncInterval / 2;
1678 int64_t extraVsyncs =
1679 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1680 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1681 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001682
David Sodman99974d22017-11-28 12:04:33 -08001683 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1684 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1685 getBE().mCompositorTiming.interval = vsyncInterval;
1686 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001687}
1688
David Sodman2b406362017-12-15 13:33:47 -08001689void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001690{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001691 ATRACE_CALL();
1692 ALOGV("postComposition");
1693
Brian Anderson3546a3f2016-07-14 11:51:14 -07001694 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001695 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001696 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001697 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001698 }
1699
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001700 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001701 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001702
David Sodman73beded2017-11-15 11:56:06 -08001703 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001704 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001705 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001706 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001707 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001708 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001709 } else {
1710 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1711 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001712
David Sodman73beded2017-11-15 11:56:06 -08001713 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001714 mPreviousPresentFence =
1715 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1716 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001717 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001718
Lloyd Pique41be5d22018-06-21 13:11:48 -07001719 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1720 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001721
David Sodman2b406362017-12-15 13:33:47 -08001722 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001723 // when we started doing work for this frame, but that should be okay
1724 // since updateCompositorTiming has snapping logic.
1725 updateCompositorTiming(
David Sodman2b406362017-12-15 13:33:47 -08001726 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001727 CompositorTiming compositorTiming;
1728 {
David Sodman99974d22017-11-28 12:04:33 -08001729 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1730 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001731 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001732
Robert Carr2047fae2016-11-28 14:09:09 -08001733 mDrawingState.traverseInZOrder([&](Layer* layer) {
1734 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001735 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001736 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001737 recordBufferingStats(layer->getName().string(),
1738 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001739 }
Robert Carr2047fae2016-11-28 14:09:09 -08001740 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001741
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001742 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001743 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001744 enableHardwareVsync();
1745 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001746 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001747 }
1748 }
1749
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001750 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001751 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001752 enableHardwareVsync();
1753 }
1754 }
1755
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001756 if (mAnimCompositionPending) {
1757 mAnimCompositionPending = false;
1758
Brian Anderson4e606e32017-03-16 15:34:57 -07001759 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001760 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001761 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001762 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001763 // The HWC doesn't support present fences, so use the refresh
1764 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001765 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001766 mAnimFrameTracker.setActualPresentTime(presentTime);
1767 }
1768 mAnimFrameTracker.advanceFrame();
1769 }
Dan Stozab90cf072015-03-05 11:05:59 -08001770
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001771 mTimeStats.incrementTotalFrames();
1772 if (mHadClientComposition) {
1773 mTimeStats.incrementClientCompositionFrames();
1774 }
1775
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001776 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001777 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001778 return;
1779 }
1780
1781 nsecs_t currentTime = systemTime();
1782 if (mHasPoweredOff) {
1783 mHasPoweredOff = false;
1784 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001785 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001786 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001787 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1788 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001789 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001790 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001791 }
David Sodman4a36e932017-11-07 14:29:47 -08001792 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001793 }
David Sodman4a36e932017-11-07 14:29:47 -08001794 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001795
1796 {
1797 std::lock_guard lock(mTexturePoolMutex);
1798 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1799 if (refillCount > 0) {
1800 const size_t offset = mTexturePool.size();
1801 mTexturePool.resize(mTexturePoolSize);
1802 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1803 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1804 }
1805 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001806}
1807
1808void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001809 ATRACE_CALL();
1810 ALOGV("rebuildLayerStacks");
1811
Mathias Agopiancd60f992012-08-16 16:28:27 -07001812 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001813 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001814 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001815 mVisibleRegionsDirty = false;
1816 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001817
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001818 for (const auto& pair : mDisplays) {
1819 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001820 Region opaqueRegion;
1821 Region dirtyRegion;
1822 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001823 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001824 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001825 const Rect bounds = display->getBounds();
1826 if (display->isPoweredOn()) {
1827 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001828
Jeff Sharkey76488112017-02-27 14:15:18 -07001829 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001830 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001831 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001832 Region drawRegion(tr.transform(
1833 layer->visibleNonTransparentRegion));
1834 drawRegion.andSelf(bounds);
1835 if (!drawRegion.isEmpty()) {
1836 layersSortedByZ.add(layer);
1837 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001838 // Clear out the HWC layer if this layer was
1839 // previously visible, but no longer is
1840 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001841 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001842 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001843 // WM changes display->layerStack upon sleep/awake.
1844 // Here we make sure we delete the HWC layers even if
1845 // WM changed their layer stack.
1846 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001847 }
1848
1849 // If a layer is not going to get a release fence because
1850 // it is invisible, but it is also going to release its
1851 // old buffer, add it to the list of layers needing
1852 // fences.
1853 if (hwcLayerDestroyed) {
1854 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1855 mLayersWithQueuedFrames.cend(), layer);
1856 if (found != mLayersWithQueuedFrames.cend()) {
1857 layersNeedingFences.add(layer);
1858 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001859 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001860 });
1861 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001862 display->setVisibleLayersSortedByZ(layersSortedByZ);
1863 display->setLayersNeedingFences(layersNeedingFences);
1864 display->undefinedRegion.set(bounds);
1865 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1866 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001867 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001868 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001869}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001870
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001871// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001872// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001873// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001874// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001875// The returned HDR data space is one of
1876// - Dataspace::UNKNOWN
1877// - Dataspace::BT2020_HLG
1878// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001879Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1880 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001881 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001882 *outHdrDataSpace = Dataspace::UNKNOWN;
1883
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001884 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001885 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001886 case Dataspace::V0_SCRGB:
1887 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001888 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001889 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001890 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001891 case Dataspace::BT2020_PQ:
1892 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001893 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001894 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001895 case Dataspace::BT2020_HLG:
1896 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001897 // When there's mixed PQ content and HLG content, we set the HDR
1898 // data space to be BT2020_PQ and convert HLG to PQ.
1899 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1900 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001901 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001902 break;
1903 default:
1904 break;
1905 }
Romain Guy54f154a2017-10-24 21:40:32 +01001906 }
1907
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001908 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001909}
1910
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001911// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001912void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1913 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001914 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1915 *outMode = ColorMode::NATIVE;
1916 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001917 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001918 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001919 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001920
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001921 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001922 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001923
Peiyong Lindfde5112018-06-05 10:58:41 -07001924 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001925 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001926 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001927 if (isHdr) {
1928 bestDataSpace = hdrDataSpace;
1929 }
1930
Chia-I Wu0d711262018-05-21 15:19:35 -07001931 RenderIntent intent;
1932 switch (mDisplayColorSetting) {
1933 case DisplayColorSetting::MANAGED:
1934 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001935 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001936 break;
1937 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001938 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001939 break;
1940 default: // vendor display color setting
1941 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1942 break;
1943 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001944
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001945 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001946}
1947
David Sodman2b406362017-12-15 13:33:47 -08001948void SurfaceFlinger::beginFrame()
1949{
1950 for (const auto& [token, display] : mDisplays) {
1951 bool dirty = !display->getDirtyRegion(mRepaintEverything).isEmpty();
1952 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
1953 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
1954
1955 // If nothing has changed (!dirty), don't recompose.
1956 // If something changed, but we don't currently have any visible layers,
1957 // and didn't when we last did a composition, then skip it this time.
1958 // The second rule does two things:
1959 // - When all layers are removed from a display, we'll emit one black
1960 // frame, then nothing more until we get new layers.
1961 // - When a display is created with a private layer stack, we won't
1962 // emit any black frames until a layer is added to the layer stack.
1963 bool mustRecompose = dirty && !(empty && wasEmpty);
1964
1965 ALOGV_IF(display->isVirtual(), "Display %d: %s composition (%sdirty %sempty %swasEmpty)",
1966 display->getId(), mustRecompose ? "doing" : "skipping", dirty ? "+" : "-",
1967 empty ? "+" : "-", wasEmpty ? "+" : "-");
1968
1969 display->beginFrame(mustRecompose);
1970
1971 if (mustRecompose) {
1972 display->lastCompositionHadVisibleLayers = !empty;
1973 }
1974 }
1975}
1976
1977void SurfaceFlinger::prepareFrame()
1978{
1979 for (const auto& [token, display] : mDisplays) {
1980 if (!display->isPoweredOn()) {
1981 continue;
1982 }
1983
1984 status_t result = display->prepareFrame(*getBE().mHwc);
1985 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
1986 display->getId(), result, strerror(-result));
1987 }
1988}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001989
Mathias Agopiancd60f992012-08-16 16:28:27 -07001990void SurfaceFlinger::doComposition() {
1991 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001992 ALOGV("doComposition");
1993
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001994 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001995 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001996 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001997 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001998 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08001999
2000 // repaint the framebuffer (if needed)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002001 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002002
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002003 display->dirtyRegion.clear();
2004 display->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002005 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002006 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002007 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002008}
2009
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002010void SurfaceFlinger::postFramebuffer()
2011{
Mathias Agopian841cde52012-03-01 15:44:37 -08002012 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002013 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002014
Mathias Agopiana44b0412011-10-16 18:46:35 -07002015 const nsecs_t now = systemTime();
2016 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002017
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002018 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002019 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002020 continue;
2021 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07002022 const auto displayId = display->getId();
2023 if (displayId >= 0) {
2024 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002025 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002026 display->onSwapBuffersCompleted();
2027 display->makeCurrent();
2028 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002029 sp<Fence> releaseFence = Fence::NO_FENCE;
2030
Chia-I Wu7b549592017-11-15 09:14:57 -08002031 // The layer buffer from the previous frame (if any) is released
2032 // by HWC only when the release fence from this frame (if any) is
2033 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002034 auto hwcLayer = layer->getHwcLayer(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002035 if (displayId >= 0) {
2036 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
2037 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002038
2039 // If the layer was client composited in the previous frame, we
2040 // need to merge with the previous client target acquire fence.
2041 // Since we do not track that, always merge with the current
2042 // client target acquire fence when it is available, even though
2043 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002044 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002045 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002046 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002047 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002048
David Sodmanb8af7922017-12-21 15:17:55 -08002049 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002050 }
Chia-I Wu83806892017-11-16 10:50:20 -08002051
2052 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002053 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002054 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002055 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002056 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002057 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002058 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002059 }
2060 }
2061
Dominik Laskowski7e045462018-05-30 13:02:02 -07002062 if (displayId >= 0) {
2063 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002064 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002065 }
2066
Mathias Agopiana44b0412011-10-16 18:46:35 -07002067 mLastSwapBufferTime = systemTime() - now;
2068 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002069
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002070 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002071 const auto display = getDefaultDisplayDeviceLocked();
2072 if (display && getHwComposer().isConnected(display->getId())) {
2073 const uint32_t flipCount = display->getPageFlipCount();
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002074 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2075 logFrameStats();
2076 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002077 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002078}
2079
Mathias Agopian87baae12012-07-31 12:38:26 -07002080void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002081{
Mathias Agopian841cde52012-03-01 15:44:37 -08002082 ATRACE_CALL();
2083
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002084 // here we keep a copy of the drawing state (that is the state that's
2085 // going to be overwritten by handleTransactionLocked()) outside of
2086 // mStateLock so that the side-effects of the State assignment
2087 // don't happen with mStateLock held (which can cause deadlocks).
2088 State drawingState(mDrawingState);
2089
Mathias Agopianca4d3602011-05-19 15:38:14 -07002090 Mutex::Autolock _l(mStateLock);
2091 const nsecs_t now = systemTime();
2092 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002093
Mathias Agopianca4d3602011-05-19 15:38:14 -07002094 // Here we're guaranteed that some transaction flags are set
2095 // so we can call handleTransactionLocked() unconditionally.
2096 // We call getTransactionFlags(), which will also clear the flags,
2097 // with mStateLock held to guarantee that mCurrentState won't change
2098 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002099
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002100 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002101 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002102 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002103
Mathias Agopianca4d3602011-05-19 15:38:14 -07002104 mLastTransactionTime = systemTime() - now;
2105 mDebugInTransaction = 0;
2106 invalidateHwcGeometry();
2107 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002108}
2109
Dominik Laskowski7e045462018-05-30 13:02:02 -07002110DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002111 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002112 // Figure out whether the event is for the primary display or an
2113 // external display by matching the Hwc display id against one for a
2114 // connected display. If we did not find a match, we then check what
2115 // displays are not already connected to determine the type. If we don't
2116 // have a connected primary display, we assume the new display is meant to
2117 // be the primary display, and then if we don't have an external display,
2118 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002119 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2120 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002121 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002122 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002123 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002124 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002125 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002126 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002127 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002128 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002129 return DisplayDevice::DISPLAY_EXTERNAL;
2130 }
2131
2132 return DisplayDevice::DISPLAY_ID_INVALID;
2133}
2134
Lloyd Piqueba04e622017-12-14 17:11:26 -08002135void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2136 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002137 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002138 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002139 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002140 continue;
2141 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002142
2143 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2144 ALOGE("External displays are not supported by the vr hardware composer.");
2145 continue;
2146 }
2147
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002148 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002149 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002150 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002151 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002152 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002153
2154 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002155 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002156 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002157 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002158 DisplayDeviceState info;
2159 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002160 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2161 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002162 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002163 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002164 mInterceptor->saveDisplayCreation(info);
2165 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002166 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002167 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002168
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002169 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002170 if (idx >= 0) {
2171 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002172 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002173 mCurrentState.displays.removeItemsAt(idx);
2174 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002175 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002176 }
2177
2178 processDisplayChangesLocked();
2179 }
2180
2181 mPendingHotplugEvents.clear();
2182}
2183
Lloyd Pique99d3da52018-01-22 17:48:03 -08002184sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002185 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002186 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002187 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002188 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002189 HdrCapabilities hdrCapabilities;
2190 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002191
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002192 if (hasWideColorDisplay && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002193 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002194 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002195 if (isWideColorMode(colorMode)) {
2196 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002197 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002198
Dominik Laskowski7e045462018-05-30 13:02:02 -07002199 std::vector<RenderIntent> renderIntents =
2200 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002201 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002202 }
tangrobin6753a022018-08-10 10:58:54 +08002203 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002204
tangrobin6753a022018-08-10 10:58:54 +08002205 if (displayId >= 0) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002206 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2207 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2208 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002209
2210 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2211 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2212
2213 /*
2214 * Create our display's surface
2215 */
2216 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2217 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002218 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002219 renderSurface->setNativeWindow(nativeWindow.get());
2220 const int displayWidth = renderSurface->queryWidth();
2221 const int displayHeight = renderSurface->queryHeight();
2222
2223 // Make sure that composition can never be stalled by a virtual display
2224 // consumer that isn't processing buffers fast enough. We have to do this
2225 // in two places:
2226 // * Here, in case the display is composed entirely by HWC.
2227 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2228 // window's swap interval in eglMakeCurrent, so they'll override the
2229 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002230 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002231 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2232 }
2233
2234 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002235 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002236
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002237 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002238 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2239 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2240 displayHeight, hasWideColorGamut, hdrCapabilities,
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002241 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002242
2243 if (maxFrameBufferAcquiredBuffers >= 3) {
2244 nativeWindowSurface->preallocateBuffers();
2245 }
2246
2247 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002248 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2249 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002250 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002251 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002252 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002253 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002254 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002255 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002256 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002257 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002258 display->setLayerStack(state.layerStack);
2259 display->setProjection(state.orientation, state.viewport, state.frame);
2260 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002261
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002262 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002263}
2264
Lloyd Pique347200f2017-12-14 17:00:15 -08002265void SurfaceFlinger::processDisplayChangesLocked() {
2266 // here we take advantage of Vector's copy-on-write semantics to
2267 // improve performance by skipping the transaction entirely when
2268 // know that the lists are identical
2269 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2270 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2271 if (!curr.isIdenticalTo(draw)) {
2272 mVisibleRegionsDirty = true;
2273 const size_t cc = curr.size();
2274 size_t dc = draw.size();
2275
2276 // find the displays that were removed
2277 // (ie: in drawing state but not in current state)
2278 // also handle displays that changed
2279 // (ie: displays that are in both lists)
2280 for (size_t i = 0; i < dc;) {
2281 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2282 if (j < 0) {
2283 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002284 // Call makeCurrent() on the primary display so we can
2285 // be sure that nothing associated with this display
2286 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002287 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2288 defaultDisplay->makeCurrent();
2289 }
2290 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2291 display->disconnect(getHwComposer());
2292 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002293 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2294 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2295 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2296 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2297 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002298 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002299 } else {
2300 // this display is in both lists. see if something changed.
2301 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002302 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002303 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2304 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2305 if (state_binder != draw_binder) {
2306 // changing the surface is like destroying and
2307 // recreating the DisplayDevice, so we just remove it
2308 // from the drawing state, so that it get re-added
2309 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002310 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2311 display->disconnect(getHwComposer());
2312 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002313 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002314 mDrawingState.displays.removeItemsAt(i);
2315 dc--;
2316 // at this point we must loop to the next item
2317 continue;
2318 }
2319
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002320 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002321 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002322 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002323 }
2324 if ((state.orientation != draw[i].orientation) ||
2325 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002326 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002327 }
2328 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002329 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002330 }
2331 }
2332 }
2333 ++i;
2334 }
2335
2336 // find displays that were added
2337 // (ie: in current state but not in drawing state)
2338 for (size_t i = 0; i < cc; i++) {
2339 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2340 const DisplayDeviceState& state(curr[i]);
2341
2342 sp<DisplaySurface> dispSurface;
2343 sp<IGraphicBufferProducer> producer;
2344 sp<IGraphicBufferProducer> bqProducer;
2345 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002346 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002347
Dominik Laskowski7e045462018-05-30 13:02:02 -07002348 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002349 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002350 // Virtual displays without a surface are dormant:
2351 // they have external state (layer stack, projection,
2352 // etc.) but no internal state (i.e. a DisplayDevice).
2353 if (state.surface != nullptr) {
2354 // Allow VR composer to use virtual displays.
2355 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2356 int width = 0;
2357 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2358 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2359 int height = 0;
2360 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2361 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2362 int intFormat = 0;
2363 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2364 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002365 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002366
Dominik Laskowski7e045462018-05-30 13:02:02 -07002367 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2368 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002369 }
2370
2371 // TODO: Plumb requested format back up to consumer
2372
2373 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002374 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002375 bqProducer, bqConsumer,
2376 state.displayName);
2377
2378 dispSurface = vds;
2379 producer = vds;
2380 }
2381 } else {
2382 ALOGE_IF(state.surface != nullptr,
2383 "adding a supported display, but rendering "
2384 "surface is provided (%p), ignoring it",
2385 state.surface.get());
2386
Dominik Laskowski7e045462018-05-30 13:02:02 -07002387 displayId = state.type;
2388 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002389 producer = bqProducer;
2390 }
2391
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002392 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002393 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002394 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002395 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002396 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002397 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002398 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2399 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2400 true);
2401 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2402 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2403 true);
2404 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002405 }
2406 }
2407 }
2408 }
2409 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002410
2411 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002412}
2413
Mathias Agopian87baae12012-07-31 12:38:26 -07002414void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002415{
Dan Stoza7dde5992015-05-22 09:51:44 -07002416 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002417 mCurrentState.traverseInZOrder([](Layer* layer) {
2418 layer->notifyAvailableFrames();
2419 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002420
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002421 /*
2422 * Traversal of the children
2423 * (perform the transaction for each of them if needed)
2424 */
2425
Mathias Agopian3559b072012-08-15 13:46:03 -07002426 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002427 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002428 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002429 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002430
2431 const uint32_t flags = layer->doTransaction(0);
2432 if (flags & Layer::eVisibleRegion)
2433 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002434 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002435 }
2436
2437 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002438 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002439 */
2440
Mathias Agopiane57f2922012-08-09 16:29:12 -07002441 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002442 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002443 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002444 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002445
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002446 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002447 // The transform hint might have changed for some layers
2448 // (either because a display has changed, or because a layer
2449 // as changed).
2450 //
2451 // Walk through all the layers in currentLayers,
2452 // and update their transform hint.
2453 //
2454 // If a layer is visible only on a single display, then that
2455 // display is used to calculate the hint, otherwise we use the
2456 // default display.
2457 //
2458 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2459 // the hint is set before we acquire a buffer from the surface texture.
2460 //
2461 // NOTE: layer transactions have taken place already, so we use their
2462 // drawing state. However, SurfaceFlinger's own transaction has not
2463 // happened yet, so we must use the current state layer list
2464 // (soon to become the drawing state list).
2465 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002466 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002467 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002468 bool first = true;
2469 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002470 // NOTE: we rely on the fact that layers are sorted by
2471 // layerStack first (so we don't have to traverse the list
2472 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002473 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002474 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002475 currentlayerStack = layerStack;
2476 // figure out if this layerstack is mirrored
2477 // (more than one display) if so, pick the default display,
2478 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002479 hintDisplay = nullptr;
2480 for (const auto& [token, display] : mDisplays) {
2481 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2482 if (hintDisplay) {
2483 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002484 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002485 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002486 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002487 }
2488 }
2489 }
2490 }
Chet Haase91d25932013-04-11 15:24:55 -07002491
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002492 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002493 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2494 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002495
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002496 // could be null when this layer is using a layerStack
2497 // that is not visible on any display. Also can occur at
2498 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002499 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002500 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002501
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002502 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002503 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002504 if (hintDisplay) {
2505 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002506 }
Robert Carr2047fae2016-11-28 14:09:09 -08002507
2508 first = false;
2509 });
Mathias Agopian84300952012-11-21 16:02:13 -08002510 }
2511
2512
Mathias Agopian3559b072012-08-15 13:46:03 -07002513 /*
2514 * Perform our own transaction if needed
2515 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002516
2517 if (mLayersAdded) {
2518 mLayersAdded = false;
2519 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002520 mVisibleRegionsDirty = true;
2521 }
2522
2523 // some layers might have been removed, so
2524 // we need to update the regions they're exposing.
2525 if (mLayersRemoved) {
2526 mLayersRemoved = false;
2527 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002528 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002529 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002530 // this layer is not visible anymore
2531 // TODO: we could traverse the tree from front to back and
2532 // compute the actual visible region
2533 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002534 Region visibleReg;
2535 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002536 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002537 }
Robert Carr2047fae2016-11-28 14:09:09 -08002538 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002539 }
2540
2541 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002542
2543 updateCursorAsync();
2544}
2545
2546void SurfaceFlinger::updateCursorAsync()
2547{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002548 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002549 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002550 continue;
2551 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002552
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002553 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2554 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002555 }
2556 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002557}
2558
2559void SurfaceFlinger::commitTransaction()
2560{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002561 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002562 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002563 for (const auto& l : mLayersPendingRemoval) {
2564 recordBufferingStats(l->getName().string(),
2565 l->getOccupancyHistory(true));
2566 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002567 }
2568 mLayersPendingRemoval.clear();
2569 }
2570
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002571 // If this transaction is part of a window animation then the next frame
2572 // we composite should be considered an animation as well.
2573 mAnimCompositionPending = mAnimTransactionPending;
2574
Mathias Agopian4fec8732012-06-29 14:12:52 -07002575 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002576 // clear the "changed" flags in current state
2577 mCurrentState.colorMatrixChanged = false;
2578
Robert Carr1f0a16a2016-10-24 16:27:39 -07002579 mDrawingState.traverseInZOrder([](Layer* layer) {
2580 layer->commitChildList();
2581 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002582 mTransactionPending = false;
2583 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002584 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002585}
2586
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002587void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2588 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002589 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002590 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002591
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002592 Region aboveOpaqueLayers;
2593 Region aboveCoveredLayers;
2594 Region dirty;
2595
Mathias Agopian87baae12012-07-31 12:38:26 -07002596 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002597
Robert Carr2047fae2016-11-28 14:09:09 -08002598 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002599 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002600 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002601
Jesse Hall01e29052013-02-19 16:13:35 -08002602 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002603 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002604 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002605 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002606
Mathias Agopianab028732010-03-16 16:41:46 -07002607 /*
2608 * opaqueRegion: area of a surface that is fully opaque.
2609 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002610 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002611
2612 /*
2613 * visibleRegion: area of a surface that is visible on screen
2614 * and not fully transparent. This is essentially the layer's
2615 * footprint minus the opaque regions above it.
2616 * Areas covered by a translucent surface are considered visible.
2617 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002618 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002619
2620 /*
2621 * coveredRegion: area of a surface that is covered by all
2622 * visible regions above it (which includes the translucent areas).
2623 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002624 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002625
Jesse Halla8026d22012-09-25 13:25:04 -07002626 /*
2627 * transparentRegion: area of a surface that is hinted to be completely
2628 * transparent. This is only used to tell when the layer has no visible
2629 * non-transparent regions and can be removed from the layer list. It
2630 * does not affect the visibleRegion of this layer or any layers
2631 * beneath it. The hint may not be correct if apps don't respect the
2632 * SurfaceView restrictions (which, sadly, some don't).
2633 */
2634 Region transparentRegion;
2635
Mathias Agopianab028732010-03-16 16:41:46 -07002636
2637 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002638 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002639 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002640 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002641 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002642 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002643 if (!visibleRegion.isEmpty()) {
2644 // Remove the transparent area from the visible region
2645 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002646 if (tr.preserveRects()) {
2647 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002648 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002649 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002650 // transformation too complex, can't do the
2651 // transparent region optimization.
2652 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002653 }
Mathias Agopianab028732010-03-16 16:41:46 -07002654 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002655
Mathias Agopianab028732010-03-16 16:41:46 -07002656 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002657 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002658 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002659 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002660 // the opaque region is the layer's footprint
2661 opaqueRegion = visibleRegion;
2662 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002663 }
2664 }
2665
Robert Carre5f4f692018-01-12 13:12:28 -08002666 if (visibleRegion.isEmpty()) {
2667 layer->clearVisibilityRegions();
2668 return;
2669 }
2670
Mathias Agopianab028732010-03-16 16:41:46 -07002671 // Clip the covered region to the visible region
2672 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2673
2674 // Update aboveCoveredLayers for next (lower) layer
2675 aboveCoveredLayers.orSelf(visibleRegion);
2676
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002677 // subtract the opaque region covered by the layers above us
2678 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002679
2680 // compute this layer's dirty region
2681 if (layer->contentDirty) {
2682 // we need to invalidate the whole region
2683 dirty = visibleRegion;
2684 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002685 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002686 layer->contentDirty = false;
2687 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002688 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002689 * the exposed region consists of two components:
2690 * 1) what's VISIBLE now and was COVERED before
2691 * 2) what's EXPOSED now less what was EXPOSED before
2692 *
2693 * note that (1) is conservative, we start with the whole
2694 * visible region but only keep what used to be covered by
2695 * something -- which mean it may have been exposed.
2696 *
2697 * (2) handles areas that were not covered by anything but got
2698 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002699 */
Mathias Agopianab028732010-03-16 16:41:46 -07002700 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002701 const Region oldVisibleRegion = layer->visibleRegion;
2702 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002703 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2704 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002705 }
2706 dirty.subtractSelf(aboveOpaqueLayers);
2707
2708 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002709 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002710
Mathias Agopianab028732010-03-16 16:41:46 -07002711 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002712 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002713
Jesse Halla8026d22012-09-25 13:25:04 -07002714 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002715 layer->setVisibleRegion(visibleRegion);
2716 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002717 layer->setVisibleNonTransparentRegion(
2718 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002719 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002720
Mathias Agopian87baae12012-07-31 12:38:26 -07002721 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002722}
2723
Chia-I Wuab0c3192017-08-01 11:29:00 -07002724void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002725 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002726 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2727 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002728 }
2729 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002730}
2731
Dan Stoza6b9454d2014-11-07 16:00:59 -08002732bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002733{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002734 ALOGV("handlePageFlip");
2735
Brian Andersond6927fb2016-07-23 23:37:30 -07002736 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002737
Mathias Agopian4fec8732012-06-29 14:12:52 -07002738 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002739 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002740 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002741
2742 // Store the set of layers that need updates. This set must not change as
2743 // buffers are being latched, as this could result in a deadlock.
2744 // Example: Two producers share the same command stream and:
2745 // 1.) Layer 0 is latched
2746 // 2.) Layer 0 gets a new frame
2747 // 2.) Layer 1 gets a new frame
2748 // 3.) Layer 1 is latched.
2749 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2750 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002751 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002752 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002753 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07002754 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002755 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002756 } else {
2757 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002758 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002759 } else {
2760 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002761 }
Robert Carr2047fae2016-11-28 14:09:09 -08002762 });
2763
Dan Stoza9e56aa02015-11-02 13:00:03 -08002764 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002765 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002766 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002767 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002768 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002769 newDataLatched = true;
2770 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002771 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002772
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002773 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002774
2775 // If we will need to wake up at some time in the future to deal with a
2776 // queued frame that shouldn't be displayed during this vsync period, wake
2777 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002778 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002779 signalLayerUpdate();
2780 }
2781
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002782 // enter boot animation on first buffer latch
2783 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2784 ALOGI("Enter boot animation");
2785 mBootStage = BootStage::BOOTANIMATION;
2786 }
2787
Dan Stoza6b9454d2014-11-07 16:00:59 -08002788 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002789 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002790}
2791
Mathias Agopianad456f92011-01-13 17:53:01 -08002792void SurfaceFlinger::invalidateHwcGeometry()
2793{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002794 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002795}
2796
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002797void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2798 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002799 // We only need to actually compose the display if:
2800 // 1) It is being handled by hardware composer, which may need this to
2801 // keep its virtual display state machine in sync, or
2802 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002803 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002804 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002805 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002806 return;
2807 }
2808
Dan Stoza9e56aa02015-11-02 13:00:03 -08002809 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002810 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002811
2812 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002813 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002814}
2815
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002816bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002817 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002818
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002819 const Region bounds(display->bounds());
2820 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002821 const auto displayId = display->getId();
2822 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002823 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002824
Chia-I Wu8e50e692018-05-04 10:12:37 -07002825 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002826 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002827
Dan Stoza9e56aa02015-11-02 13:00:03 -08002828 if (hasClientComposition) {
2829 ALOGV("hasClientComposition");
2830
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002831 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002832 if (display->hasWideColorGamut()) {
2833 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002834 }
2835 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002836 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002837 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002838
Dominik Laskowski7e045462018-05-30 13:02:02 -07002839 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002840 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2841 HWC2::Capability::SkipClientColorTransform);
2842
Chia-I Wud49d6692018-06-27 07:17:41 +08002843 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002844 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2845 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08002846 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002847 }
2848
Chia-I Wud49d6692018-06-27 07:17:41 +08002849 // The current enhanced saturation matrix is designed to enhance Display P3,
2850 // thus we only apply this matrix when the render intent is not colorimetric
2851 // and the output color space is Display P3.
2852 needsEnhancedColorMatrix =
2853 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2854 outputDataspace == Dataspace::DISPLAY_P3);
2855 if (needsEnhancedColorMatrix) {
2856 colorMatrix *= mEnhancedSaturationMatrix;
2857 }
2858
2859 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002860
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002861 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002862 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002863 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002864 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002865
2866 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002867 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2868 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2869 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002870 }
2871 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002872 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002873
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002874 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002875 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002876 // when using overlays, we assume a fully transparent framebuffer
2877 // NOTE: we could reduce how much we need to clear, for instance
2878 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002879 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002880 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002881 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002882 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002883 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002884 // we're left with the letterbox region
2885 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002886 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07002887
2888 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002889 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07002890
Mathias Agopianb9494d52012-04-18 02:28:45 -07002891 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002892 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002893 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002894 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002895 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002896 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002897
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002898 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002899 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002900 // scissor on the main display. It should never be needed
2901 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002902 const Rect& bounds = display->getBounds();
2903 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07002904 if (scissor != bounds) {
2905 // scissor doesn't match the screen's dimensions, so we
2906 // need to clear everything outside of it and enable
2907 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002908
Mathias Agopianf45c5102012-10-24 16:29:17 -07002909 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002910 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002911 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002912 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002913 }
2914 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002915 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002916
Mathias Agopian85d751c2012-08-29 16:59:24 -07002917 /*
2918 * and then, render the layers targeted at the framebuffer
2919 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002920
Dan Stoza9e56aa02015-11-02 13:00:03 -08002921 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07002922 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002923 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002924 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002925 const Region clip(bounds.intersect(
2926 displayTransform.transform(layer->visibleRegion)));
2927 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002928 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002929 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002930 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002931 case HWC2::Composition::Cursor:
2932 case HWC2::Composition::Device:
2933 case HWC2::Composition::Sideband:
2934 case HWC2::Composition::SolidColor: {
2935 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002936 if (layer->getClearClientTarget(displayId) && !firstLayer &&
Rajavenu Kyatham2eae6d32018-04-10 12:34:05 +05302937 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
2938 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002939 // never clear the very first layer since we're
2940 // guaranteed the FB is already cleared
2941 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002942 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002943 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002944 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002945 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002946 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002947 break;
2948 }
2949 default:
2950 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002951 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002952 } else {
2953 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002954 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002955 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002956 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002957
Chia-I Wud49d6692018-06-27 07:17:41 +08002958 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002959 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002960 }
2961
Mathias Agopianf45c5102012-10-24 16:29:17 -07002962 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002963 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002964 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002965}
2966
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002967void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
2968 const Region& region) const {
2969 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002970 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002971 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002972}
2973
Dan Stoza7d89d062015-04-30 13:29:25 -07002974status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002975 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002976 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002977 const sp<Layer>& lbc,
2978 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002979{
Dan Stoza7d89d062015-04-30 13:29:25 -07002980 // add this layer to the current state list
2981 {
2982 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002983 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002984 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2985 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002986 return NO_MEMORY;
2987 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002988 if (parent == nullptr) {
2989 mCurrentState.layersSortedByZ.add(lbc);
2990 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002991 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002992 ALOGE("addClientLayer called with a removed parent");
2993 return NAME_NOT_FOUND;
2994 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002995 parent->addChild(lbc);
2996 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002997
Yiwei Zhang243b3782018-05-15 17:40:04 -07002998 if (gbc != nullptr) {
2999 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3000 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3001 mMaxGraphicBufferProducerListSize,
3002 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3003 mGraphicBufferProducerList.size(),
3004 mMaxGraphicBufferProducerListSize, mNumLayers);
3005 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003006 mLayersAdded = true;
3007 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003008 }
3009
Mathias Agopian96f08192010-06-02 23:28:45 -07003010 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003011 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003012
Dan Stoza7d89d062015-04-30 13:29:25 -07003013 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003014}
3015
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003016status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003017 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003018 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3019}
Robert Carr7f9b8992017-03-10 11:08:39 -08003020
chaviwca27f252018-02-06 16:46:39 -08003021status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3022 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003023 if (layer->isPendingRemoval()) {
3024 return NO_ERROR;
3025 }
3026
Robert Carr1f0a16a2016-10-24 16:27:39 -07003027 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003028 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003029 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003030 if (topLevelOnly) {
3031 return NO_ERROR;
3032 }
3033
Chia-I Wu98f1c102017-05-30 14:54:08 -07003034 sp<Layer> ancestor = p;
3035 while (ancestor->getParent() != nullptr) {
3036 ancestor = ancestor->getParent();
3037 }
3038 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3039 ALOGE("removeLayer called with a layer whose parent has been removed");
3040 return NAME_NOT_FOUND;
3041 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003042
3043 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003044 } else {
3045 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003046 }
3047
Robert Carr136e2f62017-02-08 17:54:29 -08003048 // As a matter of normal operation, the LayerCleaner will produce a second
3049 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3050 // so we will succeed in promoting it, but it's already been removed
3051 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3052 // otherwise something has gone wrong and we are leaking the layer.
3053 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003054 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3055 layer->getName().string(),
3056 (p != nullptr) ? p->getName().string() : "no-parent");
3057 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003058 } else if (index < 0) {
3059 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003060 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003061
Chia-I Wuc6657022017-08-15 11:18:17 -07003062 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003063 mLayersPendingRemoval.add(layer);
3064 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003065 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003066 setTransactionFlags(eTransactionNeeded);
3067 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003068}
3069
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003070uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003071 return android_atomic_release_load(&mTransactionFlags);
3072}
3073
Mathias Agopian3f844832013-08-07 21:24:32 -07003074uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003075 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3076}
3077
Mathias Agopian3f844832013-08-07 21:24:32 -07003078uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003079 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3080}
3081
3082uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3083 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003084 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003085 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003086 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003087 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003088 }
3089 return old;
3090}
3091
chaviwca27f252018-02-06 16:46:39 -08003092bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3093 for (const ComposerState& state : states) {
3094 // Here we need to check that the interface we're given is indeed
3095 // one of our own. A malicious client could give us a nullptr
3096 // IInterface, or one of its own or even one of our own but a
3097 // different type. All these situations would cause us to crash.
3098 if (state.client == nullptr) {
3099 return true;
3100 }
3101
3102 sp<IBinder> binder = IInterface::asBinder(state.client);
3103 if (binder == nullptr) {
3104 return true;
3105 }
3106
3107 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3108 return true;
3109 }
3110 }
3111 return false;
3112}
3113
Mathias Agopian8b33f032012-07-24 20:43:54 -07003114void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003115 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003116 const Vector<DisplayState>& displays,
3117 uint32_t flags)
3118{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003119 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003120 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003121 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003122
chaviwca27f252018-02-06 16:46:39 -08003123 if (containsAnyInvalidClientState(states)) {
3124 return;
3125 }
3126
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003127 if (flags & eAnimation) {
3128 // For window updates that are part of an animation we must wait for
3129 // previous animation "frames" to be handled.
3130 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003131 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003132 if (CC_UNLIKELY(err != NO_ERROR)) {
3133 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003134 // caller after a few seconds.
3135 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3136 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003137 mAnimTransactionPending = false;
3138 break;
3139 }
3140 }
3141 }
3142
chaviwca27f252018-02-06 16:46:39 -08003143 for (const DisplayState& display : displays) {
3144 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003145 }
3146
chaviwca27f252018-02-06 16:46:39 -08003147 for (const ComposerState& state : states) {
3148 transactionFlags |= setClientStateLocked(state);
3149 }
3150
3151 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3152 // as destroyed should only occur after setting all other states. This is to allow for a
3153 // child re-parent to happen before marking its original parent as destroyed (which would
3154 // then mark the child as destroyed).
3155 for (const ComposerState& state : states) {
3156 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003157 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003158
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003159 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3160 // anyway. This can be used as a flush mechanism for previous async transactions.
3161 // Empty animation transaction can be used to simulate back-pressure, so also force a
3162 // transaction for empty animation transactions.
3163 if (transactionFlags == 0 &&
3164 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003165 transactionFlags = eTransactionNeeded;
3166 }
3167
Mathias Agopian386aa982011-11-07 21:58:03 -08003168 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003169 if (mInterceptor->isEnabled()) {
3170 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003171 }
Irvel468051e2016-06-13 16:44:44 -07003172
Mathias Agopian386aa982011-11-07 21:58:03 -08003173 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003174 const auto start = (flags & eEarlyWakeup)
3175 ? VSyncModulator::TransactionStart::EARLY
3176 : VSyncModulator::TransactionStart::NORMAL;
3177 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003178
3179 // if this is a synchronous transaction, wait for it to take effect
3180 // before returning.
3181 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003182 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003183 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003184 if (flags & eAnimation) {
3185 mAnimTransactionPending = true;
3186 }
3187 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003188 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3189 if (CC_UNLIKELY(err != NO_ERROR)) {
3190 // just in case something goes wrong in SF, return to the
3191 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003192 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3193 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003194 break;
3195 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003196 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003197 }
3198}
3199
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003200uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3201 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3202 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003203
Mathias Agopiane57f2922012-08-09 16:29:12 -07003204 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003205 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3206
3207 const uint32_t what = s.what;
3208 if (what & DisplayState::eSurfaceChanged) {
3209 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3210 state.surface = s.surface;
3211 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003212 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003213 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003214 if (what & DisplayState::eLayerStackChanged) {
3215 if (state.layerStack != s.layerStack) {
3216 state.layerStack = s.layerStack;
3217 flags |= eDisplayTransactionNeeded;
3218 }
3219 }
3220 if (what & DisplayState::eDisplayProjectionChanged) {
3221 if (state.orientation != s.orientation) {
3222 state.orientation = s.orientation;
3223 flags |= eDisplayTransactionNeeded;
3224 }
3225 if (state.frame != s.frame) {
3226 state.frame = s.frame;
3227 flags |= eDisplayTransactionNeeded;
3228 }
3229 if (state.viewport != s.viewport) {
3230 state.viewport = s.viewport;
3231 flags |= eDisplayTransactionNeeded;
3232 }
3233 }
3234 if (what & DisplayState::eDisplaySizeChanged) {
3235 if (state.width != s.width) {
3236 state.width = s.width;
3237 flags |= eDisplayTransactionNeeded;
3238 }
3239 if (state.height != s.height) {
3240 state.height = s.height;
3241 flags |= eDisplayTransactionNeeded;
3242 }
3243 }
3244
Mathias Agopiane57f2922012-08-09 16:29:12 -07003245 return flags;
3246}
3247
Robert Carrd4ae7f32018-06-07 16:10:57 -07003248bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3249 IPCThreadState* ipc = IPCThreadState::self();
3250 const int pid = ipc->getCallingPid();
3251 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003252 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003253 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003254 return false;
3255 }
3256 return true;
3257}
3258
chaviwca27f252018-02-06 16:46:39 -08003259uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3260 const layer_state_t& s = composerState.state;
3261 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3262
Mathias Agopian13127d82013-03-05 17:47:11 -08003263 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003264 if (layer == nullptr) {
3265 return 0;
3266 }
3267
3268 if (layer->isPendingRemoval()) {
3269 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3270 return 0;
3271 }
3272
3273 uint32_t flags = 0;
3274
3275 const uint32_t what = s.what;
3276 bool geometryAppliesWithResize =
3277 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003278
3279 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3280 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003281 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003282 layer->pushPendingState();
3283 }
3284
chaviw8b3871a2017-11-01 17:41:01 -07003285 if (what & layer_state_t::ePositionChanged) {
3286 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3287 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003288 }
chaviw8b3871a2017-11-01 17:41:01 -07003289 }
3290 if (what & layer_state_t::eLayerChanged) {
3291 // NOTE: index needs to be calculated before we update the state
3292 const auto& p = layer->getParent();
3293 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003294 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003295 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003296 mCurrentState.layersSortedByZ.removeAt(idx);
3297 mCurrentState.layersSortedByZ.add(layer);
3298 // we need traversal (state changed)
3299 // AND transaction (list changed)
3300 flags |= eTransactionNeeded|eTraversalNeeded;
3301 }
chaviw8b3871a2017-11-01 17:41:01 -07003302 } else {
3303 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003304 flags |= eTransactionNeeded|eTraversalNeeded;
3305 }
3306 }
chaviw8b3871a2017-11-01 17:41:01 -07003307 }
3308 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003309 // NOTE: index needs to be calculated before we update the state
3310 const auto& p = layer->getParent();
3311 if (p == nullptr) {
3312 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3313 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3314 mCurrentState.layersSortedByZ.removeAt(idx);
3315 mCurrentState.layersSortedByZ.add(layer);
3316 // we need traversal (state changed)
3317 // AND transaction (list changed)
3318 flags |= eTransactionNeeded|eTraversalNeeded;
3319 }
3320 } else {
3321 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3322 flags |= eTransactionNeeded|eTraversalNeeded;
3323 }
chaviw8b3871a2017-11-01 17:41:01 -07003324 }
3325 }
3326 if (what & layer_state_t::eSizeChanged) {
3327 if (layer->setSize(s.w, s.h)) {
3328 flags |= eTraversalNeeded;
3329 }
3330 }
3331 if (what & layer_state_t::eAlphaChanged) {
3332 if (layer->setAlpha(s.alpha))
3333 flags |= eTraversalNeeded;
3334 }
3335 if (what & layer_state_t::eColorChanged) {
3336 if (layer->setColor(s.color))
3337 flags |= eTraversalNeeded;
3338 }
3339 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003340 // TODO: b/109894387
3341 //
3342 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3343 // rotation. To see the problem observe that if we have a square parent, and a child
3344 // of the same size, then we rotate the child 45 degrees around it's center, the child
3345 // must now be cropped to a non rectangular 8 sided region.
3346 //
3347 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3348 // private API, and the WindowManager only uses rotation in one case, which is on a top
3349 // level layer in which cropping is not an issue.
3350 //
3351 // However given that abuse of rotation matrices could lead to surfaces extending outside
3352 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3353 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3354 // transformations.
3355 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003356 flags |= eTraversalNeeded;
3357 }
3358 if (what & layer_state_t::eTransparentRegionChanged) {
3359 if (layer->setTransparentRegionHint(s.transparentRegion))
3360 flags |= eTraversalNeeded;
3361 }
3362 if (what & layer_state_t::eFlagsChanged) {
3363 if (layer->setFlags(s.flags, s.mask))
3364 flags |= eTraversalNeeded;
3365 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003366 if (what & layer_state_t::eCropChanged_legacy) {
3367 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003368 flags |= eTraversalNeeded;
3369 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003370 if (what & layer_state_t::eFinalCropChanged_legacy) {
3371 if (layer->setFinalCrop_legacy(s.finalCrop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003372 flags |= eTraversalNeeded;
3373 }
3374 if (what & layer_state_t::eLayerStackChanged) {
3375 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3376 // We only allow setting layer stacks for top level layers,
3377 // everything else inherits layer stack from its parent.
3378 if (layer->hasParent()) {
3379 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3380 layer->getName().string());
3381 } else if (idx < 0) {
3382 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3383 "that also does not appear in the top level layer list. Something"
3384 " has gone wrong.", layer->getName().string());
3385 } else if (layer->setLayerStack(s.layerStack)) {
3386 mCurrentState.layersSortedByZ.removeAt(idx);
3387 mCurrentState.layersSortedByZ.add(layer);
3388 // we need traversal (state changed)
3389 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003390 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003391 }
3392 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003393 if (what & layer_state_t::eDeferTransaction_legacy) {
3394 if (s.barrierHandle_legacy != nullptr) {
3395 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3396 } else if (s.barrierGbp_legacy != nullptr) {
3397 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003398 if (authenticateSurfaceTextureLocked(gbp)) {
3399 const auto& otherLayer =
3400 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003401 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003402 } else {
3403 ALOGE("Attempt to defer transaction to to an"
3404 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003405 }
3406 }
chaviw8b3871a2017-11-01 17:41:01 -07003407 // We don't trigger a traversal here because if no other state is
3408 // changed, we don't want this to cause any more work
3409 }
3410 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003411 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003412 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003413 if (!hadParent) {
3414 mCurrentState.layersSortedByZ.remove(layer);
3415 }
chaviw8b3871a2017-11-01 17:41:01 -07003416 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003417 }
chaviw8b3871a2017-11-01 17:41:01 -07003418 }
3419 if (what & layer_state_t::eReparentChildren) {
3420 if (layer->reparentChildren(s.reparentHandle)) {
3421 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003422 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003423 }
chaviw8b3871a2017-11-01 17:41:01 -07003424 if (what & layer_state_t::eDetachChildren) {
3425 layer->detachChildren();
3426 }
3427 if (what & layer_state_t::eOverrideScalingModeChanged) {
3428 layer->setOverrideScalingMode(s.overrideScalingMode);
3429 // We don't trigger a traversal here because if no other state is
3430 // changed, we don't want this to cause any more work
3431 }
Marissa Wall61c58622018-07-18 10:12:20 -07003432 if (what & layer_state_t::eTransformChanged) {
3433 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3434 }
3435 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3436 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3437 flags |= eTraversalNeeded;
3438 }
3439 if (what & layer_state_t::eCropChanged) {
3440 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3441 }
3442 if (what & layer_state_t::eBufferChanged) {
3443 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3444 }
3445 if (what & layer_state_t::eAcquireFenceChanged) {
3446 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3447 }
3448 if (what & layer_state_t::eDataspaceChanged) {
3449 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3450 }
3451 if (what & layer_state_t::eHdrMetadataChanged) {
3452 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3453 }
3454 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3455 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3456 }
3457 if (what & layer_state_t::eApiChanged) {
3458 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3459 }
3460 if (what & layer_state_t::eSidebandStreamChanged) {
3461 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3462 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003463 return flags;
3464}
3465
chaviwca27f252018-02-06 16:46:39 -08003466void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3467 const layer_state_t& state = composerState.state;
3468 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3469
3470 sp<Layer> layer(client->getLayerUser(state.surface));
3471 if (layer == nullptr) {
3472 return;
3473 }
3474
3475 if (layer->isPendingRemoval()) {
3476 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3477 return;
3478 }
3479
3480 if (state.what & layer_state_t::eDestroySurface) {
3481 removeLayerLocked(mStateLock, layer);
3482 }
3483}
3484
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003485status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003486 const String8& name,
3487 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003488 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003489 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003490 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003491{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003492 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003493 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003494 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003495 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003496 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003497
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003498 status_t result = NO_ERROR;
3499
3500 sp<Layer> layer;
3501
Cody Northropbc755282017-03-31 12:00:08 -06003502 String8 uniqueName = getUniqueLayerName(name);
3503
Mathias Agopian3165cc22012-08-08 19:42:09 -07003504 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003505 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003506 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3507 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003508
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003509 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003510 case ISurfaceComposerClient::eFXSurfaceBufferState:
3511 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3512 break;
chaviw13fdc492017-06-27 12:40:18 -07003513 case ISurfaceComposerClient::eFXSurfaceColor:
3514 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003515 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003516 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003517 break;
3518 default:
3519 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003520 break;
3521 }
3522
Dan Stoza7d89d062015-04-30 13:29:25 -07003523 if (result != NO_ERROR) {
3524 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003525 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003526
Chia-I Wuab0c3192017-08-01 11:29:00 -07003527 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3528 // TODO b/64227542
3529 if (windowType == 441731) {
3530 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3531 layer->setPrimaryDisplayOnly();
3532 }
3533
Albert Chaulk479c60c2017-01-27 14:21:34 -05003534 layer->setInfo(windowType, ownerUid);
3535
Robert Carr1f0a16a2016-10-24 16:27:39 -07003536 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003537 if (result != NO_ERROR) {
3538 return result;
3539 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003540 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003541
3542 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003543 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003544}
3545
Cody Northropbc755282017-03-31 12:00:08 -06003546String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3547{
3548 bool matchFound = true;
3549 uint32_t dupeCounter = 0;
3550
3551 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3552 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3553
Dan Stoza436ccf32018-06-21 12:10:12 -07003554 // Grab the state lock since we're accessing mCurrentState
3555 Mutex::Autolock lock(mStateLock);
3556
Cody Northropbc755282017-03-31 12:00:08 -06003557 // Loop over layers until we're sure there is no matching name
3558 while (matchFound) {
3559 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003560 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003561 if (layer->getName() == uniqueName) {
3562 matchFound = true;
3563 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3564 }
3565 });
3566 }
3567
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003568 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3569 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003570
3571 return uniqueName;
3572}
3573
Marissa Wallfd668622018-05-10 10:21:13 -07003574status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3575 uint32_t w, uint32_t h, uint32_t flags,
3576 PixelFormat& format, sp<IBinder>* handle,
3577 sp<IGraphicBufferProducer>* gbp,
3578 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003579 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003580 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003581 case PIXEL_FORMAT_TRANSPARENT:
3582 case PIXEL_FORMAT_TRANSLUCENT:
3583 format = PIXEL_FORMAT_RGBA_8888;
3584 break;
3585 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003586 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003587 break;
3588 }
3589
Marissa Wallfd668622018-05-10 10:21:13 -07003590 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3591 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003592 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003593 *handle = layer->getHandle();
3594 *gbp = layer->getProducer();
3595 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003596 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003597
Marissa Wallfd668622018-05-10 10:21:13 -07003598 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003599 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003600}
3601
Marissa Wall61c58622018-07-18 10:12:20 -07003602status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3603 uint32_t w, uint32_t h, uint32_t flags,
3604 sp<IBinder>* handle, sp<Layer>* outLayer) {
3605 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3606 *handle = layer->getHandle();
3607 *outLayer = layer;
3608
3609 return NO_ERROR;
3610}
3611
chaviw13fdc492017-06-27 12:40:18 -07003612status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003613 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003614 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003615{
chaviw13fdc492017-06-27 12:40:18 -07003616 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003617 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003618 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003619}
3620
Mathias Agopianac9fa422013-02-11 16:40:36 -08003621status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003622{
Robert Carr9524cb32017-02-13 11:32:32 -08003623 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003624 status_t err = NO_ERROR;
3625 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003626 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003627 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003628 err = removeLayer(l);
3629 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3630 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003631 }
3632 return err;
3633}
3634
Mathias Agopian13127d82013-03-05 17:47:11 -08003635status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003636{
Mathias Agopian67106042013-03-14 19:18:13 -07003637 // called by ~LayerCleaner() when all references to the IBinder (handle)
3638 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003639 sp<Layer> l = layer.promote();
3640 if (l == nullptr) {
3641 // The layer has already been removed, carry on
3642 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003643 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003644 // If we have a parent, then we can continue to live as long as it does.
3645 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003646}
3647
Mathias Agopianb60314a2012-04-10 22:09:54 -07003648// ---------------------------------------------------------------------------
3649
Andy McFadden13a082e2012-08-24 10:16:42 -07003650void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003651 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3652 if (!displayToken) return;
3653
Jesse Hall01e29052013-02-19 16:13:35 -08003654 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003655 Vector<ComposerState> state;
3656 Vector<DisplayState> displays;
3657 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003658 d.what = DisplayState::eDisplayProjectionChanged |
3659 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003660 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003661 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003662 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003663 d.frame.makeInvalid();
3664 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003665 d.width = 0;
3666 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003667 displays.add(d);
3668 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003669
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003670 const auto display = getDisplayDevice(displayToken);
3671 if (!display) return;
3672
3673 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3674
3675 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003676 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003677 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003678
Brian Andersond0010582017-03-07 13:20:31 -08003679 // Use phase of 0 since phase is not known.
3680 // Use latency of 0, which will snap to the ideal latency.
3681 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003682}
3683
3684void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003685 // Async since we may be called from the main thread.
3686 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003687}
3688
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003689void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3690 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003691 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003692 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003693
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003694 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003695 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003696 return;
3697 }
3698
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003699 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003700 ALOGW("Trying to set power mode for virtual display");
3701 return;
3702 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003703
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003704 display->setPowerMode(mode);
3705
Lloyd Pique4dccc412018-01-22 17:21:36 -08003706 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003707 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003708 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003709 if (idx < 0) {
3710 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3711 return;
3712 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003713 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003714 }
3715
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003716 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003717 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003718 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003719 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003720 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003721 // FIXME: eventthread only knows about the main display right now
3722 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003723 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003724 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003725
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003726 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003727 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003728 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003729
3730 struct sched_param param = {0};
3731 param.sched_priority = 1;
3732 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3733 ALOGW("Couldn't set SCHED_FIFO on display on");
3734 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003735 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003736 // Turn off the display
3737 struct sched_param param = {0};
3738 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3739 ALOGW("Couldn't set SCHED_OTHER on display off");
3740 }
3741
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003742 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003743 disableHardwareVsync(true); // also cancels any in-progress resync
3744
Mathias Agopiancde87a32012-09-13 14:09:01 -07003745 // FIXME: eventthread only knows about the main display right now
3746 mEventThread->onScreenReleased();
3747 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003748
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003749 getHwComposer().setPowerMode(type, mode);
3750 mVisibleRegionsDirty = true;
3751 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003752 } else if (mode == HWC_POWER_MODE_DOZE ||
3753 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003754 // Update display while dozing
3755 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003756 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003757 // FIXME: eventthread only knows about the main display right now
3758 mEventThread->onScreenAcquired();
3759 resyncToHardwareVsync(true);
3760 }
3761 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3762 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003763 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003764 disableHardwareVsync(true); // also cancels any in-progress resync
3765 // FIXME: eventthread only knows about the main display right now
3766 mEventThread->onScreenReleased();
3767 }
3768 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003769 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003770 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003771 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003772 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003773
3774 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003775}
3776
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003777void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003778 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003779 const auto display = getDisplayDevice(displayToken);
3780 if (!display) {
3781 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3782 displayToken.get());
3783 } else if (display->isVirtual()) {
3784 ALOGW("Attempt to set power mode %d for virtual display", mode);
3785 } else {
3786 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003787 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003788 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003789}
3790
3791// ---------------------------------------------------------------------------
3792
Lloyd Pique755e3192018-01-31 16:46:15 -08003793status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3794 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003795 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003796
Mathias Agopianbd115332013-04-18 16:41:04 -07003797 IPCThreadState* ipc = IPCThreadState::self();
3798 const int pid = ipc->getCallingPid();
3799 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003800
Mathias Agopianbd115332013-04-18 16:41:04 -07003801 if ((uid != AID_SHELL) &&
3802 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003803 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003804 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003805 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003806 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003807 // (this would indicate SF is stuck, but we want to be able to
3808 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003809 status_t err = mStateLock.timedLock(s2ns(1));
3810 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003811 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003812 result.appendFormat(
3813 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3814 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003815 }
3816
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003817 bool dumpAll = true;
3818 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003819 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003820
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003821 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003822 if ((index < numArgs) &&
3823 (args[index] == String16("--list"))) {
3824 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003825 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003826 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003827 }
3828
3829 if ((index < numArgs) &&
3830 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003831 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003832 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003833 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003834 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003835
3836 if ((index < numArgs) &&
3837 (args[index] == String16("--latency-clear"))) {
3838 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003839 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003840 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003841 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003842
3843 if ((index < numArgs) &&
3844 (args[index] == String16("--dispsync"))) {
3845 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07003846 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07003847 dumpAll = false;
3848 }
Dan Stozab90cf072015-03-05 11:05:59 -08003849
3850 if ((index < numArgs) &&
3851 (args[index] == String16("--static-screen"))) {
3852 index++;
3853 dumpStaticScreenStats(result);
3854 dumpAll = false;
3855 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003856
3857 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003858 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003859 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003860 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003861 dumpAll = false;
3862 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003863
3864 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3865 index++;
3866 dumpWideColorInfo(result);
3867 dumpAll = false;
3868 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003869
3870 if ((index < numArgs) &&
3871 (args[index] == String16("--enable-layer-stats"))) {
3872 index++;
3873 mLayerStats.enable();
3874 dumpAll = false;
3875 }
3876
3877 if ((index < numArgs) &&
3878 (args[index] == String16("--disable-layer-stats"))) {
3879 index++;
3880 mLayerStats.disable();
3881 dumpAll = false;
3882 }
3883
3884 if ((index < numArgs) &&
3885 (args[index] == String16("--clear-layer-stats"))) {
3886 index++;
3887 mLayerStats.clear();
3888 dumpAll = false;
3889 }
3890
3891 if ((index < numArgs) &&
3892 (args[index] == String16("--dump-layer-stats"))) {
3893 index++;
3894 mLayerStats.dump(result);
3895 dumpAll = false;
3896 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003897
3898 if ((index < numArgs) &&
3899 (args[index] == String16("--display-identification"))) {
3900 index++;
3901 dumpDisplayIdentificationData(result);
3902 dumpAll = false;
3903 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003904
3905 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3906 index++;
3907 mTimeStats.parseArgs(asProto, args, index, result);
3908 dumpAll = false;
3909 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003910 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003911
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003912 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003913 if (asProto) {
3914 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3915 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3916 } else {
3917 dumpAllLocked(args, index, result);
3918 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003919 }
3920
Mathias Agopian9795c422009-08-26 16:36:26 -07003921 if (locked) {
3922 mStateLock.unlock();
3923 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003924 }
3925 write(fd, result.string(), result.size());
3926 return NO_ERROR;
3927}
3928
Dan Stozac7014012014-02-14 15:03:43 -08003929void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3930 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003931{
Robert Carr2047fae2016-11-28 14:09:09 -08003932 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003933 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003934 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003935}
3936
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003937void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003938 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003939{
3940 String8 name;
3941 if (index < args.size()) {
3942 name = String8(args[index]);
3943 index++;
3944 }
3945
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003946 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
3947 getHwComposer().isConnected(displayId)) {
3948 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
3949 const nsecs_t period = activeConfig->getVsyncPeriod();
3950 result.appendFormat("%" PRId64 "\n", period);
3951 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003952
3953 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003954 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003955 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003956 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003957 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003958 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003959 }
Robert Carr2047fae2016-11-28 14:09:09 -08003960 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003961 }
3962}
3963
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003964void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003965 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003966{
3967 String8 name;
3968 if (index < args.size()) {
3969 name = String8(args[index]);
3970 index++;
3971 }
3972
Robert Carr2047fae2016-11-28 14:09:09 -08003973 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003974 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003975 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003976 }
Robert Carr2047fae2016-11-28 14:09:09 -08003977 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003978
Svetoslavd85084b2014-03-20 10:28:31 -07003979 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003980}
3981
Jamie Gennis6547ff42013-07-16 20:12:42 -07003982// This should only be called from the main thread. Otherwise it would need
3983// the lock and should use mCurrentState rather than mDrawingState.
3984void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003985 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003986 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003987 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003988
3989 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3990}
3991
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003992void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003993{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003994 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003995
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003996 if (isLayerTripleBufferingDisabled())
3997 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003998
3999 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004000 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004001 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004002 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004003 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4004 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004005 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004006}
4007
Dan Stozab90cf072015-03-05 11:05:59 -08004008void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4009{
4010 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004011 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4012 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004013 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004014 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004015 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4016 b + 1, bucketTimeSec, percent);
4017 }
David Sodman4a36e932017-11-07 14:29:47 -08004018 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004019 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004020 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004021 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004022 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004023}
4024
Dan Stozae77c7662016-05-13 11:37:28 -07004025void SurfaceFlinger::recordBufferingStats(const char* layerName,
4026 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004027 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4028 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004029 for (const auto& segment : history) {
4030 if (!segment.usedThirdBuffer) {
4031 stats.twoBufferTime += segment.totalTime;
4032 }
4033 if (segment.occupancyAverage < 1.0f) {
4034 stats.doubleBufferedTime += segment.totalTime;
4035 } else if (segment.occupancyAverage < 2.0f) {
4036 stats.tripleBufferedTime += segment.totalTime;
4037 }
4038 ++stats.numSegments;
4039 stats.totalTime += segment.totalTime;
4040 }
4041}
4042
Brian Andersond6927fb2016-07-23 23:37:30 -07004043void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4044 result.appendFormat("Layer frame timestamps:\n");
4045
4046 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4047 const size_t count = currentLayers.size();
4048 for (size_t i=0 ; i<count ; i++) {
4049 currentLayers[i]->dumpFrameEvents(result);
4050 }
4051}
4052
Dan Stozae77c7662016-05-13 11:37:28 -07004053void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4054 result.append("Buffering stats:\n");
4055 result.append(" [Layer name] <Active time> <Two buffer> "
4056 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004057 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004058 typedef std::tuple<std::string, float, float, float> BufferTuple;
4059 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004060 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004061 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004062 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004063 if (stats.numSegments == 0) {
4064 continue;
4065 }
4066 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4067 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4068 stats.totalTime;
4069 float doubleBufferRatio = static_cast<float>(
4070 stats.doubleBufferedTime) / stats.totalTime;
4071 float tripleBufferRatio = static_cast<float>(
4072 stats.tripleBufferedTime) / stats.totalTime;
4073 sorted.insert({activeTime, {name, twoBufferRatio,
4074 doubleBufferRatio, tripleBufferRatio}});
4075 }
4076 for (const auto& sortedPair : sorted) {
4077 float activeTime = sortedPair.first;
4078 const BufferTuple& values = sortedPair.second;
4079 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4080 std::get<0>(values).c_str(), activeTime,
4081 std::get<1>(values), std::get<2>(values),
4082 std::get<3>(values));
4083 }
4084 result.append("\n");
4085}
4086
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004087void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004088 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004089 const int32_t displayId = display->getId();
4090 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4091 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004092 continue;
4093 }
4094
Dominik Laskowski7e045462018-05-30 13:02:02 -07004095 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004096 uint8_t port;
4097 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004098 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004099 result.append("no identification data\n");
4100 continue;
4101 }
4102
4103 if (!isEdid(data)) {
4104 result.append("unknown identification data: ");
4105 for (uint8_t byte : data) {
4106 result.appendFormat("%x ", byte);
4107 }
4108 result.append("\n");
4109 continue;
4110 }
4111
4112 const auto edid = parseEdid(data);
4113 if (!edid) {
4114 result.append("invalid EDID: ");
4115 for (uint8_t byte : data) {
4116 result.appendFormat("%x ", byte);
4117 }
4118 result.append("\n");
4119 continue;
4120 }
4121
4122 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4123 result.append(edid->displayName.data(), edid->displayName.length());
4124 result.append("\"\n");
4125 }
4126 result.append("\n");
4127}
4128
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004129void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4130 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004131 result.appendFormat("DisplayColorSetting: %s\n",
4132 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004133
4134 // TODO: print out if wide-color mode is active or not
4135
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004136 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004137 const int32_t displayId = display->getId();
4138 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004139 continue;
4140 }
4141
Dominik Laskowski7e045462018-05-30 13:02:02 -07004142 result.appendFormat("Display %d color modes:\n", displayId);
4143 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004144 for (auto&& mode : modes) {
4145 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4146 }
4147
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004148 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004149 result.appendFormat(" Current color mode: %s (%d)\n",
4150 decodeColorMode(currentMode).c_str(), currentMode);
4151 }
4152 result.append("\n");
4153}
4154
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004155LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004156 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004157 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4158 const State& state = useDrawing ? mDrawingState : mCurrentState;
4159 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004160 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004161 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004162 });
4163
4164 return layersProto;
4165}
4166
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004167LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004168 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004169
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004170 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004171 resolution->set_w(display.getWidth());
4172 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004173
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004174 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4175 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4176 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004177
Dominik Laskowski7e045462018-05-30 13:02:02 -07004178 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004179 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004180 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004181 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004182 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004183 }
4184 });
4185
4186 return layersProto;
4187}
4188
Mathias Agopian74d211a2013-04-22 16:55:35 +02004189void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4190 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004191{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004192 bool colorize = false;
4193 if (index < args.size()
4194 && (args[index] == String16("--color"))) {
4195 colorize = true;
4196 index++;
4197 }
4198
4199 Colorizer colorizer(colorize);
4200
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004201 // figure out if we're stuck somewhere
4202 const nsecs_t now = systemTime();
4203 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4204 const nsecs_t inTransaction(mDebugInTransaction);
4205 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4206 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4207
4208 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004209 * Dump library configuration.
4210 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004211
4212 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004213 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004214 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004215 appendSfConfigString(result);
4216 appendUiConfigString(result);
4217 appendGuiConfigString(result);
4218 result.append("\n");
4219
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004220 result.append("\nDisplay identification data:\n");
4221 dumpDisplayIdentificationData(result);
4222
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004223 result.append("\nWide-Color information:\n");
4224 dumpWideColorInfo(result);
4225
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004226 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004227 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004228 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004229 result.append(SyncFeatures::getInstance().toString());
4230 result.append("\n");
4231
Andy McFadden41d67d72014-04-25 16:58:34 -07004232 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004233 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004234 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004235
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004236 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4237 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004238 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4239 getHwComposer().isConnected(displayId)) {
4240 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004241 result.appendFormat("Display %d: "
4242 "app phase %" PRId64 " ns, "
4243 "sf phase %" PRId64 " ns, "
4244 "early app phase %" PRId64 " ns, "
4245 "early sf phase %" PRId64 " ns, "
4246 "early app gl phase %" PRId64 " ns, "
4247 "early sf gl phase %" PRId64 " ns, "
4248 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4249 displayId,
4250 vsyncPhaseOffsetNs,
4251 sfVsyncPhaseOffsetNs,
4252 appEarlyOffset,
4253 sfEarlyOffset,
4254 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004255 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004256 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004257 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004258 result.append("\n");
4259
Dan Stozab90cf072015-03-05 11:05:59 -08004260 // Dump static screen stats
4261 result.append("\n");
4262 dumpStaticScreenStats(result);
4263 result.append("\n");
4264
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004265 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4266
Dan Stozae77c7662016-05-13 11:37:28 -07004267 dumpBufferingStats(result);
4268
Andy McFadden4803b742012-09-24 19:07:20 -07004269 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004270 * Dump the visible layer list
4271 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004272 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004273 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004274 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4275 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004276 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004277
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004278 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004279 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004280 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004281 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004282
4283 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004284 * Dump Display state
4285 */
4286
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004287 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004288 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004289 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004290 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004291 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004292 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004293 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004294
4295 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004296 * Dump SurfaceFlinger global state
4297 */
4298
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004299 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004300 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004301 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004302
Mathias Agopian888c8222012-08-04 21:10:38 -07004303 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004304 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004305
David Sodmanbc815282017-11-05 18:57:52 -08004306 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004307
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004308 if (display) {
4309 display->undefinedRegion.dump(result, "undefinedRegion");
4310 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4311 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004312 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004313 result.appendFormat(" last eglSwapBuffers() time: %f us\n"
4314 " last transaction time : %f us\n"
4315 " transaction-flags : %08x\n"
4316 " gpu_to_cpu_unsupported : %d\n",
4317 mLastSwapBufferTime / 1000.0, mLastTransactionTime / 1000.0,
4318 mTransactionFlags, !mGpuToCpuSupported);
4319
4320 if (display) {
4321 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4322 result.appendFormat(" refresh-rate : %f fps\n"
4323 " x-dpi : %f\n"
4324 " y-dpi : %f\n",
4325 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4326 activeConfig->getDpiY());
4327 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004328
Mathias Agopian74d211a2013-04-22 16:55:35 +02004329 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004330 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004331
Mathias Agopian74d211a2013-04-22 16:55:35 +02004332 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004333 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004334
4335 /*
4336 * VSYNC state
4337 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004338 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004339 result.append("\n");
4340
4341 /*
4342 * HWC layer minidump
4343 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004344 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004345 const int32_t displayId = display->getId();
4346 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004347 continue;
4348 }
4349
Dominik Laskowski7e045462018-05-30 13:02:02 -07004350 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004351 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004352 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004353 result.append("\n");
4354 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004355
4356 /*
4357 * Dump HWComposer state
4358 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004359 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004360 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004361 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004362 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004363 result.appendFormat(" h/w composer %s\n",
4364 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004365 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004366
4367 /*
4368 * Dump gralloc state
4369 */
4370 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4371 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004372
4373 /*
4374 * Dump VrFlinger state if in use.
4375 */
4376 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4377 result.append("VrFlinger state:\n");
4378 result.append(mVrFlinger->Dump().c_str());
4379 result.append("\n");
4380 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004381}
4382
Dominik Laskowski7e045462018-05-30 13:02:02 -07004383const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004384 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004385 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004386 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004387 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004388 }
4389 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004390
4391 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4392 static const Vector<sp<Layer>> empty;
4393 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004394}
4395
Keun young Park63f165f2012-08-31 10:53:36 -07004396bool SurfaceFlinger::startDdmConnection()
4397{
4398 void* libddmconnection_dso =
4399 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4400 if (!libddmconnection_dso) {
4401 return false;
4402 }
4403 void (*DdmConnection_start)(const char* name);
4404 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004405 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004406 if (!DdmConnection_start) {
4407 dlclose(libddmconnection_dso);
4408 return false;
4409 }
4410 (*DdmConnection_start)(getServiceName());
4411 return true;
4412}
4413
Chia-I Wu28f320b2018-05-03 11:02:56 -07004414void SurfaceFlinger::updateColorMatrixLocked() {
4415 mat4 colorMatrix;
4416 if (mGlobalSaturationFactor != 1.0f) {
4417 // Rec.709 luma coefficients
4418 float3 luminance{0.213f, 0.715f, 0.072f};
4419 luminance *= 1.0f - mGlobalSaturationFactor;
4420 mat4 saturationMatrix = mat4(
4421 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4422 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4423 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4424 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4425 );
4426 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4427 } else {
4428 colorMatrix = mClientColorMatrix * mDaltonizer();
4429 }
4430
4431 if (mCurrentState.colorMatrix != colorMatrix) {
4432 mCurrentState.colorMatrix = colorMatrix;
4433 mCurrentState.colorMatrixChanged = true;
4434 setTransactionFlags(eTransactionNeeded);
4435 }
4436}
4437
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004438status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004439#pragma clang diagnostic push
4440#pragma clang diagnostic error "-Wswitch-enum"
4441 switch (static_cast<ISurfaceComposerTag>(code)) {
4442 // These methods should at minimum make sure that the client requested
4443 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004444 case BOOT_FINISHED:
4445 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004446 case CREATE_CONNECTION:
4447 case CREATE_DISPLAY:
4448 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004449 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004450 case GET_ACTIVE_COLOR_MODE:
4451 case GET_ANIMATION_FRAME_STATS:
4452 case GET_HDR_CAPABILITIES:
4453 case SET_ACTIVE_CONFIG:
4454 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004455 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004456 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004457 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4458 IPCThreadState* ipc = IPCThreadState::self();
4459 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4460 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004461 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004462 }
Robert Carr1db73f62016-12-21 12:58:51 -08004463 return OK;
4464 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004465 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004466 IPCThreadState* ipc = IPCThreadState::self();
4467 const int pid = ipc->getCallingPid();
4468 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004469 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4470 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004471 return PERMISSION_DENIED;
4472 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004473 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004474 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004475 // Used by apps to hook Choreographer to SurfaceFlinger.
4476 case CREATE_DISPLAY_EVENT_CONNECTION:
4477 // The following calls are currently used by clients that do not
4478 // request necessary permissions. However, they do not expose any secret
4479 // information, so it is OK to pass them.
4480 case AUTHENTICATE_SURFACE:
4481 case GET_ACTIVE_CONFIG:
4482 case GET_BUILT_IN_DISPLAY:
4483 case GET_DISPLAY_COLOR_MODES:
4484 case GET_DISPLAY_CONFIGS:
4485 case GET_DISPLAY_STATS:
4486 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4487 // Calling setTransactionState is safe, because you need to have been
4488 // granted a reference to Client* and Handle* to do anything with it.
4489 case SET_TRANSACTION_STATE:
4490 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4491 case CREATE_SCOPED_CONNECTION: {
4492 return OK;
4493 }
4494 case CAPTURE_LAYERS:
4495 case CAPTURE_SCREEN: {
4496 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004497 IPCThreadState* ipc = IPCThreadState::self();
4498 const int pid = ipc->getCallingPid();
4499 const int uid = ipc->getCallingUid();
4500 if ((uid != AID_GRAPHICS) &&
4501 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4502 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4503 return PERMISSION_DENIED;
4504 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004505 return OK;
4506 }
4507 // The following codes are deprecated and should never be allowed to access SF.
4508 case CONNECT_DISPLAY_UNUSED:
4509 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4510 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4511 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004512 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004513 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004514
4515 // These codes are used for the IBinder protocol to either interrogate the recipient
4516 // side of the transaction for its canonical interface descriptor or to dump its state.
4517 // We let them pass by default.
4518 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4519 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4520 code == IBinder::SYSPROPS_TRANSACTION) {
4521 return OK;
4522 }
4523 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4524 // in onTransact verifies that the user is root, and has access to use SF.
4525 if (code >= 1000 && code <= 1029) {
4526 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4527 return OK;
4528 }
4529 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4530 return PERMISSION_DENIED;
4531#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004532}
4533
Ana Krulec13be8ad2018-08-21 02:43:56 +00004534status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4535 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004536 status_t credentialCheck = CheckTransactCodeCredentials(code);
4537 if (credentialCheck != OK) {
4538 return credentialCheck;
4539 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004540
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004541 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4542 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004543 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004544 IPCThreadState* ipc = IPCThreadState::self();
4545 const int uid = ipc->getCallingUid();
4546 if (CC_UNLIKELY(uid != AID_SYSTEM
4547 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004548 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004549 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004550 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004551 return PERMISSION_DENIED;
4552 }
4553 int n;
4554 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004555 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004556 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004557 return NO_ERROR;
4558 case 1002: // SHOW_UPDATES
4559 n = data.readInt32();
4560 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004561 invalidateHwcGeometry();
4562 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004563 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004564 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004565 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004566 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004567 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004568 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004569 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004570 setTransactionFlags(
4571 eTransactionNeeded|
4572 eDisplayTransactionNeeded|
4573 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004574 return NO_ERROR;
4575 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004576 case 1006:{ // send empty update
4577 signalRefresh();
4578 return NO_ERROR;
4579 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004580 case 1008: // toggle use of hw composer
4581 n = data.readInt32();
4582 mDebugDisableHWC = n ? 1 : 0;
4583 invalidateHwcGeometry();
4584 repaintEverything();
4585 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004586 case 1009: // toggle use of transform hint
4587 n = data.readInt32();
4588 mDebugDisableTransformHint = n ? 1 : 0;
4589 invalidateHwcGeometry();
4590 repaintEverything();
4591 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004592 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004593 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004594 reply->writeInt32(0);
4595 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004596 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004597 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004598 return NO_ERROR;
4599 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004600 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004601 if (!display) {
4602 return NAME_NOT_FOUND;
4603 }
4604
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004605 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004606 return NO_ERROR;
4607 }
4608 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004609 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004610 // daltonize
4611 n = data.readInt32();
4612 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004613 case 1:
4614 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4615 break;
4616 case 2:
4617 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4618 break;
4619 case 3:
4620 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4621 break;
4622 default:
4623 mDaltonizer.setType(ColorBlindnessType::None);
4624 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004625 }
4626 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004627 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004628 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004629 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004630 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004631
4632 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004633 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004634 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004635 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004636 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004637 // apply a color matrix
4638 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004639 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004640 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004641 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004642 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004643 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004644 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004645 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004646 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004647 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004648 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004649
4650 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4651 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004652 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004653 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4654 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4655 }
4656
Chia-I Wu28f320b2018-05-03 11:02:56 -07004657 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004658 return NO_ERROR;
4659 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004660 // This is an experimental interface
4661 // Needs to be shifted to proper binder interface when we productize
4662 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004663 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07004664 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004665 return NO_ERROR;
4666 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004667 case 1017: {
4668 n = data.readInt32();
4669 mForceFullDamage = static_cast<bool>(n);
4670 return NO_ERROR;
4671 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004672 case 1018: { // Modify Choreographer's phase offset
4673 n = data.readInt32();
4674 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4675 return NO_ERROR;
4676 }
4677 case 1019: { // Modify SurfaceFlinger's phase offset
4678 n = data.readInt32();
4679 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4680 return NO_ERROR;
4681 }
Irvel468051e2016-06-13 16:44:44 -07004682 case 1020: { // Layer updates interceptor
4683 n = data.readInt32();
4684 if (n) {
4685 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004686 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004687 }
4688 else{
4689 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004690 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004691 }
4692 return NO_ERROR;
4693 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004694 case 1021: { // Disable HWC virtual displays
4695 n = data.readInt32();
4696 mUseHwcVirtualDisplays = !n;
4697 return NO_ERROR;
4698 }
Romain Guy0147a172017-06-01 13:53:56 -07004699 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004700 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004701 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004702
Chia-I Wu28f320b2018-05-03 11:02:56 -07004703 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004704 return NO_ERROR;
4705 }
Romain Guy54f154a2017-10-24 21:40:32 +01004706 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004707 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004708 invalidateHwcGeometry();
4709 repaintEverything();
4710 return NO_ERROR;
4711 }
4712 case 1024: { // Is wide color gamut rendering/color management supported?
4713 reply->writeBool(hasWideColorDisplay);
4714 return NO_ERROR;
4715 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004716 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004717 n = data.readInt32();
4718 if (n) {
4719 ALOGV("LayerTracing enabled");
4720 mTracing.enable();
4721 doTracing("tracing.enable");
4722 reply->writeInt32(NO_ERROR);
4723 } else {
4724 ALOGV("LayerTracing disabled");
4725 status_t err = mTracing.disable();
4726 reply->writeInt32(err);
4727 }
4728 return NO_ERROR;
4729 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004730 case 1026: { // Get layer tracing status
4731 reply->writeBool(mTracing.isEnabled());
4732 return NO_ERROR;
4733 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004734 // Is a DisplayColorSetting supported?
4735 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004736 const auto display = getDefaultDisplayDevice();
4737 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004738 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004739 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004740
4741 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4742 switch (setting) {
4743 case DisplayColorSetting::MANAGED:
4744 reply->writeBool(hasWideColorDisplay);
4745 break;
4746 case DisplayColorSetting::UNMANAGED:
4747 reply->writeBool(true);
4748 break;
4749 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004750 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004751 break;
4752 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004753 reply->writeBool(
4754 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004755 break;
4756 }
4757 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004758 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004759 // Is VrFlinger active?
4760 case 1028: {
4761 Mutex::Autolock _l(mStateLock);
4762 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4763 return NO_ERROR;
4764 }
David Sodman6d46c1e2018-07-13 12:59:48 -07004765 case 1029: {
4766 // Code 1029 is an experimental feature that allows applications to
4767 // simulate a high frequency panel by setting a multiplier and divisor
4768 // on the VSYNC-sf clock. If either the multiplier or divisor are
4769 // 0, then the code will set both to 1 to return the VSYNC-sf clock
4770 // to it's normal frequency.
4771 int multiplier = data.readInt32();
4772 int divisor = data.readInt32();
4773
4774 if ((multiplier == 0) || (divisor == 0)) {
4775 multiplier = 1;
4776 divisor = 1;
4777 }
4778
4779 if ((multiplier == 1) && (divisor == 1)) {
4780 enableHardwareVsync();
4781 } else {
4782 disableHardwareVsync(true);
4783 }
4784 getBE().mHwc->getActiveConfig(DisplayDevice::DISPLAY_PRIMARY)
4785 ->scalePanelFrequency(multiplier, divisor);
4786 mPrimaryDispSync->scalePeriod(multiplier, divisor);
4787
4788 ATRACE_INT("PeriodMultiplier", multiplier);
4789 ATRACE_INT("PeriodDivisor", divisor);
4790 return NO_ERROR;
4791 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004792 }
4793 }
4794 return err;
4795}
4796
Steven Thomas6d8110b2017-08-31 18:24:21 -07004797void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004798 android_atomic_or(1, &mRepaintEverything);
4799 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004800}
4801
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004802// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4803class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004804public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004805 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4806 ~WindowDisconnector() {
4807 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004808 }
4809
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004810private:
4811 ANativeWindow* mWindow;
4812 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004813};
4814
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004815status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4816 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4817 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4818 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004819 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004820 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004821
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004822 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004823
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004824 const auto display = getDisplayDeviceLocked(displayToken);
4825 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004826
Yiwei Zhang06a58e22018-08-20 16:42:23 -07004827 const Rect& dispScissor = display->getScissor();
4828 if (!dispScissor.isEmpty()) {
4829 sourceCrop.set(dispScissor);
4830 // adb shell screencap will default reqWidth and reqHeight to zeros.
4831 if (reqWidth == 0 || reqHeight == 0) {
4832 reqWidth = uint32_t(dispScissor.width());
4833 reqHeight = uint32_t(dispScissor.height());
4834 }
4835 }
4836
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004837 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004838
4839 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004840 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004841 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004842}
4843
4844status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004845 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004846 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004847 ATRACE_CALL();
4848
4849 class LayerRenderArea : public RenderArea {
4850 public:
Robert Carr578038f2018-03-09 12:25:24 -08004851 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4852 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004853 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004854 mLayer(layer),
4855 mCrop(crop),
4856 mFlinger(flinger),
4857 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07004858 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004859 Rect getBounds() const override {
4860 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07004861 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07004862 }
Marissa Wall61c58622018-07-18 10:12:20 -07004863 int getHeight() const override {
4864 return mLayer->getActiveHeight(mLayer->getDrawingState());
4865 }
4866 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07004867 bool isSecure() const override { return false; }
4868 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004869 Rect getSourceCrop() const override {
4870 if (mCrop.isEmpty()) {
4871 return getBounds();
4872 } else {
4873 return mCrop;
4874 }
4875 }
Robert Carr578038f2018-03-09 12:25:24 -08004876 class ReparentForDrawing {
4877 public:
4878 const sp<Layer>& oldParent;
4879 const sp<Layer>& newParent;
4880
4881 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4882 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004883 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004884 }
Robert Carr15eae092018-03-23 13:43:53 -07004885 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004886 };
4887
4888 void render(std::function<void()> drawLayers) override {
4889 if (!mChildrenOnly) {
4890 mTransform = mLayer->getTransform().inverse();
4891 drawLayers();
4892 } else {
4893 Rect bounds = getBounds();
4894 screenshotParentLayer =
4895 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4896 bounds.getWidth(), bounds.getHeight(), 0);
4897
4898 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4899 drawLayers();
4900 }
4901 }
chaviwa76b2712017-09-20 12:02:26 -07004902
chaviwa76b2712017-09-20 12:02:26 -07004903 private:
chaviw7206d492017-11-10 16:16:12 -08004904 const sp<Layer> mLayer;
4905 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004906
4907 // In the "childrenOnly" case we reparent the children to a screenshot
4908 // layer which has no properties set and which does not draw.
4909 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07004910 ui::Transform mTransform;
Robert Carr578038f2018-03-09 12:25:24 -08004911
4912 SurfaceFlinger* mFlinger;
4913 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004914 };
4915
4916 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4917 auto parent = layerHandle->owner.promote();
4918
chaviw7206d492017-11-10 16:16:12 -08004919 if (parent == nullptr || parent->isPendingRemoval()) {
4920 ALOGE("captureLayers called with a removed parent");
4921 return NAME_NOT_FOUND;
4922 }
4923
Robert Carr578038f2018-03-09 12:25:24 -08004924 const int uid = IPCThreadState::self()->getCallingUid();
4925 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4926 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4927 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4928 return PERMISSION_DENIED;
4929 }
4930
chaviw7206d492017-11-10 16:16:12 -08004931 Rect crop(sourceCrop);
4932 if (sourceCrop.width() <= 0) {
4933 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07004934 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08004935 }
4936
4937 if (sourceCrop.height() <= 0) {
4938 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07004939 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08004940 }
4941
4942 int32_t reqWidth = crop.width() * frameScale;
4943 int32_t reqHeight = crop.height() * frameScale;
4944
Robert Carr578038f2018-03-09 12:25:24 -08004945 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004946
Robert Carr578038f2018-03-09 12:25:24 -08004947 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004948 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4949 if (!layer->isVisible()) {
4950 return;
Robert Carr578038f2018-03-09 12:25:24 -08004951 } else if (childrenOnly && layer == parent.get()) {
4952 return;
chaviwa76b2712017-09-20 12:02:26 -07004953 }
4954 visitor(layer);
4955 });
4956 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004957 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004958}
4959
4960status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4961 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004962 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004963 bool useIdentityTransform) {
4964 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004965
Iris Chang7501ed62018-04-30 14:45:42 +08004966 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004967
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004968 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4969 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4970 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4971 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004972
4973 // This mutex protects syncFd and captureResult for communication of the return values from the
4974 // main thread back to this Binder thread
4975 std::mutex captureMutex;
4976 std::condition_variable captureCondition;
4977 std::unique_lock<std::mutex> captureLock(captureMutex);
4978 int syncFd = -1;
4979 std::optional<status_t> captureResult;
4980
Robert Carr03480e22018-01-04 16:02:06 -08004981 const int uid = IPCThreadState::self()->getCallingUid();
4982 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4983
Dominik Laskowski8c001672018-05-30 16:52:06 -07004984 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004985 // If there is a refresh pending, bug out early and tell the binder thread to try again
4986 // after the refresh.
4987 if (mRefreshPending) {
4988 ATRACE_NAME("Skipping screenshot for now");
4989 std::unique_lock<std::mutex> captureLock(captureMutex);
4990 captureResult = std::make_optional<status_t>(EAGAIN);
4991 captureCondition.notify_one();
4992 return;
4993 }
4994
4995 status_t result = NO_ERROR;
4996 int fd = -1;
4997 {
4998 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07004999 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005000 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5001 useIdentityTransform, forSystem, &fd);
5002 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005003 }
5004
5005 {
5006 std::unique_lock<std::mutex> captureLock(captureMutex);
5007 syncFd = fd;
5008 captureResult = std::make_optional<status_t>(result);
5009 captureCondition.notify_one();
5010 }
5011 });
5012
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005013 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005014 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005015 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005016 while (*captureResult == EAGAIN) {
5017 captureResult.reset();
5018 result = postMessageAsync(message);
5019 if (result != NO_ERROR) {
5020 return result;
5021 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005022 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005023 }
5024 result = *captureResult;
5025 }
5026
5027 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005028 sync_wait(syncFd, -1);
5029 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005030 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005031
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005032 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005033}
5034
chaviwa76b2712017-09-20 12:02:26 -07005035void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5036 TraverseLayersFunction traverseLayers, bool yswap,
5037 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005038 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005039
Lloyd Pique144e1162017-12-20 16:44:52 -08005040 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005041
5042 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005043 const auto raWidth = renderArea.getWidth();
5044 const auto raHeight = renderArea.getHeight();
5045
5046 const auto reqWidth = renderArea.getReqWidth();
5047 const auto reqHeight = renderArea.getReqHeight();
5048 Rect sourceCrop = renderArea.getSourceCrop();
5049
Iris Chang7501ed62018-04-30 14:45:42 +08005050 bool filtering = false;
5051 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5052 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5053 static_cast<int32_t>(reqHeight) != raWidth;
5054 } else {
5055 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5056 static_cast<int32_t>(reqHeight) != raHeight;
5057 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005058
Dan Stozac1879002014-05-22 15:59:05 -07005059 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005060 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005061 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005062 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005063 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
Peiyong Linefefaac2018-08-17 12:27:51 -07005064 ui::Transform tr;
Iris Chang7501ed62018-04-30 14:45:42 +08005065 uint32_t flags = 0x00;
5066 switch (mPrimaryDisplayOrientation) {
5067 case DisplayState::eOrientation90:
Peiyong Linefefaac2018-08-17 12:27:51 -07005068 flags = ui::Transform::ROT_90;
Iris Chang7501ed62018-04-30 14:45:42 +08005069 break;
5070 case DisplayState::eOrientation180:
Peiyong Linefefaac2018-08-17 12:27:51 -07005071 flags = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005072 break;
5073 case DisplayState::eOrientation270:
Peiyong Linefefaac2018-08-17 12:27:51 -07005074 flags = ui::Transform::ROT_270;
Iris Chang7501ed62018-04-30 14:45:42 +08005075 break;
5076 }
5077 tr.set(flags, raWidth, raHeight);
5078 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005079 }
5080
5081 // ensure that sourceCrop is inside screen
5082 if (sourceCrop.left < 0) {
5083 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5084 }
chaviwa76b2712017-09-20 12:02:26 -07005085 if (sourceCrop.right > raWidth) {
5086 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005087 }
5088 if (sourceCrop.top < 0) {
5089 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5090 }
chaviwa76b2712017-09-20 12:02:26 -07005091 if (sourceCrop.bottom > raHeight) {
5092 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005093 }
5094
Chia-I Wu36574d92018-05-16 10:54:36 -07005095 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5096 engine.setOutputDataSpace(Dataspace::SRGB);
5097 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005098
Mathias Agopian180f10d2013-04-10 22:55:41 -07005099 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005100 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005101
Peiyong Linefefaac2018-08-17 12:27:51 -07005102 ui::Transform::orientation_flags rotation = renderArea.getRotationFlags();
Iris Chang7501ed62018-04-30 14:45:42 +08005103 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5104 // convert hw orientation into flag presentation
5105 // here inverse transform needed
5106 uint8_t hw_rot_90 = 0x00;
5107 uint8_t hw_flip_hv = 0x00;
5108 switch (mPrimaryDisplayOrientation) {
5109 case DisplayState::eOrientation90:
Peiyong Linefefaac2018-08-17 12:27:51 -07005110 hw_rot_90 = ui::Transform::ROT_90;
5111 hw_flip_hv = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005112 break;
5113 case DisplayState::eOrientation180:
Peiyong Linefefaac2018-08-17 12:27:51 -07005114 hw_flip_hv = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005115 break;
5116 case DisplayState::eOrientation270:
Peiyong Linefefaac2018-08-17 12:27:51 -07005117 hw_rot_90 = ui::Transform::ROT_90;
Iris Chang7501ed62018-04-30 14:45:42 +08005118 break;
5119 }
5120
5121 // transform flags operation
5122 // 1) flip H V if both have ROT_90 flag
5123 // 2) XOR these flags
Peiyong Linefefaac2018-08-17 12:27:51 -07005124 uint8_t rotation_rot_90 = rotation & ui::Transform::ROT_90;
5125 uint8_t rotation_flip_hv = rotation & ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005126 if (rotation_rot_90 & hw_rot_90) {
Peiyong Linefefaac2018-08-17 12:27:51 -07005127 rotation_flip_hv = (~rotation_flip_hv) & ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005128 }
Peiyong Linefefaac2018-08-17 12:27:51 -07005129 rotation = static_cast<ui::Transform::orientation_flags>
Iris Chang7501ed62018-04-30 14:45:42 +08005130 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5131 }
5132
Mathias Agopian180f10d2013-04-10 22:55:41 -07005133 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005134 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005135 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005136 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005137
chaviw50da5042018-04-09 13:49:37 -07005138 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005139 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005140 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005141
chaviwa76b2712017-09-20 12:02:26 -07005142 traverseLayers([&](Layer* layer) {
5143 if (filtering) layer->setFiltering(true);
David Sodmanca10ed22018-04-16 14:10:25 -07005144 layer->drawNow(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005145 if (filtering) layer->setFiltering(false);
5146 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005147}
5148
chaviwa76b2712017-09-20 12:02:26 -07005149status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5150 TraverseLayersFunction traverseLayers,
5151 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005152 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005153 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005154 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005155 ATRACE_CALL();
5156
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005157 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005158
5159 traverseLayers([&](Layer* layer) {
5160 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5161 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005162
Robert Carr03480e22018-01-04 16:02:06 -08005163 // We allow the system server to take screenshots of secure layers for
5164 // use in situations like the Screen-rotation animation and place
5165 // the impetus on WindowManager to not persist them.
5166 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005167 ALOGW("FB is protected: PERMISSION_DENIED");
5168 return PERMISSION_DENIED;
5169 }
5170
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005171 // this binds the given EGLImage as a framebuffer for the
5172 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005173 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005174 if (bufferBond.getStatus() != NO_ERROR) {
5175 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005176 return INVALID_OPERATION;
5177 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005178
Dan Stozaabcda352017-06-01 14:37:39 -07005179 // this will in fact render into our dequeued buffer
5180 // via an FBO, which means we didn't have to create
5181 // an EGLSurface and therefore we're not
5182 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005183 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005184
Dan Stozaabcda352017-06-01 14:37:39 -07005185 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005186 getRenderEngine().finish();
5187 *outSyncFd = -1;
5188
chaviwa76b2712017-09-20 12:02:26 -07005189 const auto reqWidth = renderArea.getReqWidth();
5190 const auto reqHeight = renderArea.getReqHeight();
5191
Dan Stozaabcda352017-06-01 14:37:39 -07005192 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5193 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005194 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005195 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005196 } else {
5197 base::unique_fd syncFd = getRenderEngine().flush();
5198 if (syncFd < 0) {
5199 getRenderEngine().finish();
5200 }
5201 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005202 }
5203
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005204 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005205}
5206
Mathias Agopiand5556842013-09-19 17:08:37 -07005207void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005208 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005209 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005210 for (size_t y = 0; y < h; y++) {
5211 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5212 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005213 if (p[x] != 0xFF000000) return;
5214 }
5215 }
chaviwa76b2712017-09-20 12:02:26 -07005216 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005217
Robert Carr2047fae2016-11-28 14:09:09 -08005218 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005219 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005220 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005221 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5222 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5223 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5224 static_cast<float>(state.color.a));
5225 i++;
5226 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005227 }
5228}
5229
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005230// ---------------------------------------------------------------------------
5231
Dan Stoza412903f2017-04-27 13:42:17 -07005232void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5233 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005234}
5235
Dan Stoza412903f2017-04-27 13:42:17 -07005236void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5237 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005238}
5239
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005240void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5241 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005242 const LayerVector::Visitor& visitor) {
5243 // We loop through the first level of layers without traversing,
5244 // as we need to interpret min/max layer Z in the top level Z space.
5245 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005246 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005247 continue;
5248 }
5249 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005250 // relative layers are traversed in Layer::traverseInZOrder
5251 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005252 continue;
5253 }
5254 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005255 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005256 return;
5257 }
chaviwa76b2712017-09-20 12:02:26 -07005258 if (!layer->isVisible()) {
5259 return;
5260 }
5261 visitor(layer);
5262 });
5263 }
5264}
5265
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005266}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005267
Lloyd Pique074e8122018-07-26 12:57:23 -07005268
Mathias Agopian3f844832013-08-07 21:24:32 -07005269#if defined(__gl_h_)
5270#error "don't include gl/gl.h in this file"
5271#endif
5272
5273#if defined(__gl2_h_)
5274#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005275#endif