blob: 55b88f998bb2dd543a212debc94a37ef56cb3238 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Chia-I Wud49d6692018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070050
51#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070066#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070067#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020070#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080072#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080073#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070081#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070082#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070083#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070084#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
Mathias Agopian875d8e12013-06-07 15:35:48 -070086#include "RenderEngine/RenderEngine.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070087#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070088#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070089#include "Scheduler/EventControlThread.h"
90#include "Scheduler/EventThread.h"
91
Mathias Agopianff2ed702013-09-01 21:36:12 -070092#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070093
Jiyong Park4b20c2e2017-01-14 19:45:11 +090094#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080095#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
96#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090097#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090098
chaviw1d044282017-09-27 12:19:28 -070099#include <layerproto/LayerProtoParser.h>
100
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800101#define DISPLAY_COUNT 1
102
Mathias Agopianfee2b462013-07-03 12:34:01 -0700103/*
104 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
105 * black pixels.
106 */
107#define DEBUG_SCREENSHOTS false
108
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800109namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700110
Jaesoo Lee43518572017-01-23 19:03:16 +0900111using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900112using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700113using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700114using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700115using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700116using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900117
Steven Thomasb02664d2017-07-26 18:48:28 -0700118namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700119
120#pragma clang diagnostic push
121#pragma clang diagnostic error "-Wswitch-enum"
122
123bool isWideColorMode(const ColorMode colorMode) {
124 switch (colorMode) {
125 case ColorMode::DISPLAY_P3:
126 case ColorMode::ADOBE_RGB:
127 case ColorMode::DCI_P3:
128 case ColorMode::BT2020:
129 case ColorMode::BT2100_PQ:
130 case ColorMode::BT2100_HLG:
131 return true;
132 case ColorMode::NATIVE:
133 case ColorMode::STANDARD_BT601_625:
134 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
135 case ColorMode::STANDARD_BT601_525:
136 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
137 case ColorMode::STANDARD_BT709:
138 case ColorMode::SRGB:
139 return false;
140 }
141 return false;
142}
143
144#pragma clang diagnostic pop
145
Steven Thomasb02664d2017-07-26 18:48:28 -0700146class ConditionalLock {
147public:
148 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
149 if (lock) {
150 mMutex.lock();
151 }
152 }
153 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
154private:
155 Mutex& mMutex;
156 bool mLocked;
157};
Peiyong Linfca547f2018-07-09 13:03:33 -0700158
Steven Thomasb02664d2017-07-26 18:48:28 -0700159} // namespace anonymous
160
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800161// ---------------------------------------------------------------------------
162
Mathias Agopian99b49842011-06-27 16:05:52 -0700163const String16 sHardwareTest("android.permission.HARDWARE_TEST");
164const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
165const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
166const String16 sDump("android.permission.DUMP");
167
168// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800169int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
170int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700171int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700172bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800173uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800174bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800175bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800176int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800177// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600178bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700179
Kalle Raitaa099a242017-01-11 11:17:29 -0800180
181std::string getHwcServiceName() {
182 char value[PROPERTY_VALUE_MAX] = {};
183 property_get("debug.sf.hwc_service_name", value, "default");
184 ALOGI("Using HWComposer service: '%s'", value);
185 return std::string(value);
186}
187
188bool useTrebleTestingOverride() {
189 char value[PROPERTY_VALUE_MAX] = {};
190 property_get("debug.sf.treble_testing_override", value, "false");
191 ALOGI("Treble testing override: '%s'", value);
192 return std::string(value) == "true";
193}
194
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800195std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
196 switch(displayColorSetting) {
197 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700198 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800199 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700200 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800201 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700202 return std::string("Enhanced");
203 default:
204 return std::string("Unknown ") +
205 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800206 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800207}
208
Lloyd Pique99d3da52018-01-22 17:48:03 -0800209NativeWindowSurface::~NativeWindowSurface() = default;
210
211namespace impl {
212
213class NativeWindowSurface final : public android::NativeWindowSurface {
214public:
215 static std::unique_ptr<android::NativeWindowSurface> create(
216 const sp<IGraphicBufferProducer>& producer) {
217 return std::make_unique<NativeWindowSurface>(producer);
218 }
219
220 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
221 : surface(new Surface(producer, false)) {}
222
223 ~NativeWindowSurface() override = default;
224
225private:
226 sp<ANativeWindow> getNativeWindow() const override { return surface; }
227
228 void preallocateBuffers() override { surface->allocateBuffers(); }
229
230 sp<Surface> surface;
231};
232
233} // namespace impl
234
David Sodmanbc815282017-11-05 18:57:52 -0800235SurfaceFlingerBE::SurfaceFlingerBE()
236 : mHwcServiceName(getHwcServiceName()),
237 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800238 mFrameBuckets(),
239 mTotalTime(0),
240 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800241 mComposerSequenceId(0) {
242}
243
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800244SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800245 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800246 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700247 mTransactionPending(false),
248 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700249 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700250 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700251 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800252 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700253 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800254 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800255 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800256 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800257 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800258 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700259 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700260 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700261 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700262 mDebugInSwapBuffers(0),
263 mLastSwapBufferTime(0),
264 mDebugInTransaction(0),
265 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700266 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700267 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700268 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800269 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800270 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700271 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800272 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800273 mCreateBufferQueue(&BufferQueue::createBufferQueue),
274 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800275
276SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800277 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800278
279 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
280 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
281
282 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
283 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
284
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800285 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
286 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800287
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700288 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
289 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
290
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700291 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
292 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
293
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800294 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
295 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
296
Steven Thomas050b2c82017-03-06 11:45:16 -0800297 // Vr flinger is only enabled on Daydream ready devices.
298 useVrFlinger = getBool< ISurfaceFlingerConfigs,
299 &ISurfaceFlingerConfigs::useVrFlinger>(false);
300
Fabien Sanglard1971b632017-03-10 14:50:03 -0800301 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
302 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
303
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600304 hasWideColorDisplay =
305 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
306
Iris Chang7501ed62018-04-30 14:45:42 +0800307 V1_1::DisplayOrientation primaryDisplayOrientation =
308 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
309 V1_1::DisplayOrientation::ORIENTATION_0);
310
311 switch (primaryDisplayOrientation) {
312 case V1_1::DisplayOrientation::ORIENTATION_90:
313 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
314 break;
315 case V1_1::DisplayOrientation::ORIENTATION_180:
316 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
317 break;
318 case V1_1::DisplayOrientation::ORIENTATION_270:
319 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
320 break;
321 default:
322 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
323 break;
324 }
325 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
326
Lloyd Pique41be5d22018-06-21 13:11:48 -0700327 // Note: We create a local temporary with the real DispSync implementation
328 // type temporarily so we can initialize it with the configured values,
329 // before storing it for more generic use using the interface type.
330 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
331 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
332 SurfaceFlinger::dispSyncPresentTimeOffset);
333 mPrimaryDispSync = std::move(primaryDispSync);
Saurabh Shahf4174532017-07-13 10:45:07 -0700334
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800335 // debugging stuff...
336 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700337
Mathias Agopianb4b17302013-03-20 18:36:41 -0700338 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700339 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700340
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800341 property_get("debug.sf.showupdates", value, "0");
342 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700343
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700344 property_get("debug.sf.ddms", value, "0");
345 mDebugDDMS = atoi(value);
346 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700347 if (!startDdmConnection()) {
348 // start failed, and DDMS debugging not enabled
349 mDebugDDMS = 0;
350 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700351 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700352 ALOGI_IF(mDebugRegion, "showupdates enabled");
353 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700354
355 property_get("debug.sf.disable_backpressure", value, "0");
356 mPropagateBackpressure = !atoi(value);
357 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700358
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800359 property_get("debug.sf.enable_hwc_vds", value, "0");
360 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800361 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800362
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800363 property_get("ro.sf.disable_triple_buffer", value, "1");
364 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800365 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700366
Yiwei Zhang243b3782018-05-15 17:40:04 -0700367 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700368 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
369 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
370
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200371 property_get("debug.sf.early_phase_offset_ns", value, "-1");
372 const int earlySfOffsetNs = atoi(value);
373
374 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
375 const int earlyGlSfOffsetNs = atoi(value);
376
377 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
378 const int earlyAppOffsetNs = atoi(value);
379
380 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
381 const int earlyGlAppOffsetNs = atoi(value);
382
383 const VSyncModulator::Offsets earlyOffsets =
384 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
385 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
386 const VSyncModulator::Offsets earlyGlOffsets =
387 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
388 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
389 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
390 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700391
Romain Guy11d63f42017-07-20 12:47:14 -0700392 // We should be reading 'persist.sys.sf.color_saturation' here
393 // but since /data may be encrypted, we need to wait until after vold
394 // comes online to attempt to read the property. The property is
395 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800396
397 if (useTrebleTestingOverride()) {
398 // Without the override SurfaceFlinger cannot connect to HIDL
399 // services that are not listed in the manifests. Considered
400 // deriving the setting from the set service name, but it
401 // would be brittle if the name that's not 'default' is used
402 // for production purposes later on.
403 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
404 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800405}
406
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800407void SurfaceFlinger::onFirstRef()
408{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800409 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800410}
411
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800412SurfaceFlinger::~SurfaceFlinger()
413{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800414}
415
Dan Stozac7014012014-02-14 15:03:43 -0800416void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800417{
418 // the window manager died on us. prepare its eulogy.
419
Andy McFadden13a082e2012-08-24 10:16:42 -0700420 // restore initial conditions (default device unblank, etc)
421 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800422
423 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700424 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800425}
426
Robert Carr1db73f62016-12-21 12:58:51 -0800427static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700428 status_t err = client->initCheck();
429 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800430 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800431 }
Robert Carr1db73f62016-12-21 12:58:51 -0800432 return nullptr;
433}
434
435sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
436 return initClient(new Client(this));
437}
438
439sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
440 const sp<IGraphicBufferProducer>& gbp) {
441 if (authenticateSurfaceTexture(gbp) == false) {
442 return nullptr;
443 }
444 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
445 if (layer == nullptr) {
446 return nullptr;
447 }
448
449 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800450}
451
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700452sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
453 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700454{
455 class DisplayToken : public BBinder {
456 sp<SurfaceFlinger> flinger;
457 virtual ~DisplayToken() {
458 // no more references, this display must be terminated
459 Mutex::Autolock _l(flinger->mStateLock);
460 flinger->mCurrentState.displays.removeItem(this);
461 flinger->setTransactionFlags(eDisplayTransactionNeeded);
462 }
463 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700464 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700465 : flinger(flinger) {
466 }
467 };
468
469 sp<BBinder> token = new DisplayToken(this);
470
471 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700472 DisplayDeviceState info;
473 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700474 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700475 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700476 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800477 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700478 return token;
479}
480
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700481void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700482 Mutex::Autolock _l(mStateLock);
483
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700484 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700485 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700486 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700487 return;
488 }
489
490 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700491 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700492 ALOGE("destroyDisplay called for non-virtual display");
493 return;
494 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700495 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700496 mCurrentState.displays.removeItemsAt(idx);
497 setTransactionFlags(eDisplayTransactionNeeded);
498}
499
Mathias Agopiane57f2922012-08-09 16:29:12 -0700500sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700501 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700502 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800503 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700504 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700505 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700506}
507
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800508void SurfaceFlinger::bootFinished()
509{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700510 if (mStartPropertySetThread->join() != NO_ERROR) {
511 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800512 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800513 const nsecs_t now = systemTime();
514 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000515 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700516
517 // wait patiently for the window manager death
518 const String16 name("window");
519 sp<IBinder> window(defaultServiceManager()->getService(name));
520 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700521 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700522 }
523
Steven Thomas050b2c82017-03-06 11:45:16 -0800524 if (mVrFlinger) {
525 mVrFlinger->OnBootFinished();
526 }
527
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700528 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700529 // formerly we would just kill the process, but we now ask it to exit so it
530 // can choose where to stop the animation.
531 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700532
533 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
534 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
535 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700536
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800537 postMessageAsync(new LambdaMessage([this] {
538 readPersistentProperties();
539 mBootStage = BootStage::FINISHED;
540 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800541}
542
Dan Stoza436ccf32018-06-21 12:10:12 -0700543uint32_t SurfaceFlinger::getNewTexture() {
544 {
545 std::lock_guard lock(mTexturePoolMutex);
546 if (!mTexturePool.empty()) {
547 uint32_t name = mTexturePool.back();
548 mTexturePool.pop_back();
549 ATRACE_INT("TexturePoolSize", mTexturePool.size());
550 return name;
551 }
552
553 // The pool was too small, so increase it for the future
554 ++mTexturePoolSize;
555 }
556
557 // The pool was empty, so we need to get a new texture name directly using a
558 // blocking call to the main thread
559 uint32_t name = 0;
560 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
561 return name;
562}
563
Mathias Agopian3f844832013-08-07 21:24:32 -0700564void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700565 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700566}
567
Lloyd Piquee83f9312018-02-01 12:53:17 -0800568class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700569public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800570 InjectVSyncSource() = default;
571 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700572
Lloyd Piquee83f9312018-02-01 12:53:17 -0800573 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700574 std::lock_guard<std::mutex> lock(mCallbackMutex);
575 mCallback = callback;
576 }
577
Lloyd Piquee83f9312018-02-01 12:53:17 -0800578 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700579 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700580 if (mCallback) {
581 mCallback->onVSyncEvent(when);
582 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700583 }
584
Lloyd Piquee83f9312018-02-01 12:53:17 -0800585 void setVSyncEnabled(bool) override {}
586 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700587
588private:
589 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800590 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700591};
592
Wei Wangf9b05ee2017-07-19 20:59:39 -0700593// Do not call property_set on main thread which will be blocked by init
594// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700595void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700596 ALOGI( "SurfaceFlinger's main thread ready to run. "
597 "Initializing graphics H/W...");
598
Thierry Strudel2924d012017-08-14 15:19:37 -0700599 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900600
Steven Thomasb02664d2017-07-26 18:48:28 -0700601 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800602
Steven Thomasb02664d2017-07-26 18:48:28 -0700603 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800604 mEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700605 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
606 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800607 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700608 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800609 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800610 "appEventThread");
611 mSfEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700612 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800613 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800614
Lloyd Pique24b0a482018-03-09 18:52:26 -0800615 mSFEventThread =
616 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700617 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800618 [this](nsecs_t timestamp) {
619 mInterceptor->saveVSyncEvent(timestamp);
620 },
621 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800622 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200623 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800624
Steven Thomasb02664d2017-07-26 18:48:28 -0700625 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800626 getBE().mRenderEngine =
627 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
628 hasWideColorDisplay
629 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
630 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800631 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700632
633 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
634 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800635 getBE().mHwc.reset(
636 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700637 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800638 // Process any initial hotplug and resulting display changes.
639 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700640 const auto display = getDefaultDisplayDeviceLocked();
641 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
642 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
643 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800644
Lloyd Piquefcd86612017-12-14 17:15:36 -0800645 // make the default display GLContext current so that we can create textures
646 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700647 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800648
Steven Thomas050b2c82017-03-06 11:45:16 -0800649 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700650 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700651 // This callback is called from the vr flinger dispatch thread. We
652 // need to call signalTransaction(), which requires holding
653 // mStateLock when we're not on the main thread. Acquiring
654 // mStateLock from the vr flinger dispatch thread might trigger a
655 // deadlock in surface flinger (see b/66916578), so post a message
656 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700657 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700658 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
659 mVrFlingerRequestsDisplay = requestDisplay;
660 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700661 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800662 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700663 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
664 getHwComposer()
665 .getHwcDisplayId(display->getId())
666 .value_or(0),
667 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800668 if (!mVrFlinger) {
669 ALOGE("Failed to start vrflinger");
670 }
671 }
672
Lloyd Pique379adc12018-01-22 17:31:47 -0800673 mEventControlThread = std::make_unique<impl::EventControlThread>(
674 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700675
Mathias Agopian92a979a2012-08-02 18:32:23 -0700676 // initialize our drawing state
677 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700678
Andy McFadden13a082e2012-08-24 10:16:42 -0700679 // set initial conditions (e.g. unblank default device)
680 initializeDisplays();
681
David Sodmanbc815282017-11-05 18:57:52 -0800682 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700683
Wei Wangf9b05ee2017-07-19 20:59:39 -0700684 // Inform native graphics APIs whether the present timestamp is supported:
685 if (getHwComposer().hasCapability(
686 HWC2::Capability::PresentFenceIsNotReliable)) {
687 mStartPropertySetThread = new StartPropertySetThread(false);
688 } else {
689 mStartPropertySetThread = new StartPropertySetThread(true);
690 }
691
692 if (mStartPropertySetThread->Start() != NO_ERROR) {
693 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800694 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800695
Chia-I Wud49d6692018-06-27 07:17:41 +0800696 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
697 // is used to saturate legacy sRGB content. However, to make sure the same color under
698 // Display P3 will be saturated to the same color, we intentionally break the API spec
699 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
700 // such saturation matrix on Display P3 is understood fully, the API should always return
701 // identify matrix.
702 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
703 Dataspace::SRGB_LINEAR);
704
705 // we will apply this on Display P3.
706 if (mEnhancedSaturationMatrix != mat4()) {
707 ColorSpace srgb(ColorSpace::sRGB());
708 ColorSpace displayP3(ColorSpace::DisplayP3());
709 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
710 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
711 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
712 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800713
Dan Stoza9e56aa02015-11-02 13:00:03 -0800714 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700715}
716
Romain Guy11d63f42017-07-20 12:47:14 -0700717void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700718 Mutex::Autolock _l(mStateLock);
719
Romain Guy11d63f42017-07-20 12:47:14 -0700720 char value[PROPERTY_VALUE_MAX];
721
722 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800723 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700724 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800725 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100726
727 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700728 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700729}
730
Mathias Agopiana67e4182012-06-19 17:26:12 -0700731void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800732 // Start boot animation service by setting a property mailbox
733 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700734 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800735 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700736 if (mStartPropertySetThread->join() != NO_ERROR) {
737 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800738 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700739}
740
Mathias Agopian875d8e12013-06-07 15:35:48 -0700741size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800742 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700743}
744
Mathias Agopian875d8e12013-06-07 15:35:48 -0700745size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800746 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700747}
748
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800749// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800750
Jamie Gennis582270d2011-08-17 18:19:00 -0700751bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800752 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800753 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800754 return authenticateSurfaceTextureLocked(bufferProducer);
755}
756
757bool SurfaceFlinger::authenticateSurfaceTextureLocked(
758 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800759 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800760 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800761}
762
Brian Anderson6b376712017-04-04 10:51:39 -0700763status_t SurfaceFlinger::getSupportedFrameTimestamps(
764 std::vector<FrameEvent>* outSupported) const {
765 *outSupported = {
766 FrameEvent::REQUESTED_PRESENT,
767 FrameEvent::ACQUIRE,
768 FrameEvent::LATCH,
769 FrameEvent::FIRST_REFRESH_START,
770 FrameEvent::LAST_REFRESH_START,
771 FrameEvent::GPU_COMPOSITION_DONE,
772 FrameEvent::DEQUEUE_READY,
773 FrameEvent::RELEASE,
774 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700775 ConditionalLock _l(mStateLock,
776 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700777 if (!getHwComposer().hasCapability(
778 HWC2::Capability::PresentFenceIsNotReliable)) {
779 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
780 }
781 return NO_ERROR;
782}
783
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700784status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
785 Vector<DisplayInfo>* configs) {
786 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700787 return BAD_VALUE;
788 }
789
Jesse Hall692c7232012-11-08 15:41:56 -0800790 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700791 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
792 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700793 type = i;
794 break;
795 }
796 }
797
798 if (type < 0) {
799 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700800 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700801
Mathias Agopian8b736f12012-08-13 17:54:26 -0700802 // TODO: Not sure if display density should handled by SF any longer
803 class Density {
804 static int getDensityFromProperty(char const* propName) {
805 char property[PROPERTY_VALUE_MAX];
806 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800807 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700808 density = atoi(property);
809 }
810 return density;
811 }
812 public:
813 static int getEmuDensity() {
814 return getDensityFromProperty("qemu.sf.lcd_density"); }
815 static int getBuildDensity() {
816 return getDensityFromProperty("ro.sf.lcd_density"); }
817 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700818
Dan Stoza7f7da322014-05-02 15:26:25 -0700819 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700820
Steven Thomas6d8110b2017-08-31 18:24:21 -0700821 ConditionalLock _l(mStateLock,
822 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800823 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700824 DisplayInfo info = DisplayInfo();
825
Dan Stoza9e56aa02015-11-02 13:00:03 -0800826 float xdpi = hwConfig->getDpiX();
827 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700828
829 if (type == DisplayDevice::DISPLAY_PRIMARY) {
830 // The density of the device is provided by a build property
831 float density = Density::getBuildDensity() / 160.0f;
832 if (density == 0) {
833 // the build doesn't provide a density -- this is wrong!
834 // use xdpi instead
835 ALOGE("ro.sf.lcd_density must be defined as a build property");
836 density = xdpi / 160.0f;
837 }
838 if (Density::getEmuDensity()) {
839 // if "qemu.sf.lcd_density" is specified, it overrides everything
840 xdpi = ydpi = density = Density::getEmuDensity();
841 density /= 160.0f;
842 }
843 info.density = density;
844
845 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700846 const auto display = getDefaultDisplayDeviceLocked();
847 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700848 } else {
849 // TODO: where should this value come from?
850 static const int TV_DENSITY = 213;
851 info.density = TV_DENSITY / 160.0f;
852 info.orientation = 0;
853 }
854
Dan Stoza9e56aa02015-11-02 13:00:03 -0800855 info.w = hwConfig->getWidth();
856 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700857 info.xdpi = xdpi;
858 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800859 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900860 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800861
Andy McFadden91b2ca82014-06-13 14:04:23 -0700862 // This is how far in advance a buffer must be queued for
863 // presentation at a given time. If you want a buffer to appear
864 // on the screen at time N, you must submit the buffer before
865 // (N - presentationDeadline).
866 //
867 // Normally it's one full refresh period (to give SF a chance to
868 // latch the buffer), but this can be reduced by configuring a
869 // DispSync offset. Any additional delays introduced by the hardware
870 // composer or panel must be accounted for here.
871 //
872 // We add an additional 1ms to allow for processing time and
873 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800874 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800875 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700876
877 // All non-virtual displays are currently considered secure.
878 info.secure = true;
879
Iris Chang7501ed62018-04-30 14:45:42 +0800880 if (type == DisplayDevice::DISPLAY_PRIMARY &&
881 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
882 std::swap(info.w, info.h);
883 }
884
Michael Wright28f24d02016-07-12 13:30:53 -0700885 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700886 }
887
Dan Stoza7f7da322014-05-02 15:26:25 -0700888 return NO_ERROR;
889}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700890
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700891status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
892 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700893 return BAD_VALUE;
894 }
895
896 // FIXME for now we always return stats for the primary display
897 memset(stats, 0, sizeof(*stats));
Lloyd Pique41be5d22018-06-21 13:11:48 -0700898 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
899 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700900 return NO_ERROR;
901}
902
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700903int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
904 const auto display = getDisplayDevice(displayToken);
905 if (!display) {
906 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800907 return BAD_VALUE;
908 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700909
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700910 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700911}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700912
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700913void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
914 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700915 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700916 return;
917 }
918
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700919 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700920 ALOGW("Trying to set config for virtual display");
921 return;
922 }
923
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700924 display->setActiveConfig(mode);
925 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700926}
927
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700928status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700929 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700930 Vector<DisplayInfo> configs;
931 getDisplayConfigs(displayToken, &configs);
932 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
933 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
934 configs.size());
935 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700936 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700937 const auto display = getDisplayDevice(displayToken);
938 if (!display) {
939 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
940 displayToken.get());
941 } else if (display->isVirtual()) {
942 ALOGW("Attempt to set active config %d for virtual display", mode);
943 } else {
944 setActiveConfigInternal(display, mode);
945 }
946 }));
947
Mathias Agopian888c8222012-08-04 21:10:38 -0700948 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700949}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700950status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
951 Vector<ColorMode>* outColorModes) {
952 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700953 return BAD_VALUE;
954 }
955
Michael Wright28f24d02016-07-12 13:30:53 -0700956 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700957 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
958 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700959 type = i;
960 break;
961 }
962 }
963
964 if (type < 0) {
965 return type;
966 }
967
Peiyong Lina52f0292018-03-14 17:26:31 -0700968 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700969 {
970 ConditionalLock _l(mStateLock,
971 std::this_thread::get_id() != mMainThreadId);
972 modes = getHwComposer().getColorModes(type);
973 }
Michael Wright28f24d02016-07-12 13:30:53 -0700974 outColorModes->clear();
975 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
976
977 return NO_ERROR;
978}
979
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700980ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
981 if (const auto display = getDisplayDevice(displayToken)) {
982 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700983 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700984 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700985}
986
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700987void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
988 Dataspace dataSpace, RenderIntent renderIntent) {
989 ColorMode currentMode = display->getActiveColorMode();
990 Dataspace currentDataSpace = display->getCompositionDataSpace();
991 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -0700992
Peiyong Lin38e9a562018-04-10 16:24:20 -0700993 if (mode == currentMode && dataSpace == currentDataSpace &&
994 renderIntent == currentRenderIntent) {
995 return;
996 }
997
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700998 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -0700999 ALOGW("Trying to set config for virtual display");
1000 return;
1001 }
1002
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001003 display->setActiveColorMode(mode);
1004 display->setCompositionDataSpace(dataSpace);
1005 display->setActiveRenderIntent(renderIntent);
1006 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001007
1008 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001009 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1010 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001011}
1012
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001013status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001014 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001015 Vector<ColorMode> modes;
1016 getDisplayColorModes(displayToken, &modes);
1017 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1018 if (mode < ColorMode::NATIVE || !exists) {
1019 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1020 decodeColorMode(mode).c_str(), mode, displayToken.get());
1021 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001022 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001023 const auto display = getDisplayDevice(displayToken);
1024 if (!display) {
1025 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1026 decodeColorMode(mode).c_str(), mode, displayToken.get());
1027 } else if (display->isVirtual()) {
1028 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1029 decodeColorMode(mode).c_str(), mode);
1030 } else {
1031 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1032 RenderIntent::COLORIMETRIC);
1033 }
1034 }));
1035
Michael Wright28f24d02016-07-12 13:30:53 -07001036 return NO_ERROR;
1037}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001038
Svetoslavd85084b2014-03-20 10:28:31 -07001039status_t SurfaceFlinger::clearAnimationFrameStats() {
1040 Mutex::Autolock _l(mStateLock);
1041 mAnimFrameTracker.clearStats();
1042 return NO_ERROR;
1043}
1044
1045status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1046 Mutex::Autolock _l(mStateLock);
1047 mAnimFrameTracker.getStats(outStats);
1048 return NO_ERROR;
1049}
1050
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001051status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1052 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001053 Mutex::Autolock _l(mStateLock);
1054
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001055 const auto display = getDisplayDeviceLocked(displayToken);
1056 if (!display) {
1057 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001058 return BAD_VALUE;
1059 }
1060
Peiyong Linfb069302018-04-25 14:34:31 -07001061 // At this point the DisplayDeivce should already be set up,
1062 // meaning the luminance information is already queried from
1063 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001064 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001065 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1066 capabilities.getDesiredMaxLuminance(),
1067 capabilities.getDesiredMaxAverageLuminance(),
1068 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001069
1070 return NO_ERROR;
1071}
1072
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001073status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001074 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001075 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001076
Chia-I Wu90f669f2017-10-05 14:24:41 -07001077 if (mInjectVSyncs == enable) {
1078 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001079 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001080
1081 if (enable) {
1082 ALOGV("VSync Injections enabled");
1083 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001084 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001085 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001086 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001087 impl::EventThread::InterceptVSyncsCallback(),
1088 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001089 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001090 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001091 } else {
1092 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001093 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001094 }
1095
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001096 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001097 }));
1098
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001099 return NO_ERROR;
1100}
1101
1102status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001103 Mutex::Autolock _l(mStateLock);
1104
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001105 if (!mInjectVSyncs) {
1106 ALOGE("VSync Injections not enabled");
1107 return BAD_VALUE;
1108 }
1109 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1110 ALOGV("Injecting VSync inside SurfaceFlinger");
1111 mVSyncInjector->onInjectSyncEvent(when);
1112 }
1113 return NO_ERROR;
1114}
1115
Lloyd Pique755e3192018-01-31 16:46:15 -08001116status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1117 NO_THREAD_SAFETY_ANALYSIS {
Peiyong Line70e1292018-08-09 14:06:58 -07001118 IPCThreadState* ipc = IPCThreadState::self();
1119 const int pid = ipc->getCallingPid();
1120 const int uid = ipc->getCallingUid();
1121 if ((uid != AID_SHELL) &&
1122 !PermissionCache::checkPermission(sDump, pid, uid)) {
1123 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1124 return PERMISSION_DENIED;
1125 }
1126
Kalle Raitaa099a242017-01-11 11:17:29 -08001127 // Try to acquire a lock for 1s, fail gracefully
1128 const status_t err = mStateLock.timedLock(s2ns(1));
1129 const bool locked = (err == NO_ERROR);
1130 if (!locked) {
1131 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1132 return TIMED_OUT;
1133 }
1134
1135 outLayers->clear();
1136 mCurrentState.traverseInZOrder([&](Layer* layer) {
1137 outLayers->push_back(layer->getLayerDebugInfo());
1138 });
1139
1140 mStateLock.unlock();
1141 return NO_ERROR;
1142}
1143
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001144// ----------------------------------------------------------------------------
1145
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001146sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1147 ISurfaceComposer::VsyncSource vsyncSource) {
1148 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1149 return mSFEventThread->createEventConnection();
1150 } else {
1151 return mEventThread->createEventConnection();
1152 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001153}
1154
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001155// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001156
1157void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001158 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001159}
1160
1161void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001162 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001163}
1164
1165void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001166 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001167}
1168
1169void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001170 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001171 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001172}
1173
1174status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001175 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001176 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001177}
1178
1179status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001180 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001181 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001182 if (res == NO_ERROR) {
1183 msg->wait();
1184 }
1185 return res;
1186}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001187
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001188void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001189 do {
1190 waitForEvent();
1191 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001192}
1193
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001194void SurfaceFlinger::enableHardwareVsync() {
1195 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001196 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001197 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001198 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001199 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001200 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001201}
1202
Jesse Hall948fe0c2013-10-14 12:56:09 -07001203void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001204 Mutex::Autolock _l(mHWVsyncLock);
1205
Jesse Hall948fe0c2013-10-14 12:56:09 -07001206 if (makeAvailable) {
1207 mHWVsyncAvailable = true;
1208 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001209 // Hardware vsync is not currently available, so abort the resync
1210 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001211 return;
1212 }
1213
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001214 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1215 if (!getHwComposer().isConnected(displayId)) {
1216 return;
1217 }
1218
1219 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001220 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001221
Lloyd Pique41be5d22018-06-21 13:11:48 -07001222 mPrimaryDispSync->reset();
1223 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001224
1225 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001226 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001227 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001228 mPrimaryHWVsyncEnabled = true;
1229 }
1230}
1231
Jesse Hall948fe0c2013-10-14 12:56:09 -07001232void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001233 Mutex::Autolock _l(mHWVsyncLock);
1234 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001235 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001236 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001237 mPrimaryHWVsyncEnabled = false;
1238 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001239 if (makeUnavailable) {
1240 mHWVsyncAvailable = false;
1241 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001242}
1243
Tim Murray4a4e4a22016-04-19 16:29:23 +00001244void SurfaceFlinger::resyncWithRateLimit() {
1245 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001246
1247 // No explicit locking is needed here since EventThread holds a lock while calling this method
1248 static nsecs_t sLastResyncAttempted = 0;
1249 const nsecs_t now = systemTime();
1250 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001251 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001252 }
Dan Stoza57164302017-05-08 14:03:54 -07001253 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001254}
1255
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001256void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1257 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001258 ATRACE_NAME("SF onVsync");
1259
Steven Thomas3cfac282017-02-06 12:29:30 -08001260 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001261 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001262 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001263 return;
1264 }
1265
1266 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001267 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001268 return;
1269 }
1270
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001271 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1272 // For now, we don't do anything with external display vsyncs.
1273 return;
1274 }
1275
Jamie Gennisd1700752013-10-14 12:22:52 -07001276 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001277
Jamie Gennisd1700752013-10-14 12:22:52 -07001278 { // Scope for the lock
1279 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001280 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001281 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001282 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001283 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001284
1285 if (needsHwVsync) {
1286 enableHardwareVsync();
1287 } else {
1288 disableHardwareVsync(false);
1289 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001290}
1291
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001292void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001293 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1294 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001295}
1296
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001297void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001298 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001299 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001300 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001301
Lloyd Piqueba04e622017-12-14 17:11:26 -08001302 // Ignore events that do not have the right sequenceId.
1303 if (sequenceId != getBE().mComposerSequenceId) {
1304 return;
1305 }
1306
Steven Thomasb02664d2017-07-26 18:48:28 -07001307 // Only lock if we're not on the main thread. This function is normally
1308 // called on a hwbinder thread, but for the primary display it's called on
1309 // the main thread with the state lock already held, so don't attempt to
1310 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001311 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001312
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001313 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001314
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001315 if (std::this_thread::get_id() == mMainThreadId) {
1316 // Process all pending hot plug events immediately if we are on the main thread.
1317 processDisplayHotplugEventsLocked();
1318 }
1319
Lloyd Piqueba04e622017-12-14 17:11:26 -08001320 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001321}
1322
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001323void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001324 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001325 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001326 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001327 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001328 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001329}
1330
Dan Stoza9e56aa02015-11-02 13:00:03 -08001331void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001332 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001333 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001334 getHwComposer().setVsyncEnabled(disp,
1335 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001336}
1337
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001338// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001339void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001340 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001341 // Clear the drawing state so that the logic inside of
1342 // handleTransactionLocked will fire. It will determine the delta between
1343 // mCurrentState and mDrawingState and re-apply all changes when we make the
1344 // transition.
1345 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001346 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001347 mDisplays.clear();
1348}
1349
Steven Thomas050b2c82017-03-06 11:45:16 -08001350void SurfaceFlinger::updateVrFlinger() {
1351 if (!mVrFlinger)
1352 return;
1353 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001354 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001355 return;
1356 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001357
David Sodman105b7dc2017-11-04 20:28:14 -07001358 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001359 ALOGE("Vr flinger is only supported for remote hardware composer"
1360 " service connections. Ignoring request to transition to vr"
1361 " flinger.");
1362 mVrFlingerRequestsDisplay = false;
1363 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001364 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001365
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001366 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001367
Steven Thomas0123ac62018-07-12 11:32:34 -07001368 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001369 LOG_ALWAYS_FATAL_IF(!display);
1370 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001371 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1372 // called below. Clear the reference now so we don't accidentally use it
1373 // later.
1374 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001375
Steven Thomasb02664d2017-07-26 18:48:28 -07001376 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001377 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001378 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001379
Steven Thomasb02664d2017-07-26 18:48:28 -07001380 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001381 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001382 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1383 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001384 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001385
David Sodman105b7dc2017-11-04 20:28:14 -07001386 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1387 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001388
1389 if (vrFlingerRequestsDisplay) {
1390 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001391 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001392
1393 mVisibleRegionsDirty = true;
1394 invalidateHwcGeometry();
1395
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001396 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001397 display = getDefaultDisplayDeviceLocked();
1398 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001399 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001400
Steven Thomasb02664d2017-07-26 18:48:28 -07001401 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001402 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001403 const nsecs_t period = activeConfig->getVsyncPeriod();
1404 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001405
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001406 // The present fences returned from vr_hwc are not an accurate
1407 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001408 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1409 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001410
Steven Thomasb02664d2017-07-26 18:48:28 -07001411 // Use phase of 0 since phase is not known.
1412 // Use latency of 0, which will snap to the ideal latency.
1413 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001414
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001415 resyncToHardwareVsync(false);
1416
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001417 android_atomic_or(1, &mRepaintEverything);
1418 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001419}
1420
Mathias Agopian4fec8732012-06-29 14:12:52 -07001421void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001422 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001423 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001424 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001425 bool frameMissed = !mHadClientComposition &&
1426 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001427 (mPreviousPresentFence->getSignalTime() ==
1428 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001429 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001430 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001431 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001432 mTimeStats.incrementMissedFrames();
1433 if (mPropagateBackpressure) {
1434 signalLayerUpdate();
1435 break;
1436 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001437 }
Dan Stoza50182882016-07-08 12:02:20 -07001438
Steven Thomas050b2c82017-03-06 11:45:16 -08001439 // Now that we're going to make it to the handleMessageTransaction()
1440 // call below it's safe to call updateVrFlinger(), which will
1441 // potentially trigger a display handoff.
1442 updateVrFlinger();
1443
Dan Stoza6b9454d2014-11-07 16:00:59 -08001444 bool refreshNeeded = handleMessageTransaction();
1445 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001446 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001447 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001448 // Signal a refresh if a transaction modified the window state,
1449 // a new buffer was latched, or if HWC has requested a full
1450 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001451 signalRefresh();
1452 }
1453 break;
1454 }
1455 case MessageQueue::REFRESH: {
1456 handleMessageRefresh();
1457 break;
1458 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001459 }
1460}
1461
Dan Stoza6b9454d2014-11-07 16:00:59 -08001462bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001463 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001464 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001465 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001466 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001467 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001468 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001469}
1470
Dan Stoza6b9454d2014-11-07 16:00:59 -08001471bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001472 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001473 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001474}
1475
1476void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001477 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001478
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001479 mRefreshPending = false;
1480
Lloyd Pique074e8122018-07-26 12:57:23 -07001481 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1482
1483 preComposition(refreshStartTime);
1484 rebuildLayerStacks();
1485 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001486 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001487 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001488 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001489 doComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001490 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001491
Dan Stozabfbffeb2016-07-21 14:49:33 -07001492 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001493 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001494 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001495 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001496 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001497 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001498
Dan Stoza9e56aa02015-11-02 13:00:03 -08001499 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001500}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001501
Mathias Agopiancd60f992012-08-16 16:28:27 -07001502void SurfaceFlinger::doDebugFlashRegions()
1503{
1504 // is debugging enabled
1505 if (CC_LIKELY(!mDebugRegion))
1506 return;
1507
1508 const bool repaintEverything = mRepaintEverything;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001509 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001510 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001511 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001512 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001513 if (!dirtyRegion.isEmpty()) {
1514 // redraw the whole screen
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001515 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001516
1517 // and draw the dirty region
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001518 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001519 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001520 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1521
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001522 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001523 }
1524 }
1525 }
1526
1527 postFramebuffer();
1528
1529 if (mDebugRegion > 1) {
1530 usleep(mDebugRegion * 1000);
1531 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001532
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001533 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001534 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001535 continue;
1536 }
1537
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001538 status_t result = display->prepareFrame(*getBE().mHwc);
1539 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001540 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001541 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001542}
1543
Adrian Roos1e1a1282017-11-01 19:05:31 +01001544void SurfaceFlinger::doTracing(const char* where) {
1545 ATRACE_CALL();
1546 ATRACE_NAME(where);
1547 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001548 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001549 }
1550}
1551
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001552void SurfaceFlinger::logLayerStats() {
1553 ATRACE_CALL();
1554 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001555 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001556 if (display->isPrimary()) {
1557 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001558 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001559 }
1560 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001561
1562 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001563 }
1564}
1565
Lloyd Pique074e8122018-07-26 12:57:23 -07001566void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001567{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001568 ATRACE_CALL();
1569 ALOGV("preComposition");
1570
Mathias Agopiancd60f992012-08-16 16:28:27 -07001571 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001572 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique074e8122018-07-26 12:57:23 -07001573 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001574 needExtraInvalidate = true;
1575 }
Robert Carr2047fae2016-11-28 14:09:09 -08001576 });
1577
Mathias Agopiancd60f992012-08-16 16:28:27 -07001578 if (needExtraInvalidate) {
1579 signalLayerUpdate();
1580 }
1581}
1582
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001583void SurfaceFlinger::updateCompositorTiming(
1584 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1585 std::shared_ptr<FenceTime>& presentFenceTime) {
1586 // Update queue of past composite+present times and determine the
1587 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001588 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001589 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001590 while (!getBE().mCompositePresentTimes.empty()) {
1591 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001592 // Cached values should have been updated before calling this method,
1593 // which helps avoid duplicate syscalls.
1594 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1595 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1596 break;
1597 }
1598 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001599 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001600 }
1601
1602 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001603 while (getBE().mCompositePresentTimes.size() > 16) {
1604 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001605 }
1606
Brian Andersond0010582017-03-07 13:20:31 -08001607 setCompositorTimingSnapped(
1608 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1609}
1610
1611void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1612 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001613 // Integer division and modulo round toward 0 not -inf, so we need to
1614 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001615 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001616 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1617 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1618
Brian Andersond0010582017-03-07 13:20:31 -08001619 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1620 if (idealLatency <= 0) {
1621 idealLatency = vsyncInterval;
1622 }
1623
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001624 // Snap the latency to a value that removes scheduling jitter from the
1625 // composition and present times, which often have >1ms of jitter.
1626 // Reducing jitter is important if an app attempts to extrapolate
1627 // something (such as user input) to an accurate diasplay time.
1628 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1629 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001630 nsecs_t bias = vsyncInterval / 2;
1631 int64_t extraVsyncs =
1632 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1633 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1634 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001635
David Sodman99974d22017-11-28 12:04:33 -08001636 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1637 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1638 getBE().mCompositorTiming.interval = vsyncInterval;
1639 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001640}
1641
Lloyd Pique074e8122018-07-26 12:57:23 -07001642void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001643{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001644 ATRACE_CALL();
1645 ALOGV("postComposition");
1646
Brian Anderson3546a3f2016-07-14 11:51:14 -07001647 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001648 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001649 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001650 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001651 }
1652
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001653 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001654 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001655
David Sodman73beded2017-11-15 11:56:06 -08001656 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001657 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001658 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001659 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001660 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001661 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001662 } else {
1663 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1664 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001665
David Sodman73beded2017-11-15 11:56:06 -08001666 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001667 mPreviousPresentFence =
1668 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1669 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001670 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001671
Lloyd Pique41be5d22018-06-21 13:11:48 -07001672 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1673 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001674
Lloyd Pique074e8122018-07-26 12:57:23 -07001675 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001676 // when we started doing work for this frame, but that should be okay
1677 // since updateCompositorTiming has snapping logic.
1678 updateCompositorTiming(
Lloyd Pique074e8122018-07-26 12:57:23 -07001679 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001680 CompositorTiming compositorTiming;
1681 {
David Sodman99974d22017-11-28 12:04:33 -08001682 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1683 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001684 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001685
Robert Carr2047fae2016-11-28 14:09:09 -08001686 mDrawingState.traverseInZOrder([&](Layer* layer) {
1687 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001688 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001689 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001690 recordBufferingStats(layer->getName().string(),
1691 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001692 }
Robert Carr2047fae2016-11-28 14:09:09 -08001693 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001694
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001695 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001696 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001697 enableHardwareVsync();
1698 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001699 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001700 }
1701 }
1702
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001703 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001704 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001705 enableHardwareVsync();
1706 }
1707 }
1708
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001709 if (mAnimCompositionPending) {
1710 mAnimCompositionPending = false;
1711
Brian Anderson4e606e32017-03-16 15:34:57 -07001712 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001713 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001714 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001715 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001716 // The HWC doesn't support present fences, so use the refresh
1717 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001718 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001719 mAnimFrameTracker.setActualPresentTime(presentTime);
1720 }
1721 mAnimFrameTracker.advanceFrame();
1722 }
Dan Stozab90cf072015-03-05 11:05:59 -08001723
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001724 mTimeStats.incrementTotalFrames();
1725 if (mHadClientComposition) {
1726 mTimeStats.incrementClientCompositionFrames();
1727 }
1728
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001729 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001730 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001731 return;
1732 }
1733
1734 nsecs_t currentTime = systemTime();
1735 if (mHasPoweredOff) {
1736 mHasPoweredOff = false;
1737 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001738 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001739 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001740 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1741 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001742 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001743 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001744 }
David Sodman4a36e932017-11-07 14:29:47 -08001745 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001746 }
David Sodman4a36e932017-11-07 14:29:47 -08001747 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001748
1749 {
1750 std::lock_guard lock(mTexturePoolMutex);
1751 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1752 if (refillCount > 0) {
1753 const size_t offset = mTexturePool.size();
1754 mTexturePool.resize(mTexturePoolSize);
1755 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1756 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1757 }
1758 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001759}
1760
1761void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001762 ATRACE_CALL();
1763 ALOGV("rebuildLayerStacks");
1764
Mathias Agopiancd60f992012-08-16 16:28:27 -07001765 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001766 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001767 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001768 mVisibleRegionsDirty = false;
1769 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001770
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001771 for (const auto& pair : mDisplays) {
1772 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001773 Region opaqueRegion;
1774 Region dirtyRegion;
1775 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001776 Vector<sp<Layer>> layersNeedingFences;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001777 const Transform& tr = display->getTransform();
1778 const Rect bounds = display->getBounds();
1779 if (display->isPoweredOn()) {
1780 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001781
Jeff Sharkey76488112017-02-27 14:15:18 -07001782 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001783 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001784 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001785 Region drawRegion(tr.transform(
1786 layer->visibleNonTransparentRegion));
1787 drawRegion.andSelf(bounds);
1788 if (!drawRegion.isEmpty()) {
1789 layersSortedByZ.add(layer);
1790 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001791 // Clear out the HWC layer if this layer was
1792 // previously visible, but no longer is
1793 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001794 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001795 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001796 // WM changes display->layerStack upon sleep/awake.
1797 // Here we make sure we delete the HWC layers even if
1798 // WM changed their layer stack.
1799 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001800 }
1801
1802 // If a layer is not going to get a release fence because
1803 // it is invisible, but it is also going to release its
1804 // old buffer, add it to the list of layers needing
1805 // fences.
1806 if (hwcLayerDestroyed) {
1807 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1808 mLayersWithQueuedFrames.cend(), layer);
1809 if (found != mLayersWithQueuedFrames.cend()) {
1810 layersNeedingFences.add(layer);
1811 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001812 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001813 });
1814 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001815 display->setVisibleLayersSortedByZ(layersSortedByZ);
1816 display->setLayersNeedingFences(layersNeedingFences);
1817 display->undefinedRegion.set(bounds);
1818 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1819 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001820 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001821 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001822}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001823
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001824// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001825// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001826// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001827// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001828// The returned HDR data space is one of
1829// - Dataspace::UNKNOWN
1830// - Dataspace::BT2020_HLG
1831// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001832Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1833 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001834 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001835 *outHdrDataSpace = Dataspace::UNKNOWN;
1836
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001837 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001838 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001839 case Dataspace::V0_SCRGB:
1840 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001841 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001842 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001843 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001844 case Dataspace::BT2020_PQ:
1845 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001846 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001847 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001848 case Dataspace::BT2020_HLG:
1849 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001850 // When there's mixed PQ content and HLG content, we set the HDR
1851 // data space to be BT2020_PQ and convert HLG to PQ.
1852 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1853 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001854 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001855 break;
1856 default:
1857 break;
1858 }
Romain Guy54f154a2017-10-24 21:40:32 +01001859 }
1860
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001861 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001862}
1863
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001864// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001865void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1866 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001867 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1868 *outMode = ColorMode::NATIVE;
1869 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001870 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001871 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001872 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001873
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001874 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001875 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001876
Peiyong Lindfde5112018-06-05 10:58:41 -07001877 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001878 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001879 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001880 if (isHdr) {
1881 bestDataSpace = hdrDataSpace;
1882 }
1883
Chia-I Wu0d711262018-05-21 15:19:35 -07001884 RenderIntent intent;
1885 switch (mDisplayColorSetting) {
1886 case DisplayColorSetting::MANAGED:
1887 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001888 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001889 break;
1890 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001891 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001892 break;
1893 default: // vendor display color setting
1894 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1895 break;
1896 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001897
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001898 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001899}
1900
Lloyd Pique074e8122018-07-26 12:57:23 -07001901void SurfaceFlinger::setUpHWComposer() {
1902 ATRACE_CALL();
1903 ALOGV("setUpHWComposer");
Lloyd Piqueb7d12302018-07-26 12:56:47 -07001904
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001905 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001906 bool dirty = !display->getDirtyRegion(mRepaintEverything).isEmpty();
1907 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
1908 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
Jesse Hallb7a05492014-08-14 15:45:06 -07001909
1910 // If nothing has changed (!dirty), don't recompose.
1911 // If something changed, but we don't currently have any visible layers,
1912 // and didn't when we last did a composition, then skip it this time.
1913 // The second rule does two things:
1914 // - When all layers are removed from a display, we'll emit one black
1915 // frame, then nothing more until we get new layers.
1916 // - When a display is created with a private layer stack, we won't
1917 // emit any black frames until a layer is added to the layer stack.
1918 bool mustRecompose = dirty && !(empty && wasEmpty);
1919
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001920 ALOGV_IF(display->isVirtual(), "Display %d: %s composition (%sdirty %sempty %swasEmpty)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001921 display->getId(), mustRecompose ? "doing" : "skipping", dirty ? "+" : "-",
1922 empty ? "+" : "-", wasEmpty ? "+" : "-");
Jesse Hallb7a05492014-08-14 15:45:06 -07001923
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001924 display->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001925
1926 if (mustRecompose) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001927 display->lastCompositionHadVisibleLayers = !empty;
Jesse Hallb7a05492014-08-14 15:45:06 -07001928 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001929 }
1930
Lloyd Pique074e8122018-07-26 12:57:23 -07001931 // build the h/w work list
1932 if (CC_UNLIKELY(mGeometryInvalid)) {
1933 mGeometryInvalid = false;
1934 for (const auto& [token, display] : mDisplays) {
1935 const auto displayId = display->getId();
1936 if (displayId >= 0) {
1937 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
1938 for (size_t i = 0; i < currentLayers.size(); i++) {
1939 const auto& layer = currentLayers[i];
1940 if (!layer->hasHwcLayer(displayId)) {
1941 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1942 layer->forceClientComposition(displayId);
1943 continue;
1944 }
1945 }
1946
1947 layer->setGeometry(display, i);
1948 if (mDebugDisableHWC || mDebugRegion) {
1949 layer->forceClientComposition(displayId);
1950 }
1951 }
1952 }
1953 }
1954 }
1955
1956 // Set the per-frame data
1957 for (const auto& [token, display] : mDisplays) {
1958 const auto displayId = display->getId();
1959 if (displayId < 0) {
1960 continue;
1961 }
1962
1963 if (mDrawingState.colorMatrixChanged) {
1964 display->setColorTransform(mDrawingState.colorMatrix);
1965 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1966 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %d: %d",
1967 displayId, result);
1968 }
1969 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1970 if (layer->isHdrY410()) {
1971 layer->forceClientComposition(displayId);
1972 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1973 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1974 !display->hasHDR10Support()) {
1975 layer->forceClientComposition(displayId);
1976 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1977 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1978 !display->hasHLGSupport()) {
1979 layer->forceClientComposition(displayId);
1980 }
1981
1982 if (layer->getForceClientComposition(displayId)) {
1983 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1984 layer->setCompositionType(displayId, HWC2::Composition::Client);
1985 continue;
1986 }
1987
1988 layer->setPerFrameData(display);
1989 }
1990
1991 if (hasWideColorDisplay) {
1992 ColorMode colorMode;
1993 Dataspace dataSpace;
1994 RenderIntent renderIntent;
1995 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1996 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1997 }
1998 }
1999
2000 mDrawingState.colorMatrixChanged = false;
2001
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002002 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002003 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002004 continue;
2005 }
2006
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002007 status_t result = display->prepareFrame(*getBE().mHwc);
2008 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002009 display->getId(), result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002010 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002011}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002012
Mathias Agopiancd60f992012-08-16 16:28:27 -07002013void SurfaceFlinger::doComposition() {
2014 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002015 ALOGV("doComposition");
2016
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002017 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
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()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002020 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002021 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002022
2023 // repaint the framebuffer (if needed)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002024 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002025
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002026 display->dirtyRegion.clear();
2027 display->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002028 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002029 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002030 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002031}
2032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002033void SurfaceFlinger::postFramebuffer()
2034{
Mathias Agopian841cde52012-03-01 15:44:37 -08002035 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002036 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002037
Mathias Agopiana44b0412011-10-16 18:46:35 -07002038 const nsecs_t now = systemTime();
2039 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002040
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002041 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002042 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002043 continue;
2044 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07002045 const auto displayId = display->getId();
2046 if (displayId >= 0) {
2047 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002048 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002049 display->onSwapBuffersCompleted();
2050 display->makeCurrent();
2051 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002052 sp<Fence> releaseFence = Fence::NO_FENCE;
2053
Chia-I Wu7b549592017-11-15 09:14:57 -08002054 // The layer buffer from the previous frame (if any) is released
2055 // by HWC only when the release fence from this frame (if any) is
2056 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002057 auto hwcLayer = layer->getHwcLayer(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002058 if (displayId >= 0) {
2059 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
2060 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002061
2062 // If the layer was client composited in the previous frame, we
2063 // need to merge with the previous client target acquire fence.
2064 // Since we do not track that, always merge with the current
2065 // client target acquire fence when it is available, even though
2066 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002067 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002068 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002069 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002070 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002071
David Sodmanb8af7922017-12-21 15:17:55 -08002072 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002073 }
Chia-I Wu83806892017-11-16 10:50:20 -08002074
2075 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002076 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002077 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002078 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002079 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002080 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002081 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002082 }
2083 }
2084
Dominik Laskowski7e045462018-05-30 13:02:02 -07002085 if (displayId >= 0) {
2086 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002087 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002088 }
2089
Mathias Agopiana44b0412011-10-16 18:46:35 -07002090 mLastSwapBufferTime = systemTime() - now;
2091 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002092
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002093 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002094 const auto display = getDefaultDisplayDeviceLocked();
2095 if (display && getHwComposer().isConnected(display->getId())) {
2096 const uint32_t flipCount = display->getPageFlipCount();
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002097 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2098 logFrameStats();
2099 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002100 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002101}
2102
Mathias Agopian87baae12012-07-31 12:38:26 -07002103void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002104{
Mathias Agopian841cde52012-03-01 15:44:37 -08002105 ATRACE_CALL();
2106
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002107 // here we keep a copy of the drawing state (that is the state that's
2108 // going to be overwritten by handleTransactionLocked()) outside of
2109 // mStateLock so that the side-effects of the State assignment
2110 // don't happen with mStateLock held (which can cause deadlocks).
2111 State drawingState(mDrawingState);
2112
Mathias Agopianca4d3602011-05-19 15:38:14 -07002113 Mutex::Autolock _l(mStateLock);
2114 const nsecs_t now = systemTime();
2115 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002116
Mathias Agopianca4d3602011-05-19 15:38:14 -07002117 // Here we're guaranteed that some transaction flags are set
2118 // so we can call handleTransactionLocked() unconditionally.
2119 // We call getTransactionFlags(), which will also clear the flags,
2120 // with mStateLock held to guarantee that mCurrentState won't change
2121 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002122
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002123 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002124 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002125 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002126
Mathias Agopianca4d3602011-05-19 15:38:14 -07002127 mLastTransactionTime = systemTime() - now;
2128 mDebugInTransaction = 0;
2129 invalidateHwcGeometry();
2130 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002131}
2132
Dominik Laskowski7e045462018-05-30 13:02:02 -07002133DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002134 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002135 // Figure out whether the event is for the primary display or an
2136 // external display by matching the Hwc display id against one for a
2137 // connected display. If we did not find a match, we then check what
2138 // displays are not already connected to determine the type. If we don't
2139 // have a connected primary display, we assume the new display is meant to
2140 // be the primary display, and then if we don't have an external display,
2141 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002142 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2143 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002144 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002145 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002146 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002147 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002148 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002149 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002150 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002151 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002152 return DisplayDevice::DISPLAY_EXTERNAL;
2153 }
2154
2155 return DisplayDevice::DISPLAY_ID_INVALID;
2156}
2157
Lloyd Piqueba04e622017-12-14 17:11:26 -08002158void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2159 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002160 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002161 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002162 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002163 continue;
2164 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002165
2166 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2167 ALOGE("External displays are not supported by the vr hardware composer.");
2168 continue;
2169 }
2170
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002171 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002172 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002173 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002174 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002175 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002176
2177 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002178 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002179 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002180 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002181 DisplayDeviceState info;
2182 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002183 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2184 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002185 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002186 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002187 mInterceptor->saveDisplayCreation(info);
2188 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002189 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002190 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002191
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002192 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002193 if (idx >= 0) {
2194 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002195 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002196 mCurrentState.displays.removeItemsAt(idx);
2197 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002198 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002199 }
2200
2201 processDisplayChangesLocked();
2202 }
2203
2204 mPendingHotplugEvents.clear();
2205}
2206
Lloyd Pique99d3da52018-01-22 17:48:03 -08002207sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002208 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002209 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002210 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002211 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002212 HdrCapabilities hdrCapabilities;
2213 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002214
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002215 if (hasWideColorDisplay && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002216 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002217 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002218 if (isWideColorMode(colorMode)) {
2219 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002220 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002221
Dominik Laskowski7e045462018-05-30 13:02:02 -07002222 std::vector<RenderIntent> renderIntents =
2223 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002224 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002225 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002226
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002227 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2228 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2229 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002230
2231 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2232 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2233
2234 /*
2235 * Create our display's surface
2236 */
2237 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2238 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002239 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002240 renderSurface->setNativeWindow(nativeWindow.get());
2241 const int displayWidth = renderSurface->queryWidth();
2242 const int displayHeight = renderSurface->queryHeight();
2243
2244 // Make sure that composition can never be stalled by a virtual display
2245 // consumer that isn't processing buffers fast enough. We have to do this
2246 // in two places:
2247 // * Here, in case the display is composed entirely by HWC.
2248 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2249 // window's swap interval in eglMakeCurrent, so they'll override the
2250 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002251 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002252 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2253 }
2254
2255 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002256 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002257
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002258 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002259 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2260 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2261 displayHeight, hasWideColorGamut, hdrCapabilities,
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002262 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002263
2264 if (maxFrameBufferAcquiredBuffers >= 3) {
2265 nativeWindowSurface->preallocateBuffers();
2266 }
2267
2268 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002269 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2270 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002271 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002272 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002273 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002274 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002275 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002276 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002277 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002278 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002279 display->setLayerStack(state.layerStack);
2280 display->setProjection(state.orientation, state.viewport, state.frame);
2281 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002282
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002283 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002284}
2285
Lloyd Pique347200f2017-12-14 17:00:15 -08002286void SurfaceFlinger::processDisplayChangesLocked() {
2287 // here we take advantage of Vector's copy-on-write semantics to
2288 // improve performance by skipping the transaction entirely when
2289 // know that the lists are identical
2290 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2291 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2292 if (!curr.isIdenticalTo(draw)) {
2293 mVisibleRegionsDirty = true;
2294 const size_t cc = curr.size();
2295 size_t dc = draw.size();
2296
2297 // find the displays that were removed
2298 // (ie: in drawing state but not in current state)
2299 // also handle displays that changed
2300 // (ie: displays that are in both lists)
2301 for (size_t i = 0; i < dc;) {
2302 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2303 if (j < 0) {
2304 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002305 // Call makeCurrent() on the primary display so we can
2306 // be sure that nothing associated with this display
2307 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002308 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2309 defaultDisplay->makeCurrent();
2310 }
2311 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2312 display->disconnect(getHwComposer());
2313 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002314 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2315 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2316 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2317 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2318 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002319 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002320 } else {
2321 // this display is in both lists. see if something changed.
2322 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002323 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002324 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2325 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2326 if (state_binder != draw_binder) {
2327 // changing the surface is like destroying and
2328 // recreating the DisplayDevice, so we just remove it
2329 // from the drawing state, so that it get re-added
2330 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002331 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2332 display->disconnect(getHwComposer());
2333 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002334 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002335 mDrawingState.displays.removeItemsAt(i);
2336 dc--;
2337 // at this point we must loop to the next item
2338 continue;
2339 }
2340
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002341 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002342 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002343 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002344 }
2345 if ((state.orientation != draw[i].orientation) ||
2346 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002347 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002348 }
2349 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002350 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002351 }
2352 }
2353 }
2354 ++i;
2355 }
2356
2357 // find displays that were added
2358 // (ie: in current state but not in drawing state)
2359 for (size_t i = 0; i < cc; i++) {
2360 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2361 const DisplayDeviceState& state(curr[i]);
2362
2363 sp<DisplaySurface> dispSurface;
2364 sp<IGraphicBufferProducer> producer;
2365 sp<IGraphicBufferProducer> bqProducer;
2366 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002367 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002368
Dominik Laskowski7e045462018-05-30 13:02:02 -07002369 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002370 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002371 // Virtual displays without a surface are dormant:
2372 // they have external state (layer stack, projection,
2373 // etc.) but no internal state (i.e. a DisplayDevice).
2374 if (state.surface != nullptr) {
2375 // Allow VR composer to use virtual displays.
2376 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2377 int width = 0;
2378 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2379 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2380 int height = 0;
2381 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2382 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2383 int intFormat = 0;
2384 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2385 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002386 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002387
Dominik Laskowski7e045462018-05-30 13:02:02 -07002388 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2389 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002390 }
2391
2392 // TODO: Plumb requested format back up to consumer
2393
2394 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002395 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002396 bqProducer, bqConsumer,
2397 state.displayName);
2398
2399 dispSurface = vds;
2400 producer = vds;
2401 }
2402 } else {
2403 ALOGE_IF(state.surface != nullptr,
2404 "adding a supported display, but rendering "
2405 "surface is provided (%p), ignoring it",
2406 state.surface.get());
2407
Dominik Laskowski7e045462018-05-30 13:02:02 -07002408 displayId = state.type;
2409 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002410 producer = bqProducer;
2411 }
2412
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002413 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002414 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002415 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002416 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002417 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002418 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002419 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2420 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2421 true);
2422 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2423 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2424 true);
2425 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002426 }
2427 }
2428 }
2429 }
2430 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002431
2432 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002433}
2434
Mathias Agopian87baae12012-07-31 12:38:26 -07002435void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002436{
Dan Stoza7dde5992015-05-22 09:51:44 -07002437 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002438 mCurrentState.traverseInZOrder([](Layer* layer) {
2439 layer->notifyAvailableFrames();
2440 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002441
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002442 /*
2443 * Traversal of the children
2444 * (perform the transaction for each of them if needed)
2445 */
2446
Mathias Agopian3559b072012-08-15 13:46:03 -07002447 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002448 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002449 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002450 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002451
2452 const uint32_t flags = layer->doTransaction(0);
2453 if (flags & Layer::eVisibleRegion)
2454 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002455 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002456 }
2457
2458 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002459 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002460 */
2461
Mathias Agopiane57f2922012-08-09 16:29:12 -07002462 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002463 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002464 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002465 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002466
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002467 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002468 // The transform hint might have changed for some layers
2469 // (either because a display has changed, or because a layer
2470 // as changed).
2471 //
2472 // Walk through all the layers in currentLayers,
2473 // and update their transform hint.
2474 //
2475 // If a layer is visible only on a single display, then that
2476 // display is used to calculate the hint, otherwise we use the
2477 // default display.
2478 //
2479 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2480 // the hint is set before we acquire a buffer from the surface texture.
2481 //
2482 // NOTE: layer transactions have taken place already, so we use their
2483 // drawing state. However, SurfaceFlinger's own transaction has not
2484 // happened yet, so we must use the current state layer list
2485 // (soon to become the drawing state list).
2486 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002487 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002488 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002489 bool first = true;
2490 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002491 // NOTE: we rely on the fact that layers are sorted by
2492 // layerStack first (so we don't have to traverse the list
2493 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002494 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002495 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002496 currentlayerStack = layerStack;
2497 // figure out if this layerstack is mirrored
2498 // (more than one display) if so, pick the default display,
2499 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002500 hintDisplay = nullptr;
2501 for (const auto& [token, display] : mDisplays) {
2502 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2503 if (hintDisplay) {
2504 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002505 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002506 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002507 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002508 }
2509 }
2510 }
2511 }
Chet Haase91d25932013-04-11 15:24:55 -07002512
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002513 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002514 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2515 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002516
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002517 // could be null when this layer is using a layerStack
2518 // that is not visible on any display. Also can occur at
2519 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002520 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002521 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002522
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002523 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002524 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002525 if (hintDisplay) {
2526 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002527 }
Robert Carr2047fae2016-11-28 14:09:09 -08002528
2529 first = false;
2530 });
Mathias Agopian84300952012-11-21 16:02:13 -08002531 }
2532
2533
Mathias Agopian3559b072012-08-15 13:46:03 -07002534 /*
2535 * Perform our own transaction if needed
2536 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002537
2538 if (mLayersAdded) {
2539 mLayersAdded = false;
2540 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002541 mVisibleRegionsDirty = true;
2542 }
2543
2544 // some layers might have been removed, so
2545 // we need to update the regions they're exposing.
2546 if (mLayersRemoved) {
2547 mLayersRemoved = false;
2548 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002549 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002550 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002551 // this layer is not visible anymore
2552 // TODO: we could traverse the tree from front to back and
2553 // compute the actual visible region
2554 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002555 Region visibleReg;
2556 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002557 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002558 }
Robert Carr2047fae2016-11-28 14:09:09 -08002559 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002560 }
2561
2562 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002563
2564 updateCursorAsync();
2565}
2566
2567void SurfaceFlinger::updateCursorAsync()
2568{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002569 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002570 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002571 continue;
2572 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002573
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002574 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2575 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002576 }
2577 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002578}
2579
2580void SurfaceFlinger::commitTransaction()
2581{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002582 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002583 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002584 for (const auto& l : mLayersPendingRemoval) {
2585 recordBufferingStats(l->getName().string(),
2586 l->getOccupancyHistory(true));
2587 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002588 }
2589 mLayersPendingRemoval.clear();
2590 }
2591
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002592 // If this transaction is part of a window animation then the next frame
2593 // we composite should be considered an animation as well.
2594 mAnimCompositionPending = mAnimTransactionPending;
2595
Mathias Agopian4fec8732012-06-29 14:12:52 -07002596 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002597 // clear the "changed" flags in current state
2598 mCurrentState.colorMatrixChanged = false;
2599
Robert Carr1f0a16a2016-10-24 16:27:39 -07002600 mDrawingState.traverseInZOrder([](Layer* layer) {
2601 layer->commitChildList();
2602 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002603 mTransactionPending = false;
2604 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002605 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002606}
2607
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002608void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2609 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002610 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002611 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002612
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002613 Region aboveOpaqueLayers;
2614 Region aboveCoveredLayers;
2615 Region dirty;
2616
Mathias Agopian87baae12012-07-31 12:38:26 -07002617 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002618
Robert Carr2047fae2016-11-28 14:09:09 -08002619 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002620 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002621 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002622
Jesse Hall01e29052013-02-19 16:13:35 -08002623 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002624 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002625 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002626 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002627
Mathias Agopianab028732010-03-16 16:41:46 -07002628 /*
2629 * opaqueRegion: area of a surface that is fully opaque.
2630 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002631 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002632
2633 /*
2634 * visibleRegion: area of a surface that is visible on screen
2635 * and not fully transparent. This is essentially the layer's
2636 * footprint minus the opaque regions above it.
2637 * Areas covered by a translucent surface are considered visible.
2638 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002639 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002640
2641 /*
2642 * coveredRegion: area of a surface that is covered by all
2643 * visible regions above it (which includes the translucent areas).
2644 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002645 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002646
Jesse Halla8026d22012-09-25 13:25:04 -07002647 /*
2648 * transparentRegion: area of a surface that is hinted to be completely
2649 * transparent. This is only used to tell when the layer has no visible
2650 * non-transparent regions and can be removed from the layer list. It
2651 * does not affect the visibleRegion of this layer or any layers
2652 * beneath it. The hint may not be correct if apps don't respect the
2653 * SurfaceView restrictions (which, sadly, some don't).
2654 */
2655 Region transparentRegion;
2656
Mathias Agopianab028732010-03-16 16:41:46 -07002657
2658 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002659 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002660 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002661 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002662 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002663 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002664 if (!visibleRegion.isEmpty()) {
2665 // Remove the transparent area from the visible region
2666 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002667 if (tr.preserveRects()) {
2668 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002669 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002670 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002671 // transformation too complex, can't do the
2672 // transparent region optimization.
2673 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002674 }
Mathias Agopianab028732010-03-16 16:41:46 -07002675 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002676
Mathias Agopianab028732010-03-16 16:41:46 -07002677 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002678 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002679 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002680 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2681 // the opaque region is the layer's footprint
2682 opaqueRegion = visibleRegion;
2683 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002684 }
2685 }
2686
Robert Carre5f4f692018-01-12 13:12:28 -08002687 if (visibleRegion.isEmpty()) {
2688 layer->clearVisibilityRegions();
2689 return;
2690 }
2691
Mathias Agopianab028732010-03-16 16:41:46 -07002692 // Clip the covered region to the visible region
2693 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2694
2695 // Update aboveCoveredLayers for next (lower) layer
2696 aboveCoveredLayers.orSelf(visibleRegion);
2697
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002698 // subtract the opaque region covered by the layers above us
2699 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002700
2701 // compute this layer's dirty region
2702 if (layer->contentDirty) {
2703 // we need to invalidate the whole region
2704 dirty = visibleRegion;
2705 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002706 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002707 layer->contentDirty = false;
2708 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002709 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002710 * the exposed region consists of two components:
2711 * 1) what's VISIBLE now and was COVERED before
2712 * 2) what's EXPOSED now less what was EXPOSED before
2713 *
2714 * note that (1) is conservative, we start with the whole
2715 * visible region but only keep what used to be covered by
2716 * something -- which mean it may have been exposed.
2717 *
2718 * (2) handles areas that were not covered by anything but got
2719 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002720 */
Mathias Agopianab028732010-03-16 16:41:46 -07002721 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002722 const Region oldVisibleRegion = layer->visibleRegion;
2723 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002724 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2725 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002726 }
2727 dirty.subtractSelf(aboveOpaqueLayers);
2728
2729 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002730 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002731
Mathias Agopianab028732010-03-16 16:41:46 -07002732 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002733 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002734
Jesse Halla8026d22012-09-25 13:25:04 -07002735 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002736 layer->setVisibleRegion(visibleRegion);
2737 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002738 layer->setVisibleNonTransparentRegion(
2739 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002740 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002741
Mathias Agopian87baae12012-07-31 12:38:26 -07002742 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002743}
2744
Chia-I Wuab0c3192017-08-01 11:29:00 -07002745void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002746 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002747 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2748 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002749 }
2750 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002751}
2752
Dan Stoza6b9454d2014-11-07 16:00:59 -08002753bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002754{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002755 ALOGV("handlePageFlip");
2756
Brian Andersond6927fb2016-07-23 23:37:30 -07002757 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002758
Mathias Agopian4fec8732012-06-29 14:12:52 -07002759 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002760 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002761 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002762
2763 // Store the set of layers that need updates. This set must not change as
2764 // buffers are being latched, as this could result in a deadlock.
2765 // Example: Two producers share the same command stream and:
2766 // 1.) Layer 0 is latched
2767 // 2.) Layer 0 gets a new frame
2768 // 2.) Layer 1 gets a new frame
2769 // 3.) Layer 1 is latched.
2770 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2771 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002772 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002773 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002774 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07002775 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002776 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002777 } else {
2778 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002779 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002780 } else {
2781 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002782 }
Robert Carr2047fae2016-11-28 14:09:09 -08002783 });
2784
Dan Stoza9e56aa02015-11-02 13:00:03 -08002785 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002786 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002787 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002788 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002789 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002790 newDataLatched = true;
2791 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002792 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002793
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002794 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002795
2796 // If we will need to wake up at some time in the future to deal with a
2797 // queued frame that shouldn't be displayed during this vsync period, wake
2798 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002799 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002800 signalLayerUpdate();
2801 }
2802
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002803 // enter boot animation on first buffer latch
2804 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2805 ALOGI("Enter boot animation");
2806 mBootStage = BootStage::BOOTANIMATION;
2807 }
2808
Dan Stoza6b9454d2014-11-07 16:00:59 -08002809 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002810 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002811}
2812
Mathias Agopianad456f92011-01-13 17:53:01 -08002813void SurfaceFlinger::invalidateHwcGeometry()
2814{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002815 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002816}
2817
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002818void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2819 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002820 // We only need to actually compose the display if:
2821 // 1) It is being handled by hardware composer, which may need this to
2822 // keep its virtual display state machine in sync, or
2823 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002824 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002825 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002826 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002827 return;
2828 }
2829
Dan Stoza9e56aa02015-11-02 13:00:03 -08002830 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002831 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002832
2833 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002834 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002835}
2836
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002837bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002838 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002839
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002840 const Region bounds(display->bounds());
2841 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002842 const auto displayId = display->getId();
2843 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002844 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002845
Chia-I Wu8e50e692018-05-04 10:12:37 -07002846 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002847 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002848
Dan Stoza9e56aa02015-11-02 13:00:03 -08002849 if (hasClientComposition) {
2850 ALOGV("hasClientComposition");
2851
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002852 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002853 if (display->hasWideColorGamut()) {
2854 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002855 }
2856 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002857 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002858 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002859
Dominik Laskowski7e045462018-05-30 13:02:02 -07002860 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002861 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2862 HWC2::Capability::SkipClientColorTransform);
2863
Chia-I Wud49d6692018-06-27 07:17:41 +08002864 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002865 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2866 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08002867 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002868 }
2869
Chia-I Wud49d6692018-06-27 07:17:41 +08002870 // The current enhanced saturation matrix is designed to enhance Display P3,
2871 // thus we only apply this matrix when the render intent is not colorimetric
2872 // and the output color space is Display P3.
2873 needsEnhancedColorMatrix =
2874 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2875 outputDataspace == Dataspace::DISPLAY_P3);
2876 if (needsEnhancedColorMatrix) {
2877 colorMatrix *= mEnhancedSaturationMatrix;
2878 }
2879
2880 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002881
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002882 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002883 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002884 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002885 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002886
2887 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002888 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2889 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2890 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002891 }
2892 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002893 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002894
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002895 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002896 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002897 // when using overlays, we assume a fully transparent framebuffer
2898 // NOTE: we could reduce how much we need to clear, for instance
2899 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002900 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002901 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002902 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002903 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002904 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002905 // we're left with the letterbox region
2906 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002907 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07002908
2909 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002910 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07002911
Mathias Agopianb9494d52012-04-18 02:28:45 -07002912 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002913 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002914 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002915 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002916 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002917 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002918
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002919 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002920 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002921 // scissor on the main display. It should never be needed
2922 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002923 const Rect& bounds = display->getBounds();
2924 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07002925 if (scissor != bounds) {
2926 // scissor doesn't match the screen's dimensions, so we
2927 // need to clear everything outside of it and enable
2928 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002929
Mathias Agopianf45c5102012-10-24 16:29:17 -07002930 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002931 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002932 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002933 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002934 }
2935 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002936 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002937
Mathias Agopian85d751c2012-08-29 16:59:24 -07002938 /*
2939 * and then, render the layers targeted at the framebuffer
2940 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002941
Dan Stoza9e56aa02015-11-02 13:00:03 -08002942 ALOGV("Rendering client layers");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002943 const Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002944 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002945 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002946 const Region clip(bounds.intersect(
2947 displayTransform.transform(layer->visibleRegion)));
2948 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002949 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002950 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002951 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002952 case HWC2::Composition::Cursor:
2953 case HWC2::Composition::Device:
2954 case HWC2::Composition::Sideband:
2955 case HWC2::Composition::SolidColor: {
2956 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002957 if (layer->getClearClientTarget(displayId) && !firstLayer &&
Rajavenu Kyatham2eae6d32018-04-10 12:34:05 +05302958 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
2959 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002960 // never clear the very first layer since we're
2961 // guaranteed the FB is already cleared
2962 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002963 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002964 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002965 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002966 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002967 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002968 break;
2969 }
2970 default:
2971 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002972 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002973 } else {
2974 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002975 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002976 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002977 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002978
Chia-I Wud49d6692018-06-27 07:17:41 +08002979 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002980 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002981 }
2982
Mathias Agopianf45c5102012-10-24 16:29:17 -07002983 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002984 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002985 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002986}
2987
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002988void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
2989 const Region& region) const {
2990 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002991 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002992 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002993}
2994
Dan Stoza7d89d062015-04-30 13:29:25 -07002995status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002996 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002997 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002998 const sp<Layer>& lbc,
2999 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003000{
Dan Stoza7d89d062015-04-30 13:29:25 -07003001 // add this layer to the current state list
3002 {
3003 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003004 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003005 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3006 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003007 return NO_MEMORY;
3008 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003009 if (parent == nullptr) {
3010 mCurrentState.layersSortedByZ.add(lbc);
3011 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003012 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003013 ALOGE("addClientLayer called with a removed parent");
3014 return NAME_NOT_FOUND;
3015 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003016 parent->addChild(lbc);
3017 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003018
Yiwei Zhang243b3782018-05-15 17:40:04 -07003019 if (gbc != nullptr) {
3020 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3021 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3022 mMaxGraphicBufferProducerListSize,
3023 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3024 mGraphicBufferProducerList.size(),
3025 mMaxGraphicBufferProducerListSize, mNumLayers);
3026 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003027 mLayersAdded = true;
3028 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003029 }
3030
Mathias Agopian96f08192010-06-02 23:28:45 -07003031 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003032 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003033
Dan Stoza7d89d062015-04-30 13:29:25 -07003034 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003035}
3036
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003037status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003038 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003039 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3040}
Robert Carr7f9b8992017-03-10 11:08:39 -08003041
chaviwca27f252018-02-06 16:46:39 -08003042status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3043 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003044 if (layer->isPendingRemoval()) {
3045 return NO_ERROR;
3046 }
3047
Robert Carr1f0a16a2016-10-24 16:27:39 -07003048 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003049 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003050 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003051 if (topLevelOnly) {
3052 return NO_ERROR;
3053 }
3054
Chia-I Wu98f1c102017-05-30 14:54:08 -07003055 sp<Layer> ancestor = p;
3056 while (ancestor->getParent() != nullptr) {
3057 ancestor = ancestor->getParent();
3058 }
3059 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3060 ALOGE("removeLayer called with a layer whose parent has been removed");
3061 return NAME_NOT_FOUND;
3062 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003063
3064 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003065 } else {
3066 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003067 }
3068
Robert Carr136e2f62017-02-08 17:54:29 -08003069 // As a matter of normal operation, the LayerCleaner will produce a second
3070 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3071 // so we will succeed in promoting it, but it's already been removed
3072 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3073 // otherwise something has gone wrong and we are leaking the layer.
3074 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003075 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3076 layer->getName().string(),
3077 (p != nullptr) ? p->getName().string() : "no-parent");
3078 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003079 } else if (index < 0) {
3080 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003081 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003082
Chia-I Wuc6657022017-08-15 11:18:17 -07003083 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003084 mLayersPendingRemoval.add(layer);
3085 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003086 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003087 setTransactionFlags(eTransactionNeeded);
3088 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003089}
3090
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003091uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003092 return android_atomic_release_load(&mTransactionFlags);
3093}
3094
Mathias Agopian3f844832013-08-07 21:24:32 -07003095uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003096 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3097}
3098
Mathias Agopian3f844832013-08-07 21:24:32 -07003099uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003100 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3101}
3102
3103uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3104 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003105 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003106 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003107 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003108 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003109 }
3110 return old;
3111}
3112
chaviwca27f252018-02-06 16:46:39 -08003113bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3114 for (const ComposerState& state : states) {
3115 // Here we need to check that the interface we're given is indeed
3116 // one of our own. A malicious client could give us a nullptr
3117 // IInterface, or one of its own or even one of our own but a
3118 // different type. All these situations would cause us to crash.
3119 if (state.client == nullptr) {
3120 return true;
3121 }
3122
3123 sp<IBinder> binder = IInterface::asBinder(state.client);
3124 if (binder == nullptr) {
3125 return true;
3126 }
3127
3128 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3129 return true;
3130 }
3131 }
3132 return false;
3133}
3134
Mathias Agopian8b33f032012-07-24 20:43:54 -07003135void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003136 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003137 const Vector<DisplayState>& displays,
3138 uint32_t flags)
3139{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003140 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003141 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003142 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003143
chaviwca27f252018-02-06 16:46:39 -08003144 if (containsAnyInvalidClientState(states)) {
3145 return;
3146 }
3147
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003148 if (flags & eAnimation) {
3149 // For window updates that are part of an animation we must wait for
3150 // previous animation "frames" to be handled.
3151 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003152 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003153 if (CC_UNLIKELY(err != NO_ERROR)) {
3154 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003155 // caller after a few seconds.
3156 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3157 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003158 mAnimTransactionPending = false;
3159 break;
3160 }
3161 }
3162 }
3163
chaviwca27f252018-02-06 16:46:39 -08003164 for (const DisplayState& display : displays) {
3165 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003166 }
3167
chaviwca27f252018-02-06 16:46:39 -08003168 for (const ComposerState& state : states) {
3169 transactionFlags |= setClientStateLocked(state);
3170 }
3171
3172 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3173 // as destroyed should only occur after setting all other states. This is to allow for a
3174 // child re-parent to happen before marking its original parent as destroyed (which would
3175 // then mark the child as destroyed).
3176 for (const ComposerState& state : states) {
3177 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003178 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003179
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003180 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3181 // anyway. This can be used as a flush mechanism for previous async transactions.
3182 // Empty animation transaction can be used to simulate back-pressure, so also force a
3183 // transaction for empty animation transactions.
3184 if (transactionFlags == 0 &&
3185 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003186 transactionFlags = eTransactionNeeded;
3187 }
3188
Mathias Agopian386aa982011-11-07 21:58:03 -08003189 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003190 if (mInterceptor->isEnabled()) {
3191 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003192 }
Irvel468051e2016-06-13 16:44:44 -07003193
Mathias Agopian386aa982011-11-07 21:58:03 -08003194 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003195 const auto start = (flags & eEarlyWakeup)
3196 ? VSyncModulator::TransactionStart::EARLY
3197 : VSyncModulator::TransactionStart::NORMAL;
3198 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003199
3200 // if this is a synchronous transaction, wait for it to take effect
3201 // before returning.
3202 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003203 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003204 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003205 if (flags & eAnimation) {
3206 mAnimTransactionPending = true;
3207 }
3208 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003209 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3210 if (CC_UNLIKELY(err != NO_ERROR)) {
3211 // just in case something goes wrong in SF, return to the
3212 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003213 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3214 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003215 break;
3216 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003217 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003218 }
3219}
3220
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003221uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3222 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3223 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003224
Mathias Agopiane57f2922012-08-09 16:29:12 -07003225 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003226 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3227
3228 const uint32_t what = s.what;
3229 if (what & DisplayState::eSurfaceChanged) {
3230 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3231 state.surface = s.surface;
3232 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003233 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003234 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003235 if (what & DisplayState::eLayerStackChanged) {
3236 if (state.layerStack != s.layerStack) {
3237 state.layerStack = s.layerStack;
3238 flags |= eDisplayTransactionNeeded;
3239 }
3240 }
3241 if (what & DisplayState::eDisplayProjectionChanged) {
3242 if (state.orientation != s.orientation) {
3243 state.orientation = s.orientation;
3244 flags |= eDisplayTransactionNeeded;
3245 }
3246 if (state.frame != s.frame) {
3247 state.frame = s.frame;
3248 flags |= eDisplayTransactionNeeded;
3249 }
3250 if (state.viewport != s.viewport) {
3251 state.viewport = s.viewport;
3252 flags |= eDisplayTransactionNeeded;
3253 }
3254 }
3255 if (what & DisplayState::eDisplaySizeChanged) {
3256 if (state.width != s.width) {
3257 state.width = s.width;
3258 flags |= eDisplayTransactionNeeded;
3259 }
3260 if (state.height != s.height) {
3261 state.height = s.height;
3262 flags |= eDisplayTransactionNeeded;
3263 }
3264 }
3265
Mathias Agopiane57f2922012-08-09 16:29:12 -07003266 return flags;
3267}
3268
Robert Carrd4ae7f32018-06-07 16:10:57 -07003269bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3270 IPCThreadState* ipc = IPCThreadState::self();
3271 const int pid = ipc->getCallingPid();
3272 const int uid = ipc->getCallingUid();
Peiyong Line70e1292018-08-09 14:06:58 -07003273
Robert Carrd4ae7f32018-06-07 16:10:57 -07003274 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Peiyong Line70e1292018-08-09 14:06:58 -07003275 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003276 return false;
3277 }
3278 return true;
3279}
3280
chaviwca27f252018-02-06 16:46:39 -08003281uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3282 const layer_state_t& s = composerState.state;
3283 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3284
Mathias Agopian13127d82013-03-05 17:47:11 -08003285 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003286 if (layer == nullptr) {
3287 return 0;
3288 }
3289
3290 if (layer->isPendingRemoval()) {
3291 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3292 return 0;
3293 }
3294
3295 uint32_t flags = 0;
3296
3297 const uint32_t what = s.what;
3298 bool geometryAppliesWithResize =
3299 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003300
3301 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3302 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003303 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003304 layer->pushPendingState();
3305 }
3306
chaviw8b3871a2017-11-01 17:41:01 -07003307 if (what & layer_state_t::ePositionChanged) {
3308 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3309 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003310 }
chaviw8b3871a2017-11-01 17:41:01 -07003311 }
3312 if (what & layer_state_t::eLayerChanged) {
3313 // NOTE: index needs to be calculated before we update the state
3314 const auto& p = layer->getParent();
3315 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003316 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003317 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003318 mCurrentState.layersSortedByZ.removeAt(idx);
3319 mCurrentState.layersSortedByZ.add(layer);
3320 // we need traversal (state changed)
3321 // AND transaction (list changed)
3322 flags |= eTransactionNeeded|eTraversalNeeded;
3323 }
chaviw8b3871a2017-11-01 17:41:01 -07003324 } else {
3325 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003326 flags |= eTransactionNeeded|eTraversalNeeded;
3327 }
3328 }
chaviw8b3871a2017-11-01 17:41:01 -07003329 }
3330 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003331 // NOTE: index needs to be calculated before we update the state
3332 const auto& p = layer->getParent();
3333 if (p == nullptr) {
3334 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3335 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3336 mCurrentState.layersSortedByZ.removeAt(idx);
3337 mCurrentState.layersSortedByZ.add(layer);
3338 // we need traversal (state changed)
3339 // AND transaction (list changed)
3340 flags |= eTransactionNeeded|eTraversalNeeded;
3341 }
3342 } else {
3343 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3344 flags |= eTransactionNeeded|eTraversalNeeded;
3345 }
chaviw8b3871a2017-11-01 17:41:01 -07003346 }
3347 }
3348 if (what & layer_state_t::eSizeChanged) {
3349 if (layer->setSize(s.w, s.h)) {
3350 flags |= eTraversalNeeded;
3351 }
3352 }
3353 if (what & layer_state_t::eAlphaChanged) {
3354 if (layer->setAlpha(s.alpha))
3355 flags |= eTraversalNeeded;
3356 }
3357 if (what & layer_state_t::eColorChanged) {
3358 if (layer->setColor(s.color))
3359 flags |= eTraversalNeeded;
3360 }
3361 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003362 // TODO: b/109894387
3363 //
3364 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3365 // rotation. To see the problem observe that if we have a square parent, and a child
3366 // of the same size, then we rotate the child 45 degrees around it's center, the child
3367 // must now be cropped to a non rectangular 8 sided region.
3368 //
3369 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3370 // private API, and the WindowManager only uses rotation in one case, which is on a top
3371 // level layer in which cropping is not an issue.
3372 //
3373 // However given that abuse of rotation matrices could lead to surfaces extending outside
3374 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3375 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3376 // transformations.
3377 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003378 flags |= eTraversalNeeded;
3379 }
3380 if (what & layer_state_t::eTransparentRegionChanged) {
3381 if (layer->setTransparentRegionHint(s.transparentRegion))
3382 flags |= eTraversalNeeded;
3383 }
3384 if (what & layer_state_t::eFlagsChanged) {
3385 if (layer->setFlags(s.flags, s.mask))
3386 flags |= eTraversalNeeded;
3387 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003388 if (what & layer_state_t::eCropChanged_legacy) {
3389 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003390 flags |= eTraversalNeeded;
3391 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003392 if (what & layer_state_t::eFinalCropChanged_legacy) {
3393 if (layer->setFinalCrop_legacy(s.finalCrop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003394 flags |= eTraversalNeeded;
3395 }
3396 if (what & layer_state_t::eLayerStackChanged) {
3397 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3398 // We only allow setting layer stacks for top level layers,
3399 // everything else inherits layer stack from its parent.
3400 if (layer->hasParent()) {
3401 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3402 layer->getName().string());
3403 } else if (idx < 0) {
3404 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3405 "that also does not appear in the top level layer list. Something"
3406 " has gone wrong.", layer->getName().string());
3407 } else if (layer->setLayerStack(s.layerStack)) {
3408 mCurrentState.layersSortedByZ.removeAt(idx);
3409 mCurrentState.layersSortedByZ.add(layer);
3410 // we need traversal (state changed)
3411 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003412 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003413 }
3414 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003415 if (what & layer_state_t::eDeferTransaction_legacy) {
3416 if (s.barrierHandle_legacy != nullptr) {
3417 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3418 } else if (s.barrierGbp_legacy != nullptr) {
3419 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003420 if (authenticateSurfaceTextureLocked(gbp)) {
3421 const auto& otherLayer =
3422 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003423 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003424 } else {
3425 ALOGE("Attempt to defer transaction to to an"
3426 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003427 }
3428 }
chaviw8b3871a2017-11-01 17:41:01 -07003429 // 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 }
3432 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003433 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003434 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003435 if (!hadParent) {
3436 mCurrentState.layersSortedByZ.remove(layer);
3437 }
chaviw8b3871a2017-11-01 17:41:01 -07003438 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003439 }
chaviw8b3871a2017-11-01 17:41:01 -07003440 }
3441 if (what & layer_state_t::eReparentChildren) {
3442 if (layer->reparentChildren(s.reparentHandle)) {
3443 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003444 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003445 }
chaviw8b3871a2017-11-01 17:41:01 -07003446 if (what & layer_state_t::eDetachChildren) {
3447 layer->detachChildren();
3448 }
3449 if (what & layer_state_t::eOverrideScalingModeChanged) {
3450 layer->setOverrideScalingMode(s.overrideScalingMode);
3451 // We don't trigger a traversal here because if no other state is
3452 // changed, we don't want this to cause any more work
3453 }
Marissa Wall61c58622018-07-18 10:12:20 -07003454 if (what & layer_state_t::eTransformChanged) {
3455 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3456 }
3457 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3458 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3459 flags |= eTraversalNeeded;
3460 }
3461 if (what & layer_state_t::eCropChanged) {
3462 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3463 }
3464 if (what & layer_state_t::eBufferChanged) {
3465 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3466 }
3467 if (what & layer_state_t::eAcquireFenceChanged) {
3468 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3469 }
3470 if (what & layer_state_t::eDataspaceChanged) {
3471 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3472 }
3473 if (what & layer_state_t::eHdrMetadataChanged) {
3474 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3475 }
3476 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3477 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3478 }
3479 if (what & layer_state_t::eApiChanged) {
3480 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3481 }
3482 if (what & layer_state_t::eSidebandStreamChanged) {
3483 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3484 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003485 return flags;
3486}
3487
chaviwca27f252018-02-06 16:46:39 -08003488void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3489 const layer_state_t& state = composerState.state;
3490 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3491
3492 sp<Layer> layer(client->getLayerUser(state.surface));
3493 if (layer == nullptr) {
3494 return;
3495 }
3496
3497 if (layer->isPendingRemoval()) {
3498 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3499 return;
3500 }
3501
3502 if (state.what & layer_state_t::eDestroySurface) {
3503 removeLayerLocked(mStateLock, layer);
3504 }
3505}
3506
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003507status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003508 const String8& name,
3509 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003510 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003511 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003512 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003513{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003514 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003515 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003516 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003517 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003518 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003519
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003520 status_t result = NO_ERROR;
3521
3522 sp<Layer> layer;
3523
Cody Northropbc755282017-03-31 12:00:08 -06003524 String8 uniqueName = getUniqueLayerName(name);
3525
Mathias Agopian3165cc22012-08-08 19:42:09 -07003526 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003527 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003528 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3529 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003530
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003531 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003532 case ISurfaceComposerClient::eFXSurfaceBufferState:
3533 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3534 break;
chaviw13fdc492017-06-27 12:40:18 -07003535 case ISurfaceComposerClient::eFXSurfaceColor:
3536 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003537 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003538 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003539 break;
3540 default:
3541 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003542 break;
3543 }
3544
Dan Stoza7d89d062015-04-30 13:29:25 -07003545 if (result != NO_ERROR) {
3546 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003547 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003548
Chia-I Wuab0c3192017-08-01 11:29:00 -07003549 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3550 // TODO b/64227542
3551 if (windowType == 441731) {
3552 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3553 layer->setPrimaryDisplayOnly();
3554 }
3555
Albert Chaulk479c60c2017-01-27 14:21:34 -05003556 layer->setInfo(windowType, ownerUid);
3557
Robert Carr1f0a16a2016-10-24 16:27:39 -07003558 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003559 if (result != NO_ERROR) {
3560 return result;
3561 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003562 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003563
3564 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003565 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003566}
3567
Cody Northropbc755282017-03-31 12:00:08 -06003568String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3569{
3570 bool matchFound = true;
3571 uint32_t dupeCounter = 0;
3572
3573 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3574 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3575
Dan Stoza436ccf32018-06-21 12:10:12 -07003576 // Grab the state lock since we're accessing mCurrentState
3577 Mutex::Autolock lock(mStateLock);
3578
Cody Northropbc755282017-03-31 12:00:08 -06003579 // Loop over layers until we're sure there is no matching name
3580 while (matchFound) {
3581 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003582 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003583 if (layer->getName() == uniqueName) {
3584 matchFound = true;
3585 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3586 }
3587 });
3588 }
3589
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003590 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3591 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003592
3593 return uniqueName;
3594}
3595
Marissa Wallfd668622018-05-10 10:21:13 -07003596status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3597 uint32_t w, uint32_t h, uint32_t flags,
3598 PixelFormat& format, sp<IBinder>* handle,
3599 sp<IGraphicBufferProducer>* gbp,
3600 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003601 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003602 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003603 case PIXEL_FORMAT_TRANSPARENT:
3604 case PIXEL_FORMAT_TRANSLUCENT:
3605 format = PIXEL_FORMAT_RGBA_8888;
3606 break;
3607 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003608 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003609 break;
3610 }
3611
Marissa Wallfd668622018-05-10 10:21:13 -07003612 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3613 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003614 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003615 *handle = layer->getHandle();
3616 *gbp = layer->getProducer();
3617 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003618 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003619
Marissa Wallfd668622018-05-10 10:21:13 -07003620 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003621 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003622}
3623
Marissa Wall61c58622018-07-18 10:12:20 -07003624status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3625 uint32_t w, uint32_t h, uint32_t flags,
3626 sp<IBinder>* handle, sp<Layer>* outLayer) {
3627 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3628 *handle = layer->getHandle();
3629 *outLayer = layer;
3630
3631 return NO_ERROR;
3632}
3633
chaviw13fdc492017-06-27 12:40:18 -07003634status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003635 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003636 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003637{
chaviw13fdc492017-06-27 12:40:18 -07003638 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003639 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003640 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003641}
3642
Mathias Agopianac9fa422013-02-11 16:40:36 -08003643status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003644{
Robert Carr9524cb32017-02-13 11:32:32 -08003645 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003646 status_t err = NO_ERROR;
3647 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003648 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003649 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003650 err = removeLayer(l);
3651 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3652 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003653 }
3654 return err;
3655}
3656
Mathias Agopian13127d82013-03-05 17:47:11 -08003657status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003658{
Mathias Agopian67106042013-03-14 19:18:13 -07003659 // called by ~LayerCleaner() when all references to the IBinder (handle)
3660 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003661 sp<Layer> l = layer.promote();
3662 if (l == nullptr) {
3663 // The layer has already been removed, carry on
3664 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003665 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003666 // If we have a parent, then we can continue to live as long as it does.
3667 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003668}
3669
Mathias Agopianb60314a2012-04-10 22:09:54 -07003670// ---------------------------------------------------------------------------
3671
Andy McFadden13a082e2012-08-24 10:16:42 -07003672void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003673 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3674 if (!displayToken) return;
3675
Jesse Hall01e29052013-02-19 16:13:35 -08003676 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003677 Vector<ComposerState> state;
3678 Vector<DisplayState> displays;
3679 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003680 d.what = DisplayState::eDisplayProjectionChanged |
3681 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003682 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003683 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003684 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003685 d.frame.makeInvalid();
3686 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003687 d.width = 0;
3688 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003689 displays.add(d);
3690 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003691
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003692 const auto display = getDisplayDevice(displayToken);
3693 if (!display) return;
3694
3695 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3696
3697 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003698 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003699 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003700
Brian Andersond0010582017-03-07 13:20:31 -08003701 // Use phase of 0 since phase is not known.
3702 // Use latency of 0, which will snap to the ideal latency.
3703 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003704}
3705
3706void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003707 // Async since we may be called from the main thread.
3708 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003709}
3710
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003711void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3712 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003713 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003714 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003715
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003716 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003717 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003718 return;
3719 }
3720
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003721 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003722 ALOGW("Trying to set power mode for virtual display");
3723 return;
3724 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003725
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003726 display->setPowerMode(mode);
3727
Lloyd Pique4dccc412018-01-22 17:21:36 -08003728 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003729 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003730 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003731 if (idx < 0) {
3732 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3733 return;
3734 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003735 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003736 }
3737
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003738 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003739 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003740 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003741 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003742 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003743 // FIXME: eventthread only knows about the main display right now
3744 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003745 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003746 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003747
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003748 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003749 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003750 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003751
3752 struct sched_param param = {0};
3753 param.sched_priority = 1;
3754 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3755 ALOGW("Couldn't set SCHED_FIFO on display on");
3756 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003757 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003758 // Turn off the display
3759 struct sched_param param = {0};
3760 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3761 ALOGW("Couldn't set SCHED_OTHER on display off");
3762 }
3763
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003764 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003765 disableHardwareVsync(true); // also cancels any in-progress resync
3766
Mathias Agopiancde87a32012-09-13 14:09:01 -07003767 // FIXME: eventthread only knows about the main display right now
3768 mEventThread->onScreenReleased();
3769 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003770
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003771 getHwComposer().setPowerMode(type, mode);
3772 mVisibleRegionsDirty = true;
3773 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003774 } else if (mode == HWC_POWER_MODE_DOZE ||
3775 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003776 // Update display while dozing
3777 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003778 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003779 // FIXME: eventthread only knows about the main display right now
3780 mEventThread->onScreenAcquired();
3781 resyncToHardwareVsync(true);
3782 }
3783 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3784 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003785 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003786 disableHardwareVsync(true); // also cancels any in-progress resync
3787 // FIXME: eventthread only knows about the main display right now
3788 mEventThread->onScreenReleased();
3789 }
3790 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003791 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003792 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003793 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003794 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003795
3796 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003797}
3798
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003799void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003800 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003801 const auto display = getDisplayDevice(displayToken);
3802 if (!display) {
3803 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3804 displayToken.get());
3805 } else if (display->isVirtual()) {
3806 ALOGW("Attempt to set power mode %d for virtual display", mode);
3807 } else {
3808 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003809 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003810 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003811}
3812
3813// ---------------------------------------------------------------------------
3814
Lloyd Pique755e3192018-01-31 16:46:15 -08003815status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3816 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003817 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003818
Mathias Agopianbd115332013-04-18 16:41:04 -07003819 IPCThreadState* ipc = IPCThreadState::self();
3820 const int pid = ipc->getCallingPid();
3821 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003822
Mathias Agopianbd115332013-04-18 16:41:04 -07003823 if ((uid != AID_SHELL) &&
3824 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003825 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003826 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003827 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003828 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003829 // (this would indicate SF is stuck, but we want to be able to
3830 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003831 status_t err = mStateLock.timedLock(s2ns(1));
3832 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003833 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003834 result.appendFormat(
3835 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3836 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003837 }
3838
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003839 bool dumpAll = true;
3840 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003841 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003842
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003843 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003844 if ((index < numArgs) &&
3845 (args[index] == String16("--list"))) {
3846 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003847 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003848 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003849 }
3850
3851 if ((index < numArgs) &&
3852 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003853 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003854 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003855 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003856 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003857
3858 if ((index < numArgs) &&
3859 (args[index] == String16("--latency-clear"))) {
3860 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003861 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003862 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003863 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003864
3865 if ((index < numArgs) &&
3866 (args[index] == String16("--dispsync"))) {
3867 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07003868 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07003869 dumpAll = false;
3870 }
Dan Stozab90cf072015-03-05 11:05:59 -08003871
3872 if ((index < numArgs) &&
3873 (args[index] == String16("--static-screen"))) {
3874 index++;
3875 dumpStaticScreenStats(result);
3876 dumpAll = false;
3877 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003878
3879 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003880 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003881 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003882 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003883 dumpAll = false;
3884 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003885
3886 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3887 index++;
3888 dumpWideColorInfo(result);
3889 dumpAll = false;
3890 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003891
3892 if ((index < numArgs) &&
3893 (args[index] == String16("--enable-layer-stats"))) {
3894 index++;
3895 mLayerStats.enable();
3896 dumpAll = false;
3897 }
3898
3899 if ((index < numArgs) &&
3900 (args[index] == String16("--disable-layer-stats"))) {
3901 index++;
3902 mLayerStats.disable();
3903 dumpAll = false;
3904 }
3905
3906 if ((index < numArgs) &&
3907 (args[index] == String16("--clear-layer-stats"))) {
3908 index++;
3909 mLayerStats.clear();
3910 dumpAll = false;
3911 }
3912
3913 if ((index < numArgs) &&
3914 (args[index] == String16("--dump-layer-stats"))) {
3915 index++;
3916 mLayerStats.dump(result);
3917 dumpAll = false;
3918 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003919
3920 if ((index < numArgs) &&
3921 (args[index] == String16("--display-identification"))) {
3922 index++;
3923 dumpDisplayIdentificationData(result);
3924 dumpAll = false;
3925 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003926
3927 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3928 index++;
3929 mTimeStats.parseArgs(asProto, args, index, result);
3930 dumpAll = false;
3931 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003932 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003933
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003934 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003935 if (asProto) {
3936 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3937 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3938 } else {
3939 dumpAllLocked(args, index, result);
3940 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003941 }
3942
Mathias Agopian9795c422009-08-26 16:36:26 -07003943 if (locked) {
3944 mStateLock.unlock();
3945 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003946 }
3947 write(fd, result.string(), result.size());
3948 return NO_ERROR;
3949}
3950
Dan Stozac7014012014-02-14 15:03:43 -08003951void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3952 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003953{
Robert Carr2047fae2016-11-28 14:09:09 -08003954 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003955 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003956 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003957}
3958
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003959void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003960 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003961{
3962 String8 name;
3963 if (index < args.size()) {
3964 name = String8(args[index]);
3965 index++;
3966 }
3967
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003968 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
3969 getHwComposer().isConnected(displayId)) {
3970 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
3971 const nsecs_t period = activeConfig->getVsyncPeriod();
3972 result.appendFormat("%" PRId64 "\n", period);
3973 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003974
3975 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003976 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003977 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003978 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003979 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003980 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003981 }
Robert Carr2047fae2016-11-28 14:09:09 -08003982 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003983 }
3984}
3985
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003986void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003987 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003988{
3989 String8 name;
3990 if (index < args.size()) {
3991 name = String8(args[index]);
3992 index++;
3993 }
3994
Robert Carr2047fae2016-11-28 14:09:09 -08003995 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003996 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003997 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003998 }
Robert Carr2047fae2016-11-28 14:09:09 -08003999 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004000
Svetoslavd85084b2014-03-20 10:28:31 -07004001 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004002}
4003
Jamie Gennis6547ff42013-07-16 20:12:42 -07004004// This should only be called from the main thread. Otherwise it would need
4005// the lock and should use mCurrentState rather than mDrawingState.
4006void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004007 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004008 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004009 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004010
4011 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4012}
4013
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004014void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004015{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004016 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004017
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004018 if (isLayerTripleBufferingDisabled())
4019 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004020
4021 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004022 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004023 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004024 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004025 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4026 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004027 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004028}
4029
Dan Stozab90cf072015-03-05 11:05:59 -08004030void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4031{
4032 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004033 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4034 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004035 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004036 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004037 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4038 b + 1, bucketTimeSec, percent);
4039 }
David Sodman4a36e932017-11-07 14:29:47 -08004040 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004041 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004042 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004043 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004044 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004045}
4046
Dan Stozae77c7662016-05-13 11:37:28 -07004047void SurfaceFlinger::recordBufferingStats(const char* layerName,
4048 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004049 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4050 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004051 for (const auto& segment : history) {
4052 if (!segment.usedThirdBuffer) {
4053 stats.twoBufferTime += segment.totalTime;
4054 }
4055 if (segment.occupancyAverage < 1.0f) {
4056 stats.doubleBufferedTime += segment.totalTime;
4057 } else if (segment.occupancyAverage < 2.0f) {
4058 stats.tripleBufferedTime += segment.totalTime;
4059 }
4060 ++stats.numSegments;
4061 stats.totalTime += segment.totalTime;
4062 }
4063}
4064
Brian Andersond6927fb2016-07-23 23:37:30 -07004065void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4066 result.appendFormat("Layer frame timestamps:\n");
4067
4068 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4069 const size_t count = currentLayers.size();
4070 for (size_t i=0 ; i<count ; i++) {
4071 currentLayers[i]->dumpFrameEvents(result);
4072 }
4073}
4074
Dan Stozae77c7662016-05-13 11:37:28 -07004075void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4076 result.append("Buffering stats:\n");
4077 result.append(" [Layer name] <Active time> <Two buffer> "
4078 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004079 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004080 typedef std::tuple<std::string, float, float, float> BufferTuple;
4081 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004082 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004083 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004084 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004085 if (stats.numSegments == 0) {
4086 continue;
4087 }
4088 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4089 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4090 stats.totalTime;
4091 float doubleBufferRatio = static_cast<float>(
4092 stats.doubleBufferedTime) / stats.totalTime;
4093 float tripleBufferRatio = static_cast<float>(
4094 stats.tripleBufferedTime) / stats.totalTime;
4095 sorted.insert({activeTime, {name, twoBufferRatio,
4096 doubleBufferRatio, tripleBufferRatio}});
4097 }
4098 for (const auto& sortedPair : sorted) {
4099 float activeTime = sortedPair.first;
4100 const BufferTuple& values = sortedPair.second;
4101 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4102 std::get<0>(values).c_str(), activeTime,
4103 std::get<1>(values), std::get<2>(values),
4104 std::get<3>(values));
4105 }
4106 result.append("\n");
4107}
4108
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004109void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004110 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004111 const int32_t displayId = display->getId();
4112 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4113 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004114 continue;
4115 }
4116
Dominik Laskowski7e045462018-05-30 13:02:02 -07004117 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004118 uint8_t port;
4119 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004120 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004121 result.append("no identification data\n");
4122 continue;
4123 }
4124
4125 if (!isEdid(data)) {
4126 result.append("unknown identification data: ");
4127 for (uint8_t byte : data) {
4128 result.appendFormat("%x ", byte);
4129 }
4130 result.append("\n");
4131 continue;
4132 }
4133
4134 const auto edid = parseEdid(data);
4135 if (!edid) {
4136 result.append("invalid EDID: ");
4137 for (uint8_t byte : data) {
4138 result.appendFormat("%x ", byte);
4139 }
4140 result.append("\n");
4141 continue;
4142 }
4143
4144 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4145 result.append(edid->displayName.data(), edid->displayName.length());
4146 result.append("\"\n");
4147 }
4148 result.append("\n");
4149}
4150
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004151void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4152 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004153 result.appendFormat("DisplayColorSetting: %s\n",
4154 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004155
4156 // TODO: print out if wide-color mode is active or not
4157
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004158 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004159 const int32_t displayId = display->getId();
4160 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004161 continue;
4162 }
4163
Dominik Laskowski7e045462018-05-30 13:02:02 -07004164 result.appendFormat("Display %d color modes:\n", displayId);
4165 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004166 for (auto&& mode : modes) {
4167 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4168 }
4169
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004170 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004171 result.appendFormat(" Current color mode: %s (%d)\n",
4172 decodeColorMode(currentMode).c_str(), currentMode);
4173 }
4174 result.append("\n");
4175}
4176
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004177LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004178 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004179 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4180 const State& state = useDrawing ? mDrawingState : mCurrentState;
4181 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004182 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004183 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004184 });
4185
4186 return layersProto;
4187}
4188
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004189LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004190 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004191
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004192 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004193 resolution->set_w(display.getWidth());
4194 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004195
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004196 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4197 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4198 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004199
Dominik Laskowski7e045462018-05-30 13:02:02 -07004200 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004201 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004202 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004203 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004204 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004205 }
4206 });
4207
4208 return layersProto;
4209}
4210
Mathias Agopian74d211a2013-04-22 16:55:35 +02004211void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4212 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004213{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004214 bool colorize = false;
4215 if (index < args.size()
4216 && (args[index] == String16("--color"))) {
4217 colorize = true;
4218 index++;
4219 }
4220
4221 Colorizer colorizer(colorize);
4222
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004223 // figure out if we're stuck somewhere
4224 const nsecs_t now = systemTime();
4225 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4226 const nsecs_t inTransaction(mDebugInTransaction);
4227 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4228 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4229
4230 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004231 * Dump library configuration.
4232 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004233
4234 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004235 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004236 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004237 appendSfConfigString(result);
4238 appendUiConfigString(result);
4239 appendGuiConfigString(result);
4240 result.append("\n");
4241
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004242 result.append("\nDisplay identification data:\n");
4243 dumpDisplayIdentificationData(result);
4244
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004245 result.append("\nWide-Color information:\n");
4246 dumpWideColorInfo(result);
4247
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004248 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004249 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004250 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004251 result.append(SyncFeatures::getInstance().toString());
4252 result.append("\n");
4253
Andy McFadden41d67d72014-04-25 16:58:34 -07004254 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004255 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004256 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004257
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004258 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4259 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004260 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4261 getHwComposer().isConnected(displayId)) {
4262 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004263 result.appendFormat("Display %d: "
4264 "app phase %" PRId64 " ns, "
4265 "sf phase %" PRId64 " ns, "
4266 "early app phase %" PRId64 " ns, "
4267 "early sf phase %" PRId64 " ns, "
4268 "early app gl phase %" PRId64 " ns, "
4269 "early sf gl phase %" PRId64 " ns, "
4270 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4271 displayId,
4272 vsyncPhaseOffsetNs,
4273 sfVsyncPhaseOffsetNs,
4274 appEarlyOffset,
4275 sfEarlyOffset,
4276 appEarlyGlOffset,
4277 sfEarlyOffset,
4278 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004279 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004280 result.append("\n");
4281
Dan Stozab90cf072015-03-05 11:05:59 -08004282 // Dump static screen stats
4283 result.append("\n");
4284 dumpStaticScreenStats(result);
4285 result.append("\n");
4286
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004287 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4288
Dan Stozae77c7662016-05-13 11:37:28 -07004289 dumpBufferingStats(result);
4290
Andy McFadden4803b742012-09-24 19:07:20 -07004291 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004292 * Dump the visible layer list
4293 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004294 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004295 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004296 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4297 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004298 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004299
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004300 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004301 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004302 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004303 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004304
4305 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004306 * Dump Display state
4307 */
4308
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004309 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004310 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004311 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004312 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004313 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004314 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004315 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004316
4317 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004318 * Dump SurfaceFlinger global state
4319 */
4320
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004321 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004322 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004323 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004324
Mathias Agopian888c8222012-08-04 21:10:38 -07004325 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004326 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004327
David Sodmanbc815282017-11-05 18:57:52 -08004328 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004329
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004330 if (display) {
4331 display->undefinedRegion.dump(result, "undefinedRegion");
4332 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4333 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004334 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004335 result.appendFormat(" last eglSwapBuffers() time: %f us\n"
4336 " last transaction time : %f us\n"
4337 " transaction-flags : %08x\n"
4338 " gpu_to_cpu_unsupported : %d\n",
4339 mLastSwapBufferTime / 1000.0, mLastTransactionTime / 1000.0,
4340 mTransactionFlags, !mGpuToCpuSupported);
4341
4342 if (display) {
4343 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4344 result.appendFormat(" refresh-rate : %f fps\n"
4345 " x-dpi : %f\n"
4346 " y-dpi : %f\n",
4347 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4348 activeConfig->getDpiY());
4349 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004350
Mathias Agopian74d211a2013-04-22 16:55:35 +02004351 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004352 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004353
Mathias Agopian74d211a2013-04-22 16:55:35 +02004354 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004355 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004356
4357 /*
4358 * VSYNC state
4359 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004360 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004361 result.append("\n");
4362
4363 /*
4364 * HWC layer minidump
4365 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004366 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004367 const int32_t displayId = display->getId();
4368 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004369 continue;
4370 }
4371
Dominik Laskowski7e045462018-05-30 13:02:02 -07004372 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004373 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004374 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004375 result.append("\n");
4376 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004377
4378 /*
4379 * Dump HWComposer state
4380 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004381 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004382 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004383 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004384 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004385 result.appendFormat(" h/w composer %s\n",
4386 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004387 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004388
4389 /*
4390 * Dump gralloc state
4391 */
4392 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4393 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004394
4395 /*
4396 * Dump VrFlinger state if in use.
4397 */
4398 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4399 result.append("VrFlinger state:\n");
4400 result.append(mVrFlinger->Dump().c_str());
4401 result.append("\n");
4402 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004403}
4404
Dominik Laskowski7e045462018-05-30 13:02:02 -07004405const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004406 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004407 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004408 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004409 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004410 }
4411 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004412
4413 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4414 static const Vector<sp<Layer>> empty;
4415 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004416}
4417
Keun young Park63f165f2012-08-31 10:53:36 -07004418bool SurfaceFlinger::startDdmConnection()
4419{
4420 void* libddmconnection_dso =
4421 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4422 if (!libddmconnection_dso) {
4423 return false;
4424 }
4425 void (*DdmConnection_start)(const char* name);
4426 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004427 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004428 if (!DdmConnection_start) {
4429 dlclose(libddmconnection_dso);
4430 return false;
4431 }
4432 (*DdmConnection_start)(getServiceName());
4433 return true;
4434}
4435
Chia-I Wu28f320b2018-05-03 11:02:56 -07004436void SurfaceFlinger::updateColorMatrixLocked() {
4437 mat4 colorMatrix;
4438 if (mGlobalSaturationFactor != 1.0f) {
4439 // Rec.709 luma coefficients
4440 float3 luminance{0.213f, 0.715f, 0.072f};
4441 luminance *= 1.0f - mGlobalSaturationFactor;
4442 mat4 saturationMatrix = mat4(
4443 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4444 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4445 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4446 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4447 );
4448 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4449 } else {
4450 colorMatrix = mClientColorMatrix * mDaltonizer();
4451 }
4452
4453 if (mCurrentState.colorMatrix != colorMatrix) {
4454 mCurrentState.colorMatrix = colorMatrix;
4455 mCurrentState.colorMatrixChanged = true;
4456 setTransactionFlags(eTransactionNeeded);
4457 }
4458}
4459
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004460status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Peiyong Line70e1292018-08-09 14:06:58 -07004461 switch (code) {
Ana Krulece2437712018-07-19 17:01:45 -07004462 case CREATE_CONNECTION:
4463 case CREATE_DISPLAY:
Peiyong Line70e1292018-08-09 14:06:58 -07004464 case BOOT_FINISHED:
4465 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulece2437712018-07-19 17:01:45 -07004466 case GET_ANIMATION_FRAME_STATS:
Peiyong Line70e1292018-08-09 14:06:58 -07004467 case SET_POWER_MODE:
Ana Krulece2437712018-07-19 17:01:45 -07004468 case GET_HDR_CAPABILITIES:
Peiyong Line70e1292018-08-09 14:06:58 -07004469 case ENABLE_VSYNC_INJECTIONS:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004470 case INJECT_VSYNC:
Peiyong Line70e1292018-08-09 14:06:58 -07004471 {
4472 // codes that require permission check
Robert Carrd4ae7f32018-06-07 16:10:57 -07004473 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4474 IPCThreadState* ipc = IPCThreadState::self();
4475 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4476 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004477 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004478 }
Peiyong Line70e1292018-08-09 14:06:58 -07004479 break;
4480 }
4481 /*
4482 * Calling setTransactionState is safe, because you need to have been
4483 * granted a reference to Client* and Handle* to do anything with it.
4484 *
4485 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4486 */
4487 case SET_TRANSACTION_STATE:
4488 case CREATE_SCOPED_CONNECTION:
4489 {
Robert Carr1db73f62016-12-21 12:58:51 -08004490 return OK;
4491 }
Peiyong Line70e1292018-08-09 14:06:58 -07004492 case CAPTURE_SCREEN:
4493 {
4494 // codes that require permission check
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004495 IPCThreadState* ipc = IPCThreadState::self();
4496 const int pid = ipc->getCallingPid();
4497 const int uid = ipc->getCallingUid();
Peiyong Line70e1292018-08-09 14:06:58 -07004498 if ((uid != AID_GRAPHICS) &&
4499 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4500 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004501 return PERMISSION_DENIED;
4502 }
Peiyong Line70e1292018-08-09 14:06:58 -07004503 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004504 }
Peiyong Line70e1292018-08-09 14:06:58 -07004505 case CAPTURE_LAYERS: {
chaviwa76b2712017-09-20 12:02:26 -07004506 IPCThreadState* ipc = IPCThreadState::self();
4507 const int pid = ipc->getCallingPid();
4508 const int uid = ipc->getCallingUid();
4509 if ((uid != AID_GRAPHICS) &&
4510 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4511 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4512 return PERMISSION_DENIED;
4513 }
Peiyong Line70e1292018-08-09 14:06:58 -07004514 break;
chaviwa76b2712017-09-20 12:02:26 -07004515 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004516 }
Peiyong Line70e1292018-08-09 14:06:58 -07004517 return OK;
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004518}
4519
Peiyong Line70e1292018-08-09 14:06:58 -07004520status_t SurfaceFlinger::onTransact(
4521 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4522{
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004523 status_t credentialCheck = CheckTransactCodeCredentials(code);
4524 if (credentialCheck != OK) {
4525 return credentialCheck;
4526 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004527
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004528 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4529 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004530 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004531 IPCThreadState* ipc = IPCThreadState::self();
4532 const int uid = ipc->getCallingUid();
4533 if (CC_UNLIKELY(uid != AID_SYSTEM
4534 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004535 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004536 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004537 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004538 return PERMISSION_DENIED;
4539 }
4540 int n;
4541 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004542 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004543 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004544 return NO_ERROR;
4545 case 1002: // SHOW_UPDATES
4546 n = data.readInt32();
4547 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004548 invalidateHwcGeometry();
4549 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004550 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004551 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004552 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004553 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004554 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004555 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004556 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004557 setTransactionFlags(
4558 eTransactionNeeded|
4559 eDisplayTransactionNeeded|
4560 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004561 return NO_ERROR;
4562 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004563 case 1006:{ // send empty update
4564 signalRefresh();
4565 return NO_ERROR;
4566 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004567 case 1008: // toggle use of hw composer
4568 n = data.readInt32();
4569 mDebugDisableHWC = n ? 1 : 0;
4570 invalidateHwcGeometry();
4571 repaintEverything();
4572 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004573 case 1009: // toggle use of transform hint
4574 n = data.readInt32();
4575 mDebugDisableTransformHint = n ? 1 : 0;
4576 invalidateHwcGeometry();
4577 repaintEverything();
4578 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004579 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004580 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004581 reply->writeInt32(0);
4582 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004583 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004584 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004585 return NO_ERROR;
4586 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004587 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004588 if (!display) {
4589 return NAME_NOT_FOUND;
4590 }
4591
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004592 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004593 return NO_ERROR;
4594 }
4595 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004596 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004597 // daltonize
4598 n = data.readInt32();
4599 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004600 case 1:
4601 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4602 break;
4603 case 2:
4604 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4605 break;
4606 case 3:
4607 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4608 break;
4609 default:
4610 mDaltonizer.setType(ColorBlindnessType::None);
4611 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004612 }
4613 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004614 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004615 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004616 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004617 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004618
4619 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004620 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004621 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004622 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004623 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004624 // apply a color matrix
4625 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004626 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004627 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004628 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004629 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004630 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004631 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004632 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004633 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004634 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004635 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004636
4637 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4638 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004639 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004640 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4641 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4642 }
4643
Chia-I Wu28f320b2018-05-03 11:02:56 -07004644 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004645 return NO_ERROR;
4646 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004647 // This is an experimental interface
4648 // Needs to be shifted to proper binder interface when we productize
4649 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004650 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07004651 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004652 return NO_ERROR;
4653 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004654 case 1017: {
4655 n = data.readInt32();
4656 mForceFullDamage = static_cast<bool>(n);
4657 return NO_ERROR;
4658 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004659 case 1018: { // Modify Choreographer's phase offset
4660 n = data.readInt32();
4661 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4662 return NO_ERROR;
4663 }
4664 case 1019: { // Modify SurfaceFlinger's phase offset
4665 n = data.readInt32();
4666 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4667 return NO_ERROR;
4668 }
Irvel468051e2016-06-13 16:44:44 -07004669 case 1020: { // Layer updates interceptor
4670 n = data.readInt32();
4671 if (n) {
4672 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004673 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004674 }
4675 else{
4676 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004677 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004678 }
4679 return NO_ERROR;
4680 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004681 case 1021: { // Disable HWC virtual displays
4682 n = data.readInt32();
4683 mUseHwcVirtualDisplays = !n;
4684 return NO_ERROR;
4685 }
Romain Guy0147a172017-06-01 13:53:56 -07004686 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004687 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004688 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004689
Chia-I Wu28f320b2018-05-03 11:02:56 -07004690 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004691 return NO_ERROR;
4692 }
Romain Guy54f154a2017-10-24 21:40:32 +01004693 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004694 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004695 invalidateHwcGeometry();
4696 repaintEverything();
4697 return NO_ERROR;
4698 }
4699 case 1024: { // Is wide color gamut rendering/color management supported?
4700 reply->writeBool(hasWideColorDisplay);
4701 return NO_ERROR;
4702 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004703 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004704 n = data.readInt32();
4705 if (n) {
4706 ALOGV("LayerTracing enabled");
4707 mTracing.enable();
4708 doTracing("tracing.enable");
4709 reply->writeInt32(NO_ERROR);
4710 } else {
4711 ALOGV("LayerTracing disabled");
4712 status_t err = mTracing.disable();
4713 reply->writeInt32(err);
4714 }
4715 return NO_ERROR;
4716 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004717 case 1026: { // Get layer tracing status
4718 reply->writeBool(mTracing.isEnabled());
4719 return NO_ERROR;
4720 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004721 // Is a DisplayColorSetting supported?
4722 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004723 const auto display = getDefaultDisplayDevice();
4724 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004725 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004726 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004727
4728 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4729 switch (setting) {
4730 case DisplayColorSetting::MANAGED:
4731 reply->writeBool(hasWideColorDisplay);
4732 break;
4733 case DisplayColorSetting::UNMANAGED:
4734 reply->writeBool(true);
4735 break;
4736 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004737 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004738 break;
4739 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004740 reply->writeBool(
4741 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004742 break;
4743 }
4744 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004745 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004746 // Is VrFlinger active?
4747 case 1028: {
4748 Mutex::Autolock _l(mStateLock);
4749 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4750 return NO_ERROR;
4751 }
David Sodman6d46c1e2018-07-13 12:59:48 -07004752 case 1029: {
4753 // Code 1029 is an experimental feature that allows applications to
4754 // simulate a high frequency panel by setting a multiplier and divisor
4755 // on the VSYNC-sf clock. If either the multiplier or divisor are
4756 // 0, then the code will set both to 1 to return the VSYNC-sf clock
4757 // to it's normal frequency.
4758 int multiplier = data.readInt32();
4759 int divisor = data.readInt32();
4760
4761 if ((multiplier == 0) || (divisor == 0)) {
4762 multiplier = 1;
4763 divisor = 1;
4764 }
4765
4766 if ((multiplier == 1) && (divisor == 1)) {
4767 enableHardwareVsync();
4768 } else {
4769 disableHardwareVsync(true);
4770 }
4771 getBE().mHwc->getActiveConfig(DisplayDevice::DISPLAY_PRIMARY)
4772 ->scalePanelFrequency(multiplier, divisor);
4773 mPrimaryDispSync->scalePeriod(multiplier, divisor);
4774
4775 ATRACE_INT("PeriodMultiplier", multiplier);
4776 ATRACE_INT("PeriodDivisor", divisor);
4777 return NO_ERROR;
4778 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004779 }
4780 }
4781 return err;
4782}
4783
Steven Thomas6d8110b2017-08-31 18:24:21 -07004784void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004785 android_atomic_or(1, &mRepaintEverything);
4786 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004787}
4788
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004789// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4790class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004791public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004792 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4793 ~WindowDisconnector() {
4794 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004795 }
4796
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004797private:
4798 ANativeWindow* mWindow;
4799 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004800};
4801
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004802status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4803 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4804 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4805 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004806 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004807 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004808
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004809 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004810
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004811 const auto display = getDisplayDeviceLocked(displayToken);
4812 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004813
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004814 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004815
4816 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004817 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004818 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004819}
4820
4821status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004822 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004823 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004824 ATRACE_CALL();
4825
4826 class LayerRenderArea : public RenderArea {
4827 public:
Robert Carr578038f2018-03-09 12:25:24 -08004828 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4829 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004830 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004831 mLayer(layer),
4832 mCrop(crop),
4833 mFlinger(flinger),
4834 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004835 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004836 Rect getBounds() const override {
4837 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07004838 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07004839 }
Marissa Wall61c58622018-07-18 10:12:20 -07004840 int getHeight() const override {
4841 return mLayer->getActiveHeight(mLayer->getDrawingState());
4842 }
4843 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07004844 bool isSecure() const override { return false; }
4845 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004846 Rect getSourceCrop() const override {
4847 if (mCrop.isEmpty()) {
4848 return getBounds();
4849 } else {
4850 return mCrop;
4851 }
4852 }
Robert Carr578038f2018-03-09 12:25:24 -08004853 class ReparentForDrawing {
4854 public:
4855 const sp<Layer>& oldParent;
4856 const sp<Layer>& newParent;
4857
4858 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4859 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004860 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004861 }
Robert Carr15eae092018-03-23 13:43:53 -07004862 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004863 };
4864
4865 void render(std::function<void()> drawLayers) override {
4866 if (!mChildrenOnly) {
4867 mTransform = mLayer->getTransform().inverse();
4868 drawLayers();
4869 } else {
4870 Rect bounds = getBounds();
4871 screenshotParentLayer =
4872 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4873 bounds.getWidth(), bounds.getHeight(), 0);
4874
4875 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4876 drawLayers();
4877 }
4878 }
chaviwa76b2712017-09-20 12:02:26 -07004879
chaviwa76b2712017-09-20 12:02:26 -07004880 private:
chaviw7206d492017-11-10 16:16:12 -08004881 const sp<Layer> mLayer;
4882 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004883
4884 // In the "childrenOnly" case we reparent the children to a screenshot
4885 // layer which has no properties set and which does not draw.
4886 sp<ContainerLayer> screenshotParentLayer;
4887 Transform mTransform;
4888
4889 SurfaceFlinger* mFlinger;
4890 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004891 };
4892
4893 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4894 auto parent = layerHandle->owner.promote();
4895
chaviw7206d492017-11-10 16:16:12 -08004896 if (parent == nullptr || parent->isPendingRemoval()) {
4897 ALOGE("captureLayers called with a removed parent");
4898 return NAME_NOT_FOUND;
4899 }
4900
Robert Carr578038f2018-03-09 12:25:24 -08004901 const int uid = IPCThreadState::self()->getCallingUid();
4902 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4903 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4904 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4905 return PERMISSION_DENIED;
4906 }
4907
chaviw7206d492017-11-10 16:16:12 -08004908 Rect crop(sourceCrop);
4909 if (sourceCrop.width() <= 0) {
4910 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07004911 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08004912 }
4913
4914 if (sourceCrop.height() <= 0) {
4915 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07004916 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08004917 }
4918
4919 int32_t reqWidth = crop.width() * frameScale;
4920 int32_t reqHeight = crop.height() * frameScale;
4921
Robert Carr578038f2018-03-09 12:25:24 -08004922 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004923
Robert Carr578038f2018-03-09 12:25:24 -08004924 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004925 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4926 if (!layer->isVisible()) {
4927 return;
Robert Carr578038f2018-03-09 12:25:24 -08004928 } else if (childrenOnly && layer == parent.get()) {
4929 return;
chaviwa76b2712017-09-20 12:02:26 -07004930 }
4931 visitor(layer);
4932 });
4933 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004934 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004935}
4936
4937status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4938 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004939 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004940 bool useIdentityTransform) {
4941 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004942
Iris Chang7501ed62018-04-30 14:45:42 +08004943 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004944
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004945 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4946 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4947 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4948 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004949
4950 // This mutex protects syncFd and captureResult for communication of the return values from the
4951 // main thread back to this Binder thread
4952 std::mutex captureMutex;
4953 std::condition_variable captureCondition;
4954 std::unique_lock<std::mutex> captureLock(captureMutex);
4955 int syncFd = -1;
4956 std::optional<status_t> captureResult;
4957
Robert Carr03480e22018-01-04 16:02:06 -08004958 const int uid = IPCThreadState::self()->getCallingUid();
4959 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4960
Dominik Laskowski8c001672018-05-30 16:52:06 -07004961 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004962 // If there is a refresh pending, bug out early and tell the binder thread to try again
4963 // after the refresh.
4964 if (mRefreshPending) {
4965 ATRACE_NAME("Skipping screenshot for now");
4966 std::unique_lock<std::mutex> captureLock(captureMutex);
4967 captureResult = std::make_optional<status_t>(EAGAIN);
4968 captureCondition.notify_one();
4969 return;
4970 }
4971
4972 status_t result = NO_ERROR;
4973 int fd = -1;
4974 {
4975 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07004976 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08004977 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4978 useIdentityTransform, forSystem, &fd);
4979 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004980 }
4981
4982 {
4983 std::unique_lock<std::mutex> captureLock(captureMutex);
4984 syncFd = fd;
4985 captureResult = std::make_optional<status_t>(result);
4986 captureCondition.notify_one();
4987 }
4988 });
4989
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004990 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004991 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004992 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004993 while (*captureResult == EAGAIN) {
4994 captureResult.reset();
4995 result = postMessageAsync(message);
4996 if (result != NO_ERROR) {
4997 return result;
4998 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07004999 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005000 }
5001 result = *captureResult;
5002 }
5003
5004 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005005 sync_wait(syncFd, -1);
5006 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005007 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005008
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005009 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005010}
5011
chaviwa76b2712017-09-20 12:02:26 -07005012void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5013 TraverseLayersFunction traverseLayers, bool yswap,
5014 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005015 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005016
Lloyd Pique144e1162017-12-20 16:44:52 -08005017 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005018
5019 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005020 const auto raWidth = renderArea.getWidth();
5021 const auto raHeight = renderArea.getHeight();
5022
5023 const auto reqWidth = renderArea.getReqWidth();
5024 const auto reqHeight = renderArea.getReqHeight();
5025 Rect sourceCrop = renderArea.getSourceCrop();
5026
Iris Chang7501ed62018-04-30 14:45:42 +08005027 bool filtering = false;
5028 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5029 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5030 static_cast<int32_t>(reqHeight) != raWidth;
5031 } else {
5032 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5033 static_cast<int32_t>(reqHeight) != raHeight;
5034 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005035
Dan Stozac1879002014-05-22 15:59:05 -07005036 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005037 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005038 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005039 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005040 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5041 Transform tr;
5042 uint32_t flags = 0x00;
5043 switch (mPrimaryDisplayOrientation) {
5044 case DisplayState::eOrientation90:
5045 flags = Transform::ROT_90;
5046 break;
5047 case DisplayState::eOrientation180:
5048 flags = Transform::ROT_180;
5049 break;
5050 case DisplayState::eOrientation270:
5051 flags = Transform::ROT_270;
5052 break;
5053 }
5054 tr.set(flags, raWidth, raHeight);
5055 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005056 }
5057
5058 // ensure that sourceCrop is inside screen
5059 if (sourceCrop.left < 0) {
5060 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5061 }
chaviwa76b2712017-09-20 12:02:26 -07005062 if (sourceCrop.right > raWidth) {
5063 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005064 }
5065 if (sourceCrop.top < 0) {
5066 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5067 }
chaviwa76b2712017-09-20 12:02:26 -07005068 if (sourceCrop.bottom > raHeight) {
5069 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005070 }
5071
Chia-I Wu36574d92018-05-16 10:54:36 -07005072 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5073 engine.setOutputDataSpace(Dataspace::SRGB);
5074 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005075
Mathias Agopian180f10d2013-04-10 22:55:41 -07005076 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005077 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005078
Iris Chang7501ed62018-04-30 14:45:42 +08005079 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5080 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5081 // convert hw orientation into flag presentation
5082 // here inverse transform needed
5083 uint8_t hw_rot_90 = 0x00;
5084 uint8_t hw_flip_hv = 0x00;
5085 switch (mPrimaryDisplayOrientation) {
5086 case DisplayState::eOrientation90:
5087 hw_rot_90 = Transform::ROT_90;
5088 hw_flip_hv = Transform::ROT_180;
5089 break;
5090 case DisplayState::eOrientation180:
5091 hw_flip_hv = Transform::ROT_180;
5092 break;
5093 case DisplayState::eOrientation270:
5094 hw_rot_90 = Transform::ROT_90;
5095 break;
5096 }
5097
5098 // transform flags operation
5099 // 1) flip H V if both have ROT_90 flag
5100 // 2) XOR these flags
5101 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5102 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5103 if (rotation_rot_90 & hw_rot_90) {
5104 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5105 }
5106 rotation = static_cast<Transform::orientation_flags>
5107 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5108 }
5109
Mathias Agopian180f10d2013-04-10 22:55:41 -07005110 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005111 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005112 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005113 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005114
chaviw50da5042018-04-09 13:49:37 -07005115 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005116 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005117 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005118
chaviwa76b2712017-09-20 12:02:26 -07005119 traverseLayers([&](Layer* layer) {
5120 if (filtering) layer->setFiltering(true);
David Sodmanca10ed22018-04-16 14:10:25 -07005121 layer->drawNow(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005122 if (filtering) layer->setFiltering(false);
5123 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005124}
5125
chaviwa76b2712017-09-20 12:02:26 -07005126status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5127 TraverseLayersFunction traverseLayers,
5128 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005129 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005130 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005131 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005132 ATRACE_CALL();
5133
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005134 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005135
5136 traverseLayers([&](Layer* layer) {
5137 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5138 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005139
Robert Carr03480e22018-01-04 16:02:06 -08005140 // We allow the system server to take screenshots of secure layers for
5141 // use in situations like the Screen-rotation animation and place
5142 // the impetus on WindowManager to not persist them.
5143 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005144 ALOGW("FB is protected: PERMISSION_DENIED");
5145 return PERMISSION_DENIED;
5146 }
5147
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005148 // this binds the given EGLImage as a framebuffer for the
5149 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005150 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005151 if (bufferBond.getStatus() != NO_ERROR) {
5152 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005153 return INVALID_OPERATION;
5154 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005155
Dan Stozaabcda352017-06-01 14:37:39 -07005156 // this will in fact render into our dequeued buffer
5157 // via an FBO, which means we didn't have to create
5158 // an EGLSurface and therefore we're not
5159 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005160 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005161
Dan Stozaabcda352017-06-01 14:37:39 -07005162 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005163 getRenderEngine().finish();
5164 *outSyncFd = -1;
5165
chaviwa76b2712017-09-20 12:02:26 -07005166 const auto reqWidth = renderArea.getReqWidth();
5167 const auto reqHeight = renderArea.getReqHeight();
5168
Dan Stozaabcda352017-06-01 14:37:39 -07005169 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5170 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005171 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005172 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005173 } else {
5174 base::unique_fd syncFd = getRenderEngine().flush();
5175 if (syncFd < 0) {
5176 getRenderEngine().finish();
5177 }
5178 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005179 }
5180
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005181 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005182}
5183
Mathias Agopiand5556842013-09-19 17:08:37 -07005184void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005185 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005186 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005187 for (size_t y = 0; y < h; y++) {
5188 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5189 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005190 if (p[x] != 0xFF000000) return;
5191 }
5192 }
chaviwa76b2712017-09-20 12:02:26 -07005193 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005194
Robert Carr2047fae2016-11-28 14:09:09 -08005195 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005196 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005197 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005198 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5199 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5200 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5201 static_cast<float>(state.color.a));
5202 i++;
5203 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005204 }
5205}
5206
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005207// ---------------------------------------------------------------------------
5208
Dan Stoza412903f2017-04-27 13:42:17 -07005209void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5210 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005211}
5212
Dan Stoza412903f2017-04-27 13:42:17 -07005213void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5214 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005215}
5216
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005217void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5218 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005219 const LayerVector::Visitor& visitor) {
5220 // We loop through the first level of layers without traversing,
5221 // as we need to interpret min/max layer Z in the top level Z space.
5222 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005223 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005224 continue;
5225 }
5226 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005227 // relative layers are traversed in Layer::traverseInZOrder
5228 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005229 continue;
5230 }
5231 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005232 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005233 return;
5234 }
chaviwa76b2712017-09-20 12:02:26 -07005235 if (!layer->isVisible()) {
5236 return;
5237 }
5238 visitor(layer);
5239 });
5240 }
5241}
5242
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005243}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005244
Lloyd Pique074e8122018-07-26 12:57:23 -07005245
Mathias Agopian3f844832013-08-07 21:24:32 -07005246#if defined(__gl_h_)
5247#error "don't include gl/gl.h in this file"
5248#endif
5249
5250#if defined(__gl2_h_)
5251#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005252#endif