blob: 002b60d1bd8b9da49dc4698dc13237b26207d064 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Chia-I Wud49d6692018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070050
51#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070066#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070067#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020070#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080072#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080073#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Steven Thomasb02664d2017-07-26 18:48:28 -070079#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070080#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include "Effects/Daltonizer.h"
Mathias Agopian875d8e12013-06-07 15:35:48 -070085#include "RenderEngine/RenderEngine.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070086#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070087#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070088#include "Scheduler/EventControlThread.h"
89#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070090#include "Scheduler/InjectVSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070091
Mathias Agopianff2ed702013-09-01 21:36:12 -070092#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070093
Jiyong Park4b20c2e2017-01-14 19:45:11 +090094#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080095#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -070096#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080097#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090098#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090099
chaviw1d044282017-09-27 12:19:28 -0700100#include <layerproto/LayerProtoParser.h>
101
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800102#define DISPLAY_COUNT 1
103
Mathias Agopianfee2b462013-07-03 12:34:01 -0700104/*
105 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
106 * black pixels.
107 */
108#define DEBUG_SCREENSHOTS false
109
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800110namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700111
Jaesoo Lee43518572017-01-23 19:03:16 +0900112using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900113using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700114using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700115using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700116using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700117using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900118
Steven Thomasb02664d2017-07-26 18:48:28 -0700119namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700120
121#pragma clang diagnostic push
122#pragma clang diagnostic error "-Wswitch-enum"
123
124bool isWideColorMode(const ColorMode colorMode) {
125 switch (colorMode) {
126 case ColorMode::DISPLAY_P3:
127 case ColorMode::ADOBE_RGB:
128 case ColorMode::DCI_P3:
129 case ColorMode::BT2020:
130 case ColorMode::BT2100_PQ:
131 case ColorMode::BT2100_HLG:
132 return true;
133 case ColorMode::NATIVE:
134 case ColorMode::STANDARD_BT601_625:
135 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
136 case ColorMode::STANDARD_BT601_525:
137 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
138 case ColorMode::STANDARD_BT709:
139 case ColorMode::SRGB:
140 return false;
141 }
142 return false;
143}
144
145#pragma clang diagnostic pop
146
Steven Thomasb02664d2017-07-26 18:48:28 -0700147class ConditionalLock {
148public:
149 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
150 if (lock) {
151 mMutex.lock();
152 }
153 }
154 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
155private:
156 Mutex& mMutex;
157 bool mLocked;
158};
Peiyong Linfca547f2018-07-09 13:03:33 -0700159
Steven Thomasb02664d2017-07-26 18:48:28 -0700160} // namespace anonymous
161
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800162// ---------------------------------------------------------------------------
163
Mathias Agopian99b49842011-06-27 16:05:52 -0700164const String16 sHardwareTest("android.permission.HARDWARE_TEST");
165const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
166const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
167const String16 sDump("android.permission.DUMP");
168
169// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800170int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
171int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700172int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700173bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800174uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800175bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800176bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800177int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800178// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600179bool SurfaceFlinger::hasWideColorDisplay;
Peiyong Lin13effd12018-07-24 17:01:47 -0700180bool SurfaceFlinger::useColorManagement;
Mathias Agopian99b49842011-06-27 16:05:52 -0700181
Kalle Raitaa099a242017-01-11 11:17:29 -0800182
183std::string getHwcServiceName() {
184 char value[PROPERTY_VALUE_MAX] = {};
185 property_get("debug.sf.hwc_service_name", value, "default");
186 ALOGI("Using HWComposer service: '%s'", value);
187 return std::string(value);
188}
189
190bool useTrebleTestingOverride() {
191 char value[PROPERTY_VALUE_MAX] = {};
192 property_get("debug.sf.treble_testing_override", value, "false");
193 ALOGI("Treble testing override: '%s'", value);
194 return std::string(value) == "true";
195}
196
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800197std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
198 switch(displayColorSetting) {
199 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700200 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800201 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700202 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800203 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700204 return std::string("Enhanced");
205 default:
206 return std::string("Unknown ") +
207 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800208 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800209}
210
Lloyd Pique99d3da52018-01-22 17:48:03 -0800211NativeWindowSurface::~NativeWindowSurface() = default;
212
213namespace impl {
214
215class NativeWindowSurface final : public android::NativeWindowSurface {
216public:
217 static std::unique_ptr<android::NativeWindowSurface> create(
218 const sp<IGraphicBufferProducer>& producer) {
219 return std::make_unique<NativeWindowSurface>(producer);
220 }
221
222 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
223 : surface(new Surface(producer, false)) {}
224
225 ~NativeWindowSurface() override = default;
226
227private:
228 sp<ANativeWindow> getNativeWindow() const override { return surface; }
229
230 void preallocateBuffers() override { surface->allocateBuffers(); }
231
232 sp<Surface> surface;
233};
234
235} // namespace impl
236
David Sodmanbc815282017-11-05 18:57:52 -0800237SurfaceFlingerBE::SurfaceFlingerBE()
238 : mHwcServiceName(getHwcServiceName()),
239 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800240 mFrameBuckets(),
241 mTotalTime(0),
242 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800243 mComposerSequenceId(0) {
244}
245
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800246SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800247 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800248 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700249 mTransactionPending(false),
250 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700251 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700252 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700253 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800254 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700255 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800256 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800257 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800258 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800259 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800260 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700261 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700262 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700263 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700264 mDebugInTransaction(0),
265 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700266 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700267 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700268 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800269 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800270 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800271 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700272 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800273 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800274 mCreateBufferQueue(&BufferQueue::createBufferQueue),
275 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800276
277SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800278 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800279
280 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
281 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
282
283 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
284 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
285
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800286 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
287 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700289 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
290 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
291
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700292 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
293 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
294
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800295 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
296 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
297
Steven Thomas050b2c82017-03-06 11:45:16 -0800298 // Vr flinger is only enabled on Daydream ready devices.
299 useVrFlinger = getBool< ISurfaceFlingerConfigs,
300 &ISurfaceFlingerConfigs::useVrFlinger>(false);
301
Fabien Sanglard1971b632017-03-10 14:50:03 -0800302 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
303 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
304
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600305 hasWideColorDisplay =
306 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700307 useColorManagement =
308 getBool<V1_2::ISurfaceFlingerConfigs, &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600309
Iris Chang7501ed62018-04-30 14:45:42 +0800310 V1_1::DisplayOrientation primaryDisplayOrientation =
311 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
312 V1_1::DisplayOrientation::ORIENTATION_0);
313
314 switch (primaryDisplayOrientation) {
315 case V1_1::DisplayOrientation::ORIENTATION_90:
316 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
317 break;
318 case V1_1::DisplayOrientation::ORIENTATION_180:
319 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
320 break;
321 case V1_1::DisplayOrientation::ORIENTATION_270:
322 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
323 break;
324 default:
325 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
326 break;
327 }
328 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
329
Lloyd Pique41be5d22018-06-21 13:11:48 -0700330 // Note: We create a local temporary with the real DispSync implementation
331 // type temporarily so we can initialize it with the configured values,
332 // before storing it for more generic use using the interface type.
333 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
334 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
335 SurfaceFlinger::dispSyncPresentTimeOffset);
336 mPrimaryDispSync = std::move(primaryDispSync);
Saurabh Shahf4174532017-07-13 10:45:07 -0700337
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800338 // debugging stuff...
339 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700340
Mathias Agopianb4b17302013-03-20 18:36:41 -0700341 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700342 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700343
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800344 property_get("debug.sf.showupdates", value, "0");
345 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700346
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700347 property_get("debug.sf.ddms", value, "0");
348 mDebugDDMS = atoi(value);
349 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700350 if (!startDdmConnection()) {
351 // start failed, and DDMS debugging not enabled
352 mDebugDDMS = 0;
353 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700354 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700355 ALOGI_IF(mDebugRegion, "showupdates enabled");
356 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700357
358 property_get("debug.sf.disable_backpressure", value, "0");
359 mPropagateBackpressure = !atoi(value);
360 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700361
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800362 property_get("debug.sf.enable_hwc_vds", value, "0");
363 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800364 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800365
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800366 property_get("ro.sf.disable_triple_buffer", value, "1");
367 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800368 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700369
Yiwei Zhang243b3782018-05-15 17:40:04 -0700370 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700371 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
372 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
373
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200374 property_get("debug.sf.early_phase_offset_ns", value, "-1");
375 const int earlySfOffsetNs = atoi(value);
376
377 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
378 const int earlyGlSfOffsetNs = atoi(value);
379
380 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
381 const int earlyAppOffsetNs = atoi(value);
382
383 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
384 const int earlyGlAppOffsetNs = atoi(value);
385
386 const VSyncModulator::Offsets earlyOffsets =
387 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
388 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
389 const VSyncModulator::Offsets earlyGlOffsets =
390 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
391 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
392 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
393 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700394
Romain Guy11d63f42017-07-20 12:47:14 -0700395 // We should be reading 'persist.sys.sf.color_saturation' here
396 // but since /data may be encrypted, we need to wait until after vold
397 // comes online to attempt to read the property. The property is
398 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800399
400 if (useTrebleTestingOverride()) {
401 // Without the override SurfaceFlinger cannot connect to HIDL
402 // services that are not listed in the manifests. Considered
403 // deriving the setting from the set service name, but it
404 // would be brittle if the name that's not 'default' is used
405 // for production purposes later on.
406 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
407 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800408}
409
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800410void SurfaceFlinger::onFirstRef()
411{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800412 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800413}
414
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800415SurfaceFlinger::~SurfaceFlinger()
416{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800417}
418
Dan Stozac7014012014-02-14 15:03:43 -0800419void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800420{
421 // the window manager died on us. prepare its eulogy.
422
Andy McFadden13a082e2012-08-24 10:16:42 -0700423 // restore initial conditions (default device unblank, etc)
424 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800425
426 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700427 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800428}
429
Robert Carr1db73f62016-12-21 12:58:51 -0800430static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700431 status_t err = client->initCheck();
432 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800433 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800434 }
Robert Carr1db73f62016-12-21 12:58:51 -0800435 return nullptr;
436}
437
438sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
439 return initClient(new Client(this));
440}
441
442sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
443 const sp<IGraphicBufferProducer>& gbp) {
444 if (authenticateSurfaceTexture(gbp) == false) {
445 return nullptr;
446 }
447 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
448 if (layer == nullptr) {
449 return nullptr;
450 }
451
452 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800453}
454
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700455sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
456 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700457{
458 class DisplayToken : public BBinder {
459 sp<SurfaceFlinger> flinger;
460 virtual ~DisplayToken() {
461 // no more references, this display must be terminated
462 Mutex::Autolock _l(flinger->mStateLock);
463 flinger->mCurrentState.displays.removeItem(this);
464 flinger->setTransactionFlags(eDisplayTransactionNeeded);
465 }
466 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700467 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700468 : flinger(flinger) {
469 }
470 };
471
472 sp<BBinder> token = new DisplayToken(this);
473
474 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700475 DisplayDeviceState info;
476 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700477 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700478 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700479 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800480 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700481 return token;
482}
483
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700484void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700485 Mutex::Autolock _l(mStateLock);
486
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700487 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700488 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700489 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700490 return;
491 }
492
493 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700494 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700495 ALOGE("destroyDisplay called for non-virtual display");
496 return;
497 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700498 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700499 mCurrentState.displays.removeItemsAt(idx);
500 setTransactionFlags(eDisplayTransactionNeeded);
501}
502
Mathias Agopiane57f2922012-08-09 16:29:12 -0700503sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700504 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700505 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800506 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700507 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700508 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700509}
510
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800511void SurfaceFlinger::bootFinished()
512{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700513 if (mStartPropertySetThread->join() != NO_ERROR) {
514 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800515 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800516 const nsecs_t now = systemTime();
517 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000518 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700519
520 // wait patiently for the window manager death
521 const String16 name("window");
522 sp<IBinder> window(defaultServiceManager()->getService(name));
523 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700524 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700525 }
526
Steven Thomas050b2c82017-03-06 11:45:16 -0800527 if (mVrFlinger) {
528 mVrFlinger->OnBootFinished();
529 }
530
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700531 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700532 // formerly we would just kill the process, but we now ask it to exit so it
533 // can choose where to stop the animation.
534 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700535
536 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
537 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
538 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700539
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800540 postMessageAsync(new LambdaMessage([this] {
541 readPersistentProperties();
542 mBootStage = BootStage::FINISHED;
543 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800544}
545
Dan Stoza436ccf32018-06-21 12:10:12 -0700546uint32_t SurfaceFlinger::getNewTexture() {
547 {
548 std::lock_guard lock(mTexturePoolMutex);
549 if (!mTexturePool.empty()) {
550 uint32_t name = mTexturePool.back();
551 mTexturePool.pop_back();
552 ATRACE_INT("TexturePoolSize", mTexturePool.size());
553 return name;
554 }
555
556 // The pool was too small, so increase it for the future
557 ++mTexturePoolSize;
558 }
559
560 // The pool was empty, so we need to get a new texture name directly using a
561 // blocking call to the main thread
562 uint32_t name = 0;
563 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
564 return name;
565}
566
Mathias Agopian3f844832013-08-07 21:24:32 -0700567void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700568 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700569}
570
Wei Wangf9b05ee2017-07-19 20:59:39 -0700571// Do not call property_set on main thread which will be blocked by init
572// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700573void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700574 ALOGI( "SurfaceFlinger's main thread ready to run. "
575 "Initializing graphics H/W...");
576
Thierry Strudel2924d012017-08-14 15:19:37 -0700577 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900578
Steven Thomasb02664d2017-07-26 18:48:28 -0700579 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800580
Steven Thomasb02664d2017-07-26 18:48:28 -0700581 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800582 mEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700583 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
584 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800585 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700586 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800587 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800588 "appEventThread");
589 mSfEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700590 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800591 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800592
Lloyd Pique24b0a482018-03-09 18:52:26 -0800593 mSFEventThread =
594 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700595 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800596 [this](nsecs_t timestamp) {
597 mInterceptor->saveVSyncEvent(timestamp);
598 },
599 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800600 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200601 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800602
Steven Thomasb02664d2017-07-26 18:48:28 -0700603 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700604 int32_t renderEngineFeature = 0;
605 renderEngineFeature |= (useColorManagement ? RE::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Lloyd Pique144e1162017-12-20 16:44:52 -0800606 getBE().mRenderEngine =
Peiyong Lin13effd12018-07-24 17:01:47 -0700607 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888, renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800608 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700609
610 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
611 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800612 getBE().mHwc.reset(
613 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700614 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800615 // Process any initial hotplug and resulting display changes.
616 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700617 const auto display = getDefaultDisplayDeviceLocked();
618 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
619 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
620 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800621
Lloyd Piquefcd86612017-12-14 17:15:36 -0800622 // make the default display GLContext current so that we can create textures
623 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700624 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800625
Steven Thomas050b2c82017-03-06 11:45:16 -0800626 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700627 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700628 // This callback is called from the vr flinger dispatch thread. We
629 // need to call signalTransaction(), which requires holding
630 // mStateLock when we're not on the main thread. Acquiring
631 // mStateLock from the vr flinger dispatch thread might trigger a
632 // deadlock in surface flinger (see b/66916578), so post a message
633 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700634 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700635 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
636 mVrFlingerRequestsDisplay = requestDisplay;
637 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700638 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800639 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700640 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
641 getHwComposer()
642 .getHwcDisplayId(display->getId())
643 .value_or(0),
644 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800645 if (!mVrFlinger) {
646 ALOGE("Failed to start vrflinger");
647 }
648 }
649
Lloyd Pique379adc12018-01-22 17:31:47 -0800650 mEventControlThread = std::make_unique<impl::EventControlThread>(
651 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700652
Mathias Agopian92a979a2012-08-02 18:32:23 -0700653 // initialize our drawing state
654 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700655
Andy McFadden13a082e2012-08-24 10:16:42 -0700656 // set initial conditions (e.g. unblank default device)
657 initializeDisplays();
658
David Sodmanbc815282017-11-05 18:57:52 -0800659 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700660
Wei Wangf9b05ee2017-07-19 20:59:39 -0700661 // Inform native graphics APIs whether the present timestamp is supported:
662 if (getHwComposer().hasCapability(
663 HWC2::Capability::PresentFenceIsNotReliable)) {
664 mStartPropertySetThread = new StartPropertySetThread(false);
665 } else {
666 mStartPropertySetThread = new StartPropertySetThread(true);
667 }
668
669 if (mStartPropertySetThread->Start() != NO_ERROR) {
670 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800671 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800672
Chia-I Wud49d6692018-06-27 07:17:41 +0800673 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
674 // is used to saturate legacy sRGB content. However, to make sure the same color under
675 // Display P3 will be saturated to the same color, we intentionally break the API spec
676 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
677 // such saturation matrix on Display P3 is understood fully, the API should always return
678 // identify matrix.
679 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
680 Dataspace::SRGB_LINEAR);
681
682 // we will apply this on Display P3.
683 if (mEnhancedSaturationMatrix != mat4()) {
684 ColorSpace srgb(ColorSpace::sRGB());
685 ColorSpace displayP3(ColorSpace::DisplayP3());
686 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
687 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
688 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
689 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800690
Dan Stoza9e56aa02015-11-02 13:00:03 -0800691 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700692}
693
Romain Guy11d63f42017-07-20 12:47:14 -0700694void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700695 Mutex::Autolock _l(mStateLock);
696
Romain Guy11d63f42017-07-20 12:47:14 -0700697 char value[PROPERTY_VALUE_MAX];
698
699 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800700 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700701 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800702 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100703
704 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700705 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700706}
707
Mathias Agopiana67e4182012-06-19 17:26:12 -0700708void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800709 // Start boot animation service by setting a property mailbox
710 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700711 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800712 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700713 if (mStartPropertySetThread->join() != NO_ERROR) {
714 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800715 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700716}
717
Mathias Agopian875d8e12013-06-07 15:35:48 -0700718size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800719 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700720}
721
Mathias Agopian875d8e12013-06-07 15:35:48 -0700722size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800723 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700724}
725
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800726// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800727
Jamie Gennis582270d2011-08-17 18:19:00 -0700728bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800729 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800730 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800731 return authenticateSurfaceTextureLocked(bufferProducer);
732}
733
734bool SurfaceFlinger::authenticateSurfaceTextureLocked(
735 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800736 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800737 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800738}
739
Brian Anderson6b376712017-04-04 10:51:39 -0700740status_t SurfaceFlinger::getSupportedFrameTimestamps(
741 std::vector<FrameEvent>* outSupported) const {
742 *outSupported = {
743 FrameEvent::REQUESTED_PRESENT,
744 FrameEvent::ACQUIRE,
745 FrameEvent::LATCH,
746 FrameEvent::FIRST_REFRESH_START,
747 FrameEvent::LAST_REFRESH_START,
748 FrameEvent::GPU_COMPOSITION_DONE,
749 FrameEvent::DEQUEUE_READY,
750 FrameEvent::RELEASE,
751 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700752 ConditionalLock _l(mStateLock,
753 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700754 if (!getHwComposer().hasCapability(
755 HWC2::Capability::PresentFenceIsNotReliable)) {
756 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
757 }
758 return NO_ERROR;
759}
760
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700761status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
762 Vector<DisplayInfo>* configs) {
763 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700764 return BAD_VALUE;
765 }
766
Jesse Hall692c7232012-11-08 15:41:56 -0800767 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700768 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
769 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700770 type = i;
771 break;
772 }
773 }
774
775 if (type < 0) {
776 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700777 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700778
Mathias Agopian8b736f12012-08-13 17:54:26 -0700779 // TODO: Not sure if display density should handled by SF any longer
780 class Density {
781 static int getDensityFromProperty(char const* propName) {
782 char property[PROPERTY_VALUE_MAX];
783 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800784 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700785 density = atoi(property);
786 }
787 return density;
788 }
789 public:
790 static int getEmuDensity() {
791 return getDensityFromProperty("qemu.sf.lcd_density"); }
792 static int getBuildDensity() {
793 return getDensityFromProperty("ro.sf.lcd_density"); }
794 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700795
Dan Stoza7f7da322014-05-02 15:26:25 -0700796 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700797
Steven Thomas6d8110b2017-08-31 18:24:21 -0700798 ConditionalLock _l(mStateLock,
799 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800800 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700801 DisplayInfo info = DisplayInfo();
802
Dan Stoza9e56aa02015-11-02 13:00:03 -0800803 float xdpi = hwConfig->getDpiX();
804 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700805
806 if (type == DisplayDevice::DISPLAY_PRIMARY) {
807 // The density of the device is provided by a build property
808 float density = Density::getBuildDensity() / 160.0f;
809 if (density == 0) {
810 // the build doesn't provide a density -- this is wrong!
811 // use xdpi instead
812 ALOGE("ro.sf.lcd_density must be defined as a build property");
813 density = xdpi / 160.0f;
814 }
815 if (Density::getEmuDensity()) {
816 // if "qemu.sf.lcd_density" is specified, it overrides everything
817 xdpi = ydpi = density = Density::getEmuDensity();
818 density /= 160.0f;
819 }
820 info.density = density;
821
822 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700823 const auto display = getDefaultDisplayDeviceLocked();
824 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700825 } else {
826 // TODO: where should this value come from?
827 static const int TV_DENSITY = 213;
828 info.density = TV_DENSITY / 160.0f;
829 info.orientation = 0;
830 }
831
Dan Stoza9e56aa02015-11-02 13:00:03 -0800832 info.w = hwConfig->getWidth();
833 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700834 info.xdpi = xdpi;
835 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800836 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900837 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800838
Andy McFadden91b2ca82014-06-13 14:04:23 -0700839 // This is how far in advance a buffer must be queued for
840 // presentation at a given time. If you want a buffer to appear
841 // on the screen at time N, you must submit the buffer before
842 // (N - presentationDeadline).
843 //
844 // Normally it's one full refresh period (to give SF a chance to
845 // latch the buffer), but this can be reduced by configuring a
846 // DispSync offset. Any additional delays introduced by the hardware
847 // composer or panel must be accounted for here.
848 //
849 // We add an additional 1ms to allow for processing time and
850 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800851 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800852 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700853
854 // All non-virtual displays are currently considered secure.
855 info.secure = true;
856
Iris Chang7501ed62018-04-30 14:45:42 +0800857 if (type == DisplayDevice::DISPLAY_PRIMARY &&
858 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
859 std::swap(info.w, info.h);
860 }
861
Michael Wright28f24d02016-07-12 13:30:53 -0700862 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700863 }
864
Dan Stoza7f7da322014-05-02 15:26:25 -0700865 return NO_ERROR;
866}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700867
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700868status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
869 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700870 return BAD_VALUE;
871 }
872
873 // FIXME for now we always return stats for the primary display
874 memset(stats, 0, sizeof(*stats));
Lloyd Pique41be5d22018-06-21 13:11:48 -0700875 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
876 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700877 return NO_ERROR;
878}
879
Yiwei Zhangcd3f9e92018-08-21 15:15:42 -0700880status_t SurfaceFlinger::getDisplayViewport(const sp<IBinder>& display, Rect* outViewport) {
881 if (outViewport == nullptr || display.get() == nullptr) {
882 return BAD_VALUE;
883 }
884
885 sp<const DisplayDevice> device(getDisplayDevice(display));
886 if (device == nullptr) {
887 return BAD_VALUE;
888 }
889
890 *outViewport = device->getViewport();
891
892 return NO_ERROR;
893}
894
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700895int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
896 const auto display = getDisplayDevice(displayToken);
897 if (!display) {
898 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800899 return BAD_VALUE;
900 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700901
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700902 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700903}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700904
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700905void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
906 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700907 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700908 return;
909 }
910
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700911 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700912 ALOGW("Trying to set config for virtual display");
913 return;
914 }
915
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700916 display->setActiveConfig(mode);
917 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700918}
919
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700920status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700921 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700922 Vector<DisplayInfo> configs;
923 getDisplayConfigs(displayToken, &configs);
924 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
925 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
926 configs.size());
927 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700928 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700929 const auto display = getDisplayDevice(displayToken);
930 if (!display) {
931 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
932 displayToken.get());
933 } else if (display->isVirtual()) {
934 ALOGW("Attempt to set active config %d for virtual display", mode);
935 } else {
936 setActiveConfigInternal(display, mode);
937 }
938 }));
939
Mathias Agopian888c8222012-08-04 21:10:38 -0700940 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700941}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700942status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
943 Vector<ColorMode>* outColorModes) {
944 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700945 return BAD_VALUE;
946 }
947
Michael Wright28f24d02016-07-12 13:30:53 -0700948 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700949 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
950 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700951 type = i;
952 break;
953 }
954 }
955
956 if (type < 0) {
957 return type;
958 }
959
Peiyong Lina52f0292018-03-14 17:26:31 -0700960 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700961 {
962 ConditionalLock _l(mStateLock,
963 std::this_thread::get_id() != mMainThreadId);
964 modes = getHwComposer().getColorModes(type);
965 }
Michael Wright28f24d02016-07-12 13:30:53 -0700966 outColorModes->clear();
967 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
968
969 return NO_ERROR;
970}
971
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700972ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
973 if (const auto display = getDisplayDevice(displayToken)) {
974 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700975 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700976 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700977}
978
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700979void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
980 Dataspace dataSpace, RenderIntent renderIntent) {
981 ColorMode currentMode = display->getActiveColorMode();
982 Dataspace currentDataSpace = display->getCompositionDataSpace();
983 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -0700984
Peiyong Lin38e9a562018-04-10 16:24:20 -0700985 if (mode == currentMode && dataSpace == currentDataSpace &&
986 renderIntent == currentRenderIntent) {
987 return;
988 }
989
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700990 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -0700991 ALOGW("Trying to set config for virtual display");
992 return;
993 }
994
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700995 display->setActiveColorMode(mode);
996 display->setCompositionDataSpace(dataSpace);
997 display->setActiveRenderIntent(renderIntent);
998 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800999
1000 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001001 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1002 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001003}
1004
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001005status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001006 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001007 Vector<ColorMode> modes;
1008 getDisplayColorModes(displayToken, &modes);
1009 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1010 if (mode < ColorMode::NATIVE || !exists) {
1011 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1012 decodeColorMode(mode).c_str(), mode, displayToken.get());
1013 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001014 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001015 const auto display = getDisplayDevice(displayToken);
1016 if (!display) {
1017 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1018 decodeColorMode(mode).c_str(), mode, displayToken.get());
1019 } else if (display->isVirtual()) {
1020 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1021 decodeColorMode(mode).c_str(), mode);
1022 } else {
1023 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1024 RenderIntent::COLORIMETRIC);
1025 }
1026 }));
1027
Michael Wright28f24d02016-07-12 13:30:53 -07001028 return NO_ERROR;
1029}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001030
Svetoslavd85084b2014-03-20 10:28:31 -07001031status_t SurfaceFlinger::clearAnimationFrameStats() {
1032 Mutex::Autolock _l(mStateLock);
1033 mAnimFrameTracker.clearStats();
1034 return NO_ERROR;
1035}
1036
1037status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1038 Mutex::Autolock _l(mStateLock);
1039 mAnimFrameTracker.getStats(outStats);
1040 return NO_ERROR;
1041}
1042
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001043status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1044 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001045 Mutex::Autolock _l(mStateLock);
1046
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001047 const auto display = getDisplayDeviceLocked(displayToken);
1048 if (!display) {
1049 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001050 return BAD_VALUE;
1051 }
1052
Peiyong Linfb069302018-04-25 14:34:31 -07001053 // At this point the DisplayDeivce should already be set up,
1054 // meaning the luminance information is already queried from
1055 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001056 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001057 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1058 capabilities.getDesiredMaxLuminance(),
1059 capabilities.getDesiredMaxAverageLuminance(),
1060 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001061
1062 return NO_ERROR;
1063}
1064
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001065status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001066 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001067 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001068
Chia-I Wu90f669f2017-10-05 14:24:41 -07001069 if (mInjectVSyncs == enable) {
1070 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001071 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001072
1073 if (enable) {
1074 ALOGV("VSync Injections enabled");
1075 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001076 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001077 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001078 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001079 impl::EventThread::InterceptVSyncsCallback(),
1080 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001081 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001082 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001083 } else {
1084 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001085 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001086 }
1087
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001088 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001089 }));
1090
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001091 return NO_ERROR;
1092}
1093
1094status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001095 Mutex::Autolock _l(mStateLock);
1096
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001097 if (!mInjectVSyncs) {
1098 ALOGE("VSync Injections not enabled");
1099 return BAD_VALUE;
1100 }
1101 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1102 ALOGV("Injecting VSync inside SurfaceFlinger");
1103 mVSyncInjector->onInjectSyncEvent(when);
1104 }
1105 return NO_ERROR;
1106}
1107
Lloyd Pique755e3192018-01-31 16:46:15 -08001108status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1109 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001110 // Try to acquire a lock for 1s, fail gracefully
1111 const status_t err = mStateLock.timedLock(s2ns(1));
1112 const bool locked = (err == NO_ERROR);
1113 if (!locked) {
1114 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1115 return TIMED_OUT;
1116 }
1117
1118 outLayers->clear();
1119 mCurrentState.traverseInZOrder([&](Layer* layer) {
1120 outLayers->push_back(layer->getLayerDebugInfo());
1121 });
1122
1123 mStateLock.unlock();
1124 return NO_ERROR;
1125}
1126
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001127// ----------------------------------------------------------------------------
1128
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001129sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1130 ISurfaceComposer::VsyncSource vsyncSource) {
1131 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1132 return mSFEventThread->createEventConnection();
1133 } else {
1134 return mEventThread->createEventConnection();
1135 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001136}
1137
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001138// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001139
1140void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001141 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001142}
1143
1144void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001145 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001146}
1147
1148void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001149 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001150}
1151
1152void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001153 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001154 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001155}
1156
1157status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001158 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001159 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001160}
1161
1162status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001163 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001164 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001165 if (res == NO_ERROR) {
1166 msg->wait();
1167 }
1168 return res;
1169}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001170
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001171void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001172 do {
1173 waitForEvent();
1174 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001175}
1176
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001177void SurfaceFlinger::enableHardwareVsync() {
1178 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001179 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001180 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001181 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001182 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001183 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001184}
1185
Jesse Hall948fe0c2013-10-14 12:56:09 -07001186void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001187 Mutex::Autolock _l(mHWVsyncLock);
1188
Jesse Hall948fe0c2013-10-14 12:56:09 -07001189 if (makeAvailable) {
1190 mHWVsyncAvailable = true;
1191 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001192 // Hardware vsync is not currently available, so abort the resync
1193 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001194 return;
1195 }
1196
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001197 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1198 if (!getHwComposer().isConnected(displayId)) {
1199 return;
1200 }
1201
1202 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001203 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001204
Lloyd Pique41be5d22018-06-21 13:11:48 -07001205 mPrimaryDispSync->reset();
1206 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001207
1208 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001209 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001210 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001211 mPrimaryHWVsyncEnabled = true;
1212 }
1213}
1214
Jesse Hall948fe0c2013-10-14 12:56:09 -07001215void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001216 Mutex::Autolock _l(mHWVsyncLock);
1217 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001218 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001219 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001220 mPrimaryHWVsyncEnabled = false;
1221 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001222 if (makeUnavailable) {
1223 mHWVsyncAvailable = false;
1224 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001225}
1226
Tim Murray4a4e4a22016-04-19 16:29:23 +00001227void SurfaceFlinger::resyncWithRateLimit() {
1228 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001229
1230 // No explicit locking is needed here since EventThread holds a lock while calling this method
1231 static nsecs_t sLastResyncAttempted = 0;
1232 const nsecs_t now = systemTime();
1233 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001234 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001235 }
Dan Stoza57164302017-05-08 14:03:54 -07001236 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001237}
1238
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001239void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1240 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001241 ATRACE_NAME("SF onVsync");
1242
Steven Thomas3cfac282017-02-06 12:29:30 -08001243 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001244 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001245 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001246 return;
1247 }
1248
1249 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001250 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001251 return;
1252 }
1253
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001254 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1255 // For now, we don't do anything with external display vsyncs.
1256 return;
1257 }
1258
Jamie Gennisd1700752013-10-14 12:22:52 -07001259 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001260
Jamie Gennisd1700752013-10-14 12:22:52 -07001261 { // Scope for the lock
1262 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001263 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001264 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001265 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001266 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001267
1268 if (needsHwVsync) {
1269 enableHardwareVsync();
1270 } else {
1271 disableHardwareVsync(false);
1272 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001273}
1274
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001275void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001276 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1277 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001278}
1279
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001280void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001281 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001282 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001283 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001284
Lloyd Piqueba04e622017-12-14 17:11:26 -08001285 // Ignore events that do not have the right sequenceId.
1286 if (sequenceId != getBE().mComposerSequenceId) {
1287 return;
1288 }
1289
Steven Thomasb02664d2017-07-26 18:48:28 -07001290 // Only lock if we're not on the main thread. This function is normally
1291 // called on a hwbinder thread, but for the primary display it's called on
1292 // the main thread with the state lock already held, so don't attempt to
1293 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001294 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001295
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001296 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001297
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001298 if (std::this_thread::get_id() == mMainThreadId) {
1299 // Process all pending hot plug events immediately if we are on the main thread.
1300 processDisplayHotplugEventsLocked();
1301 }
1302
Lloyd Piqueba04e622017-12-14 17:11:26 -08001303 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001304}
1305
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001306void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001307 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001308 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001309 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001310 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001311 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001312}
1313
Dan Stoza9e56aa02015-11-02 13:00:03 -08001314void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001315 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001316 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001317 getHwComposer().setVsyncEnabled(disp,
1318 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001319}
1320
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001321// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001322void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001323 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001324 // Clear the drawing state so that the logic inside of
1325 // handleTransactionLocked will fire. It will determine the delta between
1326 // mCurrentState and mDrawingState and re-apply all changes when we make the
1327 // transition.
1328 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001329 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001330 mDisplays.clear();
1331}
1332
Steven Thomas050b2c82017-03-06 11:45:16 -08001333void SurfaceFlinger::updateVrFlinger() {
1334 if (!mVrFlinger)
1335 return;
1336 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001337 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001338 return;
1339 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001340
David Sodman105b7dc2017-11-04 20:28:14 -07001341 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001342 ALOGE("Vr flinger is only supported for remote hardware composer"
1343 " service connections. Ignoring request to transition to vr"
1344 " flinger.");
1345 mVrFlingerRequestsDisplay = false;
1346 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001347 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001348
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001349 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001350
Steven Thomas0123ac62018-07-12 11:32:34 -07001351 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001352 LOG_ALWAYS_FATAL_IF(!display);
1353 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001354 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1355 // called below. Clear the reference now so we don't accidentally use it
1356 // later.
1357 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001358
Steven Thomasb02664d2017-07-26 18:48:28 -07001359 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001360 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001361 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001362
Steven Thomasb02664d2017-07-26 18:48:28 -07001363 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001364 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001365 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1366 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001367 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001368
David Sodman105b7dc2017-11-04 20:28:14 -07001369 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1370 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001371
1372 if (vrFlingerRequestsDisplay) {
1373 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001374 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001375
1376 mVisibleRegionsDirty = true;
1377 invalidateHwcGeometry();
1378
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001379 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001380 display = getDefaultDisplayDeviceLocked();
1381 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001382 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001383
Steven Thomasb02664d2017-07-26 18:48:28 -07001384 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001385 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001386 const nsecs_t period = activeConfig->getVsyncPeriod();
1387 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001388
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001389 // The present fences returned from vr_hwc are not an accurate
1390 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001391 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1392 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001393
Steven Thomasb02664d2017-07-26 18:48:28 -07001394 // Use phase of 0 since phase is not known.
1395 // Use latency of 0, which will snap to the ideal latency.
1396 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001397
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001398 resyncToHardwareVsync(false);
1399
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001400 android_atomic_or(1, &mRepaintEverything);
1401 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001402}
1403
Mathias Agopian4fec8732012-06-29 14:12:52 -07001404void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001405 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001406 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001407 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001408 bool frameMissed = !mHadClientComposition &&
1409 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001410 (mPreviousPresentFence->getSignalTime() ==
1411 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001412 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001413 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001414 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001415 mTimeStats.incrementMissedFrames();
1416 if (mPropagateBackpressure) {
1417 signalLayerUpdate();
1418 break;
1419 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001420 }
Dan Stoza50182882016-07-08 12:02:20 -07001421
Steven Thomas050b2c82017-03-06 11:45:16 -08001422 // Now that we're going to make it to the handleMessageTransaction()
1423 // call below it's safe to call updateVrFlinger(), which will
1424 // potentially trigger a display handoff.
1425 updateVrFlinger();
1426
Dan Stoza6b9454d2014-11-07 16:00:59 -08001427 bool refreshNeeded = handleMessageTransaction();
1428 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001429 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001430 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001431 // Signal a refresh if a transaction modified the window state,
1432 // a new buffer was latched, or if HWC has requested a full
1433 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001434 signalRefresh();
1435 }
1436 break;
1437 }
1438 case MessageQueue::REFRESH: {
1439 handleMessageRefresh();
1440 break;
1441 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001442 }
1443}
1444
Dan Stoza6b9454d2014-11-07 16:00:59 -08001445bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001446 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001447 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001448 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001449 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001450 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001451 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001452}
1453
Mathias Agopian4fec8732012-06-29 14:12:52 -07001454void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001455 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001456
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001457 mRefreshPending = false;
1458
David Sodmanfa9b2af2017-12-24 13:28:59 -08001459 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
David Sodman2b406362017-12-15 13:33:47 -08001460 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001461 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001462 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001463 for (const auto& [token, display] : mDisplays) {
1464 beginFrame(display);
1465 prepareFrame(display);
1466 doDebugFlashRegions(display, repaintEverything);
1467 doComposition(display, repaintEverything);
1468 }
1469
Adrian Roos1e1a1282017-11-01 19:05:31 +01001470 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001471 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001472
1473 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001474 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001475
Dan Stozabfbffeb2016-07-21 14:49:33 -07001476 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001477 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001478 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001479 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001480 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001481
Jorim Jaggi90535212018-05-23 23:44:06 +02001482 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001483
Dan Stoza9e56aa02015-11-02 13:00:03 -08001484 mLayersWithQueuedFrames.clear();
David Sodmanba340492018-08-05 21:51:33 -07001485 for (auto& compositionInfo : getBE().mCompositionInfo) {
1486 compositionInfo.hwc.hwcLayer = nullptr;
1487 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001488}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001489
David Sodmanfa9b2af2017-12-24 13:28:59 -08001490
1491bool SurfaceFlinger::handleMessageInvalidate() {
1492 ATRACE_CALL();
1493 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001494}
1495
David Sodman79bba0e2018-08-05 18:07:49 -07001496void SurfaceFlinger::calculateWorkingSet() {
1497 ATRACE_CALL();
1498 ALOGV(__FUNCTION__);
1499
David Sodman79bba0e2018-08-05 18:07:49 -07001500 // build the h/w work list
1501 if (CC_UNLIKELY(mGeometryInvalid)) {
1502 mGeometryInvalid = false;
1503 for (const auto& [token, display] : mDisplays) {
1504 const auto displayId = display->getId();
1505 if (displayId >= 0) {
1506 const Vector<sp<Layer>>& currentLayers(
1507 display->getVisibleLayersSortedByZ());
1508 for (size_t i = 0; i < currentLayers.size(); i++) {
1509 const auto& layer = currentLayers[i];
1510
1511 if (!layer->hasHwcLayer(displayId)) {
1512 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1513 layer->forceClientComposition(displayId);
1514 continue;
1515 }
1516 }
1517
1518 layer->setGeometry(display, i);
1519 if (mDebugDisableHWC || mDebugRegion) {
1520 layer->forceClientComposition(displayId);
1521 }
1522 }
1523 }
1524 }
1525 }
1526
1527 // Set the per-frame data
1528 for (const auto& [token, display] : mDisplays) {
1529 const auto displayId = display->getId();
1530 if (displayId < 0) {
1531 continue;
1532 }
1533
1534 if (mDrawingState.colorMatrixChanged) {
1535 display->setColorTransform(mDrawingState.colorMatrix);
1536 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1537 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1538 "display %d: %d", displayId, result);
1539 }
1540 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1541 if (layer->isHdrY410()) {
1542 layer->forceClientComposition(displayId);
1543 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1544 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1545 !display->hasHDR10Support()) {
1546 layer->forceClientComposition(displayId);
1547 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1548 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1549 !display->hasHLGSupport()) {
1550 layer->forceClientComposition(displayId);
1551 }
1552
1553 if (layer->getForceClientComposition(displayId)) {
1554 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1555 layer->setCompositionType(displayId, HWC2::Composition::Client);
1556 continue;
1557 }
1558
1559 layer->setPerFrameData(display);
1560 }
1561
Peiyong Lin13effd12018-07-24 17:01:47 -07001562 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001563 ColorMode colorMode;
1564 Dataspace dataSpace;
1565 RenderIntent renderIntent;
1566 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1567 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1568 }
1569 }
1570
1571 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001572 getBE().mCompositionInfo.clear();
1573
1574 for (const auto& [token, display] : mDisplays) {
1575 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1576 auto displayId = display->getId();
1577 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1578 if (!layer->setHwcLayer(displayId)) {
1579 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1580 }
1581 getBE().mCompositionInfo.push_back(layer->getBE().compositionInfo);
1582 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1583 }
1584 }
David Sodman79bba0e2018-08-05 18:07:49 -07001585}
1586
David Sodmanfa9b2af2017-12-24 13:28:59 -08001587void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001588{
1589 // is debugging enabled
1590 if (CC_LIKELY(!mDebugRegion))
1591 return;
1592
David Sodmanfa9b2af2017-12-24 13:28:59 -08001593 if (display->isPoweredOn()) {
1594 // transform the dirty region into this screen's coordinate space
1595 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1596 if (!dirtyRegion.isEmpty()) {
1597 // redraw the whole screen
1598 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001599
David Sodmanfa9b2af2017-12-24 13:28:59 -08001600 // and draw the dirty region
1601 const int32_t height = display->getHeight();
1602 auto& engine(getRenderEngine());
1603 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001604
David Sodmanfa9b2af2017-12-24 13:28:59 -08001605 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001606 }
1607 }
1608
David Sodmanfa9b2af2017-12-24 13:28:59 -08001609 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001610
1611 if (mDebugRegion > 1) {
1612 usleep(mDebugRegion * 1000);
1613 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001614
David Sodmanfa9b2af2017-12-24 13:28:59 -08001615 if (display->isPoweredOn()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001616 status_t result = display->prepareFrame(*getBE().mHwc);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001617 ALOGE_IF(result != NO_ERROR,
1618 "prepareFrame for display %d failed:"
1619 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001620 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001621 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001622}
1623
Adrian Roos1e1a1282017-11-01 19:05:31 +01001624void SurfaceFlinger::doTracing(const char* where) {
1625 ATRACE_CALL();
1626 ATRACE_NAME(where);
1627 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001628 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001629 }
1630}
1631
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001632void SurfaceFlinger::logLayerStats() {
1633 ATRACE_CALL();
1634 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001635 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001636 if (display->isPrimary()) {
1637 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001638 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001639 }
1640 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001641
1642 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001643 }
1644}
1645
David Sodman2b406362017-12-15 13:33:47 -08001646void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001647{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001648 ATRACE_CALL();
1649 ALOGV("preComposition");
1650
David Sodman2b406362017-12-15 13:33:47 -08001651 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1652
Mathias Agopiancd60f992012-08-16 16:28:27 -07001653 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001654 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001655 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001656 needExtraInvalidate = true;
1657 }
Robert Carr2047fae2016-11-28 14:09:09 -08001658 });
1659
Mathias Agopiancd60f992012-08-16 16:28:27 -07001660 if (needExtraInvalidate) {
1661 signalLayerUpdate();
1662 }
1663}
1664
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001665void SurfaceFlinger::updateCompositorTiming(
1666 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1667 std::shared_ptr<FenceTime>& presentFenceTime) {
1668 // Update queue of past composite+present times and determine the
1669 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001670 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001671 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001672 while (!getBE().mCompositePresentTimes.empty()) {
1673 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001674 // Cached values should have been updated before calling this method,
1675 // which helps avoid duplicate syscalls.
1676 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1677 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1678 break;
1679 }
1680 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001681 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001682 }
1683
1684 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001685 while (getBE().mCompositePresentTimes.size() > 16) {
1686 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001687 }
1688
Brian Andersond0010582017-03-07 13:20:31 -08001689 setCompositorTimingSnapped(
1690 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1691}
1692
1693void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1694 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001695 // Integer division and modulo round toward 0 not -inf, so we need to
1696 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001697 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001698 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1699 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1700
Brian Andersond0010582017-03-07 13:20:31 -08001701 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1702 if (idealLatency <= 0) {
1703 idealLatency = vsyncInterval;
1704 }
1705
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001706 // Snap the latency to a value that removes scheduling jitter from the
1707 // composition and present times, which often have >1ms of jitter.
1708 // Reducing jitter is important if an app attempts to extrapolate
1709 // something (such as user input) to an accurate diasplay time.
1710 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1711 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001712 nsecs_t bias = vsyncInterval / 2;
1713 int64_t extraVsyncs =
1714 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1715 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1716 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001717
David Sodman99974d22017-11-28 12:04:33 -08001718 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1719 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1720 getBE().mCompositorTiming.interval = vsyncInterval;
1721 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001722}
1723
David Sodman2b406362017-12-15 13:33:47 -08001724void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001725{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001726 ATRACE_CALL();
1727 ALOGV("postComposition");
1728
Brian Anderson3546a3f2016-07-14 11:51:14 -07001729 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001730 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001731 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001732 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001733 }
1734
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001735 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001736 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001737
David Sodman73beded2017-11-15 11:56:06 -08001738 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001739 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001740 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001741 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001742 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001743 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001744 } else {
1745 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1746 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001747
David Sodman73beded2017-11-15 11:56:06 -08001748 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001749 mPreviousPresentFence =
1750 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1751 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001752 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001753
Lloyd Pique41be5d22018-06-21 13:11:48 -07001754 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1755 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001756
David Sodman2b406362017-12-15 13:33:47 -08001757 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001758 // when we started doing work for this frame, but that should be okay
1759 // since updateCompositorTiming has snapping logic.
1760 updateCompositorTiming(
David Sodman2b406362017-12-15 13:33:47 -08001761 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001762 CompositorTiming compositorTiming;
1763 {
David Sodman99974d22017-11-28 12:04:33 -08001764 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1765 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001766 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001767
Robert Carr2047fae2016-11-28 14:09:09 -08001768 mDrawingState.traverseInZOrder([&](Layer* layer) {
1769 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001770 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001771 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001772 recordBufferingStats(layer->getName().string(),
1773 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001774 }
Robert Carr2047fae2016-11-28 14:09:09 -08001775 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001776
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001777 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001778 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001779 enableHardwareVsync();
1780 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001781 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001782 }
1783 }
1784
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001785 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001786 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001787 enableHardwareVsync();
1788 }
1789 }
1790
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001791 if (mAnimCompositionPending) {
1792 mAnimCompositionPending = false;
1793
Brian Anderson4e606e32017-03-16 15:34:57 -07001794 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001795 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001796 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001797 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001798 // The HWC doesn't support present fences, so use the refresh
1799 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001800 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001801 mAnimFrameTracker.setActualPresentTime(presentTime);
1802 }
1803 mAnimFrameTracker.advanceFrame();
1804 }
Dan Stozab90cf072015-03-05 11:05:59 -08001805
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001806 mTimeStats.incrementTotalFrames();
1807 if (mHadClientComposition) {
1808 mTimeStats.incrementClientCompositionFrames();
1809 }
1810
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001811 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001812 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001813 return;
1814 }
1815
1816 nsecs_t currentTime = systemTime();
1817 if (mHasPoweredOff) {
1818 mHasPoweredOff = false;
1819 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001820 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001821 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001822 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1823 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001824 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001825 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001826 }
David Sodman4a36e932017-11-07 14:29:47 -08001827 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001828 }
David Sodman4a36e932017-11-07 14:29:47 -08001829 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001830
1831 {
1832 std::lock_guard lock(mTexturePoolMutex);
1833 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1834 if (refillCount > 0) {
1835 const size_t offset = mTexturePool.size();
1836 mTexturePool.resize(mTexturePoolSize);
1837 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1838 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1839 }
1840 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001841}
1842
1843void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001844 ATRACE_CALL();
1845 ALOGV("rebuildLayerStacks");
1846
Mathias Agopiancd60f992012-08-16 16:28:27 -07001847 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001848 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001849 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001850 mVisibleRegionsDirty = false;
1851 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001852
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001853 for (const auto& pair : mDisplays) {
1854 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001855 Region opaqueRegion;
1856 Region dirtyRegion;
1857 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001858 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001859 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001860 const Rect bounds = display->getBounds();
1861 if (display->isPoweredOn()) {
1862 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001863
Jeff Sharkey76488112017-02-27 14:15:18 -07001864 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001865 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001866 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001867 Region drawRegion(tr.transform(
1868 layer->visibleNonTransparentRegion));
1869 drawRegion.andSelf(bounds);
1870 if (!drawRegion.isEmpty()) {
1871 layersSortedByZ.add(layer);
1872 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001873 // Clear out the HWC layer if this layer was
1874 // previously visible, but no longer is
1875 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001876 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001877 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001878 // WM changes display->layerStack upon sleep/awake.
1879 // Here we make sure we delete the HWC layers even if
1880 // WM changed their layer stack.
1881 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001882 }
1883
1884 // If a layer is not going to get a release fence because
1885 // it is invisible, but it is also going to release its
1886 // old buffer, add it to the list of layers needing
1887 // fences.
1888 if (hwcLayerDestroyed) {
1889 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1890 mLayersWithQueuedFrames.cend(), layer);
1891 if (found != mLayersWithQueuedFrames.cend()) {
1892 layersNeedingFences.add(layer);
1893 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001894 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001895 });
1896 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001897 display->setVisibleLayersSortedByZ(layersSortedByZ);
1898 display->setLayersNeedingFences(layersNeedingFences);
1899 display->undefinedRegion.set(bounds);
1900 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1901 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001902 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001903 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001904}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001905
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001906// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001907// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001908// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001909// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001910// The returned HDR data space is one of
1911// - Dataspace::UNKNOWN
1912// - Dataspace::BT2020_HLG
1913// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001914Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1915 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001916 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001917 *outHdrDataSpace = Dataspace::UNKNOWN;
1918
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001919 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001920 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001921 case Dataspace::V0_SCRGB:
1922 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001923 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001924 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001925 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001926 case Dataspace::BT2020_PQ:
1927 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001928 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001929 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001930 case Dataspace::BT2020_HLG:
1931 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001932 // When there's mixed PQ content and HLG content, we set the HDR
1933 // data space to be BT2020_PQ and convert HLG to PQ.
1934 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1935 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001936 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001937 break;
1938 default:
1939 break;
1940 }
Romain Guy54f154a2017-10-24 21:40:32 +01001941 }
1942
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001943 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001944}
1945
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001946// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001947void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1948 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001949 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1950 *outMode = ColorMode::NATIVE;
1951 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001952 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001953 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001954 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001955
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001956 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001957 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001958
Peiyong Lindfde5112018-06-05 10:58:41 -07001959 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001960 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001961 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001962 if (isHdr) {
1963 bestDataSpace = hdrDataSpace;
1964 }
1965
Chia-I Wu0d711262018-05-21 15:19:35 -07001966 RenderIntent intent;
1967 switch (mDisplayColorSetting) {
1968 case DisplayColorSetting::MANAGED:
1969 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001970 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001971 break;
1972 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001973 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001974 break;
1975 default: // vendor display color setting
1976 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1977 break;
1978 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001979
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001980 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001981}
1982
David Sodmanfa9b2af2017-12-24 13:28:59 -08001983void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08001984{
David Sodmanfa9b2af2017-12-24 13:28:59 -08001985 bool dirty = !display->getDirtyRegion(false).isEmpty();
1986 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
1987 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08001988
David Sodmanfa9b2af2017-12-24 13:28:59 -08001989 // If nothing has changed (!dirty), don't recompose.
1990 // If something changed, but we don't currently have any visible layers,
1991 // and didn't when we last did a composition, then skip it this time.
1992 // The second rule does two things:
1993 // - When all layers are removed from a display, we'll emit one black
1994 // frame, then nothing more until we get new layers.
1995 // - When a display is created with a private layer stack, we won't
1996 // emit any black frames until a layer is added to the layer stack.
1997 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08001998
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07001999 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2000 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002001 mustRecompose ? "doing" : "skipping",
2002 dirty ? "+" : "-",
2003 empty ? "+" : "-",
2004 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002005
David Sodmanfa9b2af2017-12-24 13:28:59 -08002006 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002007
David Sodmanfa9b2af2017-12-24 13:28:59 -08002008 if (mustRecompose) {
2009 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002010 }
2011}
2012
David Sodmanfa9b2af2017-12-24 13:28:59 -08002013void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002014{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002015 if (!display->isPoweredOn()) {
2016 return;
David Sodman2b406362017-12-15 13:33:47 -08002017 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002018
2019 status_t result = display->prepareFrame(*getBE().mHwc);
2020 ALOGE_IF(result != NO_ERROR,
2021 "prepareFrame for display %d failed:"
2022 " %d (%s)",
2023 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002024}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002025
David Sodmanfa9b2af2017-12-24 13:28:59 -08002026void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002027 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002028 ALOGV("doComposition");
2029
David Sodmanfa9b2af2017-12-24 13:28:59 -08002030 if (display->isPoweredOn()) {
2031 // transform the dirty region into this screen's coordinate space
2032 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002033
David Sodmanfa9b2af2017-12-24 13:28:59 -08002034 // repaint the framebuffer (if needed)
2035 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002036
David Sodmanfa9b2af2017-12-24 13:28:59 -08002037 display->dirtyRegion.clear();
2038 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002039 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002040 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002041}
2042
David Sodmanfa9b2af2017-12-24 13:28:59 -08002043void SurfaceFlinger::postFrame()
2044{
2045 // |mStateLock| not needed as we are on the main thread
2046 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2047 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2048 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2049 logFrameStats();
2050 }
2051 }
2052}
2053
2054void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002055{
Mathias Agopian841cde52012-03-01 15:44:37 -08002056 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002057 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002058
David Sodmanfa9b2af2017-12-24 13:28:59 -08002059 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002060
David Sodmanfa9b2af2017-12-24 13:28:59 -08002061 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002062 const auto displayId = display->getId();
2063 if (displayId >= 0) {
2064 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002065 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002066 display->onSwapBuffersCompleted();
2067 display->makeCurrent();
2068 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002069 sp<Fence> releaseFence = Fence::NO_FENCE;
2070
Chia-I Wu7b549592017-11-15 09:14:57 -08002071 // The layer buffer from the previous frame (if any) is released
2072 // by HWC only when the release fence from this frame (if any) is
2073 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002074 auto hwcLayer = layer->getHwcLayer(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002075 if (displayId >= 0) {
2076 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
2077 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002078
2079 // If the layer was client composited in the previous frame, we
2080 // need to merge with the previous client target acquire fence.
2081 // Since we do not track that, always merge with the current
2082 // client target acquire fence when it is available, even though
2083 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002084 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002085 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002086 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002087 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002088
David Sodmanb8af7922017-12-21 15:17:55 -08002089 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002090 }
Chia-I Wu83806892017-11-16 10:50:20 -08002091
2092 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002093 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002094 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002095 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002096 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002097 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002098 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002099 }
2100 }
2101
Dominik Laskowski7e045462018-05-30 13:02:02 -07002102 if (displayId >= 0) {
2103 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002104 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002105 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002106}
2107
Mathias Agopian87baae12012-07-31 12:38:26 -07002108void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002109{
Mathias Agopian841cde52012-03-01 15:44:37 -08002110 ATRACE_CALL();
2111
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002112 // here we keep a copy of the drawing state (that is the state that's
2113 // going to be overwritten by handleTransactionLocked()) outside of
2114 // mStateLock so that the side-effects of the State assignment
2115 // don't happen with mStateLock held (which can cause deadlocks).
2116 State drawingState(mDrawingState);
2117
Mathias Agopianca4d3602011-05-19 15:38:14 -07002118 Mutex::Autolock _l(mStateLock);
2119 const nsecs_t now = systemTime();
2120 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002121
Mathias Agopianca4d3602011-05-19 15:38:14 -07002122 // Here we're guaranteed that some transaction flags are set
2123 // so we can call handleTransactionLocked() unconditionally.
2124 // We call getTransactionFlags(), which will also clear the flags,
2125 // with mStateLock held to guarantee that mCurrentState won't change
2126 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002127
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002128 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002129 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002130 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002131
Mathias Agopianca4d3602011-05-19 15:38:14 -07002132 mLastTransactionTime = systemTime() - now;
2133 mDebugInTransaction = 0;
2134 invalidateHwcGeometry();
2135 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002136}
2137
Dominik Laskowski7e045462018-05-30 13:02:02 -07002138DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002139 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002140 // Figure out whether the event is for the primary display or an
2141 // external display by matching the Hwc display id against one for a
2142 // connected display. If we did not find a match, we then check what
2143 // displays are not already connected to determine the type. If we don't
2144 // have a connected primary display, we assume the new display is meant to
2145 // be the primary display, and then if we don't have an external display,
2146 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002147 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2148 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002149 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002150 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002151 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002152 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002153 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002154 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002155 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002156 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002157 return DisplayDevice::DISPLAY_EXTERNAL;
2158 }
2159
2160 return DisplayDevice::DISPLAY_ID_INVALID;
2161}
2162
Lloyd Piqueba04e622017-12-14 17:11:26 -08002163void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2164 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002165 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002166 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002167 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002168 continue;
2169 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002170
2171 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2172 ALOGE("External displays are not supported by the vr hardware composer.");
2173 continue;
2174 }
2175
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002176 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002177 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002178 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002179 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002180 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002181
2182 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002183 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002184 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002185 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002186 DisplayDeviceState info;
2187 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002188 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2189 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002190 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002191 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002192 mInterceptor->saveDisplayCreation(info);
2193 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002194 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002195 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002196
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002197 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002198 if (idx >= 0) {
2199 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002200 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002201 mCurrentState.displays.removeItemsAt(idx);
2202 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002203 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002204 }
2205
2206 processDisplayChangesLocked();
2207 }
2208
2209 mPendingHotplugEvents.clear();
2210}
2211
Lloyd Pique99d3da52018-01-22 17:48:03 -08002212sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002213 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002214 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002215 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002216 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002217 HdrCapabilities hdrCapabilities;
2218 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002219
Peiyong Lin13effd12018-07-24 17:01:47 -07002220 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002221 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002222 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002223 if (isWideColorMode(colorMode)) {
2224 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002225 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002226
Dominik Laskowski7e045462018-05-30 13:02:02 -07002227 std::vector<RenderIntent> renderIntents =
2228 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002229 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002230 }
tangrobin6753a022018-08-10 10:58:54 +08002231 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002232
tangrobin6753a022018-08-10 10:58:54 +08002233 if (displayId >= 0) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002234 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2235 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2236 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002237
2238 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2239 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2240
2241 /*
2242 * Create our display's surface
2243 */
2244 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2245 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002246 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002247 renderSurface->setNativeWindow(nativeWindow.get());
2248 const int displayWidth = renderSurface->queryWidth();
2249 const int displayHeight = renderSurface->queryHeight();
2250
2251 // Make sure that composition can never be stalled by a virtual display
2252 // consumer that isn't processing buffers fast enough. We have to do this
2253 // in two places:
2254 // * Here, in case the display is composed entirely by HWC.
2255 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2256 // window's swap interval in eglMakeCurrent, so they'll override the
2257 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002258 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002259 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2260 }
2261
2262 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002263 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002264
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002265 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002266 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2267 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2268 displayHeight, hasWideColorGamut, hdrCapabilities,
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002269 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002270
2271 if (maxFrameBufferAcquiredBuffers >= 3) {
2272 nativeWindowSurface->preallocateBuffers();
2273 }
2274
2275 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002276 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2277 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002278 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002279 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002280 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002281 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002282 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002283 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002284 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002285 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002286 display->setLayerStack(state.layerStack);
2287 display->setProjection(state.orientation, state.viewport, state.frame);
2288 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002289
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002290 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002291}
2292
Lloyd Pique347200f2017-12-14 17:00:15 -08002293void SurfaceFlinger::processDisplayChangesLocked() {
2294 // here we take advantage of Vector's copy-on-write semantics to
2295 // improve performance by skipping the transaction entirely when
2296 // know that the lists are identical
2297 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2298 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2299 if (!curr.isIdenticalTo(draw)) {
2300 mVisibleRegionsDirty = true;
2301 const size_t cc = curr.size();
2302 size_t dc = draw.size();
2303
2304 // find the displays that were removed
2305 // (ie: in drawing state but not in current state)
2306 // also handle displays that changed
2307 // (ie: displays that are in both lists)
2308 for (size_t i = 0; i < dc;) {
2309 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2310 if (j < 0) {
2311 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002312 // Call makeCurrent() on the primary display so we can
2313 // be sure that nothing associated with this display
2314 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002315 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2316 defaultDisplay->makeCurrent();
2317 }
2318 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2319 display->disconnect(getHwComposer());
2320 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002321 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2322 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2323 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2324 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2325 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002326 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002327 } else {
2328 // this display is in both lists. see if something changed.
2329 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002330 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002331 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2332 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2333 if (state_binder != draw_binder) {
2334 // changing the surface is like destroying and
2335 // recreating the DisplayDevice, so we just remove it
2336 // from the drawing state, so that it get re-added
2337 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002338 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2339 display->disconnect(getHwComposer());
2340 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002341 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002342 mDrawingState.displays.removeItemsAt(i);
2343 dc--;
2344 // at this point we must loop to the next item
2345 continue;
2346 }
2347
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002348 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002349 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002350 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002351 }
2352 if ((state.orientation != draw[i].orientation) ||
2353 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002354 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002355 }
2356 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002357 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002358 }
2359 }
2360 }
2361 ++i;
2362 }
2363
2364 // find displays that were added
2365 // (ie: in current state but not in drawing state)
2366 for (size_t i = 0; i < cc; i++) {
2367 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2368 const DisplayDeviceState& state(curr[i]);
2369
2370 sp<DisplaySurface> dispSurface;
2371 sp<IGraphicBufferProducer> producer;
2372 sp<IGraphicBufferProducer> bqProducer;
2373 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002374 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002375
Dominik Laskowski7e045462018-05-30 13:02:02 -07002376 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002377 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002378 // Virtual displays without a surface are dormant:
2379 // they have external state (layer stack, projection,
2380 // etc.) but no internal state (i.e. a DisplayDevice).
2381 if (state.surface != nullptr) {
2382 // Allow VR composer to use virtual displays.
2383 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2384 int width = 0;
2385 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2386 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2387 int height = 0;
2388 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2389 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2390 int intFormat = 0;
2391 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2392 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002393 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002394
Dominik Laskowski7e045462018-05-30 13:02:02 -07002395 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2396 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002397 }
2398
2399 // TODO: Plumb requested format back up to consumer
2400
2401 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002402 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002403 bqProducer, bqConsumer,
2404 state.displayName);
2405
2406 dispSurface = vds;
2407 producer = vds;
2408 }
2409 } else {
2410 ALOGE_IF(state.surface != nullptr,
2411 "adding a supported display, but rendering "
2412 "surface is provided (%p), ignoring it",
2413 state.surface.get());
2414
Dominik Laskowski7e045462018-05-30 13:02:02 -07002415 displayId = state.type;
2416 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002417 producer = bqProducer;
2418 }
2419
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002420 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002421 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002422 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002423 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002424 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002425 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002426 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2427 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2428 true);
2429 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2430 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2431 true);
2432 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002433 }
2434 }
2435 }
2436 }
2437 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002438
2439 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002440}
2441
Mathias Agopian87baae12012-07-31 12:38:26 -07002442void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002443{
Dan Stoza7dde5992015-05-22 09:51:44 -07002444 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002445 mCurrentState.traverseInZOrder([](Layer* layer) {
2446 layer->notifyAvailableFrames();
2447 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002448
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002449 /*
2450 * Traversal of the children
2451 * (perform the transaction for each of them if needed)
2452 */
2453
Mathias Agopian3559b072012-08-15 13:46:03 -07002454 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002455 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002456 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002457 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002458
2459 const uint32_t flags = layer->doTransaction(0);
2460 if (flags & Layer::eVisibleRegion)
2461 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002462 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002463 }
2464
2465 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002466 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002467 */
2468
Mathias Agopiane57f2922012-08-09 16:29:12 -07002469 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002470 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002471 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002472 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002473
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002474 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002475 // The transform hint might have changed for some layers
2476 // (either because a display has changed, or because a layer
2477 // as changed).
2478 //
2479 // Walk through all the layers in currentLayers,
2480 // and update their transform hint.
2481 //
2482 // If a layer is visible only on a single display, then that
2483 // display is used to calculate the hint, otherwise we use the
2484 // default display.
2485 //
2486 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2487 // the hint is set before we acquire a buffer from the surface texture.
2488 //
2489 // NOTE: layer transactions have taken place already, so we use their
2490 // drawing state. However, SurfaceFlinger's own transaction has not
2491 // happened yet, so we must use the current state layer list
2492 // (soon to become the drawing state list).
2493 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002494 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002495 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002496 bool first = true;
2497 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002498 // NOTE: we rely on the fact that layers are sorted by
2499 // layerStack first (so we don't have to traverse the list
2500 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002501 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002502 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002503 currentlayerStack = layerStack;
2504 // figure out if this layerstack is mirrored
2505 // (more than one display) if so, pick the default display,
2506 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002507 hintDisplay = nullptr;
2508 for (const auto& [token, display] : mDisplays) {
2509 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2510 if (hintDisplay) {
2511 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002512 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002513 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002514 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002515 }
2516 }
2517 }
2518 }
Chet Haase91d25932013-04-11 15:24:55 -07002519
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002520 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002521 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2522 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002523
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002524 // could be null when this layer is using a layerStack
2525 // that is not visible on any display. Also can occur at
2526 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002527 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002528 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002529
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002530 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002531 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002532 if (hintDisplay) {
2533 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002534 }
Robert Carr2047fae2016-11-28 14:09:09 -08002535
2536 first = false;
2537 });
Mathias Agopian84300952012-11-21 16:02:13 -08002538 }
2539
2540
Mathias Agopian3559b072012-08-15 13:46:03 -07002541 /*
2542 * Perform our own transaction if needed
2543 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002544
2545 if (mLayersAdded) {
2546 mLayersAdded = false;
2547 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002548 mVisibleRegionsDirty = true;
2549 }
2550
2551 // some layers might have been removed, so
2552 // we need to update the regions they're exposing.
2553 if (mLayersRemoved) {
2554 mLayersRemoved = false;
2555 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002556 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002557 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002558 // this layer is not visible anymore
2559 // TODO: we could traverse the tree from front to back and
2560 // compute the actual visible region
2561 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002562 Region visibleReg;
2563 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002564 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002565 }
Robert Carr2047fae2016-11-28 14:09:09 -08002566 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002567 }
2568
2569 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002570
2571 updateCursorAsync();
2572}
2573
2574void SurfaceFlinger::updateCursorAsync()
2575{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002576 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002577 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002578 continue;
2579 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002580
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002581 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2582 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002583 }
2584 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002585}
2586
2587void SurfaceFlinger::commitTransaction()
2588{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002589 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002590 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002591 for (const auto& l : mLayersPendingRemoval) {
2592 recordBufferingStats(l->getName().string(),
2593 l->getOccupancyHistory(true));
2594 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002595 }
2596 mLayersPendingRemoval.clear();
2597 }
2598
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002599 // If this transaction is part of a window animation then the next frame
2600 // we composite should be considered an animation as well.
2601 mAnimCompositionPending = mAnimTransactionPending;
2602
Mathias Agopian4fec8732012-06-29 14:12:52 -07002603 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002604 // clear the "changed" flags in current state
2605 mCurrentState.colorMatrixChanged = false;
2606
Robert Carr1f0a16a2016-10-24 16:27:39 -07002607 mDrawingState.traverseInZOrder([](Layer* layer) {
2608 layer->commitChildList();
2609 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002610 mTransactionPending = false;
2611 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002612 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002613}
2614
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002615void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2616 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002617 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002618 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002619
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002620 Region aboveOpaqueLayers;
2621 Region aboveCoveredLayers;
2622 Region dirty;
2623
Mathias Agopian87baae12012-07-31 12:38:26 -07002624 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002625
Robert Carr2047fae2016-11-28 14:09:09 -08002626 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002627 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002628 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002629
Jesse Hall01e29052013-02-19 16:13:35 -08002630 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002631 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002632 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002633 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002634
Mathias Agopianab028732010-03-16 16:41:46 -07002635 /*
2636 * opaqueRegion: area of a surface that is fully opaque.
2637 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002638 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002639
2640 /*
2641 * visibleRegion: area of a surface that is visible on screen
2642 * and not fully transparent. This is essentially the layer's
2643 * footprint minus the opaque regions above it.
2644 * Areas covered by a translucent surface are considered visible.
2645 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002646 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002647
2648 /*
2649 * coveredRegion: area of a surface that is covered by all
2650 * visible regions above it (which includes the translucent areas).
2651 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002652 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002653
Jesse Halla8026d22012-09-25 13:25:04 -07002654 /*
2655 * transparentRegion: area of a surface that is hinted to be completely
2656 * transparent. This is only used to tell when the layer has no visible
2657 * non-transparent regions and can be removed from the layer list. It
2658 * does not affect the visibleRegion of this layer or any layers
2659 * beneath it. The hint may not be correct if apps don't respect the
2660 * SurfaceView restrictions (which, sadly, some don't).
2661 */
2662 Region transparentRegion;
2663
Mathias Agopianab028732010-03-16 16:41:46 -07002664
2665 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002666 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002667 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002668 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002669 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002670 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002671 if (!visibleRegion.isEmpty()) {
2672 // Remove the transparent area from the visible region
2673 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002674 if (tr.preserveRects()) {
2675 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002676 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002677 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002678 // transformation too complex, can't do the
2679 // transparent region optimization.
2680 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002681 }
Mathias Agopianab028732010-03-16 16:41:46 -07002682 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002683
Mathias Agopianab028732010-03-16 16:41:46 -07002684 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002685 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002686 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002687 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002688 // the opaque region is the layer's footprint
2689 opaqueRegion = visibleRegion;
2690 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002691 }
2692 }
2693
Robert Carre5f4f692018-01-12 13:12:28 -08002694 if (visibleRegion.isEmpty()) {
2695 layer->clearVisibilityRegions();
2696 return;
2697 }
2698
Mathias Agopianab028732010-03-16 16:41:46 -07002699 // Clip the covered region to the visible region
2700 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2701
2702 // Update aboveCoveredLayers for next (lower) layer
2703 aboveCoveredLayers.orSelf(visibleRegion);
2704
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002705 // subtract the opaque region covered by the layers above us
2706 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002707
2708 // compute this layer's dirty region
2709 if (layer->contentDirty) {
2710 // we need to invalidate the whole region
2711 dirty = visibleRegion;
2712 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002713 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002714 layer->contentDirty = false;
2715 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002716 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002717 * the exposed region consists of two components:
2718 * 1) what's VISIBLE now and was COVERED before
2719 * 2) what's EXPOSED now less what was EXPOSED before
2720 *
2721 * note that (1) is conservative, we start with the whole
2722 * visible region but only keep what used to be covered by
2723 * something -- which mean it may have been exposed.
2724 *
2725 * (2) handles areas that were not covered by anything but got
2726 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002727 */
Mathias Agopianab028732010-03-16 16:41:46 -07002728 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002729 const Region oldVisibleRegion = layer->visibleRegion;
2730 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002731 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2732 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002733 }
2734 dirty.subtractSelf(aboveOpaqueLayers);
2735
2736 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002737 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002738
Mathias Agopianab028732010-03-16 16:41:46 -07002739 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002740 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002741
Jesse Halla8026d22012-09-25 13:25:04 -07002742 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002743 layer->setVisibleRegion(visibleRegion);
2744 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002745 layer->setVisibleNonTransparentRegion(
2746 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002747 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002748
Mathias Agopian87baae12012-07-31 12:38:26 -07002749 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002750}
2751
Chia-I Wuab0c3192017-08-01 11:29:00 -07002752void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002753 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002754 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2755 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002756 }
2757 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002758}
2759
Dan Stoza6b9454d2014-11-07 16:00:59 -08002760bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002761{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002762 ALOGV("handlePageFlip");
2763
Brian Andersond6927fb2016-07-23 23:37:30 -07002764 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002765
Mathias Agopian4fec8732012-06-29 14:12:52 -07002766 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002767 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002768 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002769
2770 // Store the set of layers that need updates. This set must not change as
2771 // buffers are being latched, as this could result in a deadlock.
2772 // Example: Two producers share the same command stream and:
2773 // 1.) Layer 0 is latched
2774 // 2.) Layer 0 gets a new frame
2775 // 2.) Layer 1 gets a new frame
2776 // 3.) Layer 1 is latched.
2777 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2778 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002779 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002780 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002781 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07002782 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002783 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002784 } else {
2785 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002786 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002787 } else {
2788 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002789 }
Robert Carr2047fae2016-11-28 14:09:09 -08002790 });
2791
Dan Stoza9e56aa02015-11-02 13:00:03 -08002792 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002793 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002794 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002795 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002796 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002797 newDataLatched = true;
2798 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002799 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002800
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002801 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002802
2803 // If we will need to wake up at some time in the future to deal with a
2804 // queued frame that shouldn't be displayed during this vsync period, wake
2805 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002806 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002807 signalLayerUpdate();
2808 }
2809
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002810 // enter boot animation on first buffer latch
2811 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2812 ALOGI("Enter boot animation");
2813 mBootStage = BootStage::BOOTANIMATION;
2814 }
2815
Dan Stoza6b9454d2014-11-07 16:00:59 -08002816 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002817 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002818}
2819
Mathias Agopianad456f92011-01-13 17:53:01 -08002820void SurfaceFlinger::invalidateHwcGeometry()
2821{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002822 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002823}
2824
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002825void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2826 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002827 // We only need to actually compose the display if:
2828 // 1) It is being handled by hardware composer, which may need this to
2829 // keep its virtual display state machine in sync, or
2830 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002831 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002832 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002833 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002834 return;
2835 }
2836
Dan Stoza9e56aa02015-11-02 13:00:03 -08002837 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002838 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002839
2840 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002841 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002842}
2843
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002844bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002845 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002846
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002847 const Region bounds(display->bounds());
2848 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002849 const auto displayId = display->getId();
2850 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002851 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002852
Chia-I Wu8e50e692018-05-04 10:12:37 -07002853 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002854 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002855
Dan Stoza9e56aa02015-11-02 13:00:03 -08002856 if (hasClientComposition) {
2857 ALOGV("hasClientComposition");
2858
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002859 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002860 if (display->hasWideColorGamut()) {
2861 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002862 }
2863 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002864 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002865 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002866
Dominik Laskowski7e045462018-05-30 13:02:02 -07002867 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002868 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2869 HWC2::Capability::SkipClientColorTransform);
2870
Chia-I Wud49d6692018-06-27 07:17:41 +08002871 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002872 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2873 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08002874 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002875 }
2876
Chia-I Wud49d6692018-06-27 07:17:41 +08002877 // The current enhanced saturation matrix is designed to enhance Display P3,
2878 // thus we only apply this matrix when the render intent is not colorimetric
2879 // and the output color space is Display P3.
2880 needsEnhancedColorMatrix =
2881 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2882 outputDataspace == Dataspace::DISPLAY_P3);
2883 if (needsEnhancedColorMatrix) {
2884 colorMatrix *= mEnhancedSaturationMatrix;
2885 }
2886
2887 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002888
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002889 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002890 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002891 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002892 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002893
2894 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002895 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2896 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2897 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002898 }
2899 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002900 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002901
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002902 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002903 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002904 // when using overlays, we assume a fully transparent framebuffer
2905 // NOTE: we could reduce how much we need to clear, for instance
2906 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002907 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002908 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002909 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002910 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002911 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002912 // we're left with the letterbox region
2913 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002914 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07002915
2916 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002917 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07002918
Mathias Agopianb9494d52012-04-18 02:28:45 -07002919 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002920 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002921 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002922 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002923 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002924 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002925
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002926 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002927 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002928 // scissor on the main display. It should never be needed
2929 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002930 const Rect& bounds = display->getBounds();
2931 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07002932 if (scissor != bounds) {
2933 // scissor doesn't match the screen's dimensions, so we
2934 // need to clear everything outside of it and enable
2935 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002936
Mathias Agopianf45c5102012-10-24 16:29:17 -07002937 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002938 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002939 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002940 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002941 }
2942 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002943 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002944
Mathias Agopian85d751c2012-08-29 16:59:24 -07002945 /*
2946 * and then, render the layers targeted at the framebuffer
2947 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002948
Dan Stoza9e56aa02015-11-02 13:00:03 -08002949 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07002950 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002951 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002952 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002953 const Region clip(bounds.intersect(
2954 displayTransform.transform(layer->visibleRegion)));
2955 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002956 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002957 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002958 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002959 case HWC2::Composition::Cursor:
2960 case HWC2::Composition::Device:
2961 case HWC2::Composition::Sideband:
2962 case HWC2::Composition::SolidColor: {
2963 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002964 if (layer->getClearClientTarget(displayId) && !firstLayer &&
Rajavenu Kyatham2eae6d32018-04-10 12:34:05 +05302965 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
2966 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002967 // never clear the very first layer since we're
2968 // guaranteed the FB is already cleared
2969 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002970 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002971 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002972 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002973 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002974 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002975 break;
2976 }
2977 default:
2978 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002979 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002980 } else {
2981 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002982 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002983 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002984 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002985
Chia-I Wud49d6692018-06-27 07:17:41 +08002986 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002987 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002988 }
2989
Mathias Agopianf45c5102012-10-24 16:29:17 -07002990 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002991 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002992 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002993}
2994
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002995void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
2996 const Region& region) const {
2997 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002998 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002999 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003000}
3001
Dan Stoza7d89d062015-04-30 13:29:25 -07003002status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003003 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003004 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003005 const sp<Layer>& lbc,
3006 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003007{
Dan Stoza7d89d062015-04-30 13:29:25 -07003008 // add this layer to the current state list
3009 {
3010 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003011 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003012 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3013 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003014 return NO_MEMORY;
3015 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003016 if (parent == nullptr) {
3017 mCurrentState.layersSortedByZ.add(lbc);
3018 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003019 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003020 ALOGE("addClientLayer called with a removed parent");
3021 return NAME_NOT_FOUND;
3022 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003023 parent->addChild(lbc);
3024 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003025
Yiwei Zhang243b3782018-05-15 17:40:04 -07003026 if (gbc != nullptr) {
3027 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3028 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3029 mMaxGraphicBufferProducerListSize,
3030 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3031 mGraphicBufferProducerList.size(),
3032 mMaxGraphicBufferProducerListSize, mNumLayers);
3033 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003034 mLayersAdded = true;
3035 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003036 }
3037
Mathias Agopian96f08192010-06-02 23:28:45 -07003038 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003039 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003040
Dan Stoza7d89d062015-04-30 13:29:25 -07003041 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003042}
3043
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003044status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003045 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003046 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3047}
Robert Carr7f9b8992017-03-10 11:08:39 -08003048
chaviwca27f252018-02-06 16:46:39 -08003049status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3050 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003051 if (layer->isPendingRemoval()) {
3052 return NO_ERROR;
3053 }
3054
Robert Carr1f0a16a2016-10-24 16:27:39 -07003055 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003056 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003057 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003058 if (topLevelOnly) {
3059 return NO_ERROR;
3060 }
3061
Chia-I Wu98f1c102017-05-30 14:54:08 -07003062 sp<Layer> ancestor = p;
3063 while (ancestor->getParent() != nullptr) {
3064 ancestor = ancestor->getParent();
3065 }
3066 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3067 ALOGE("removeLayer called with a layer whose parent has been removed");
3068 return NAME_NOT_FOUND;
3069 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003070
3071 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003072 } else {
3073 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003074 }
3075
Robert Carr136e2f62017-02-08 17:54:29 -08003076 // As a matter of normal operation, the LayerCleaner will produce a second
3077 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3078 // so we will succeed in promoting it, but it's already been removed
3079 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3080 // otherwise something has gone wrong and we are leaking the layer.
3081 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003082 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3083 layer->getName().string(),
3084 (p != nullptr) ? p->getName().string() : "no-parent");
3085 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003086 } else if (index < 0) {
3087 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003088 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003089
Chia-I Wuc6657022017-08-15 11:18:17 -07003090 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003091 mLayersPendingRemoval.add(layer);
3092 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003093 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003094 setTransactionFlags(eTransactionNeeded);
3095 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003096}
3097
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003098uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003099 return android_atomic_release_load(&mTransactionFlags);
3100}
3101
Mathias Agopian3f844832013-08-07 21:24:32 -07003102uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003103 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3104}
3105
Mathias Agopian3f844832013-08-07 21:24:32 -07003106uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003107 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3108}
3109
3110uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3111 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003112 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003113 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003114 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003115 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003116 }
3117 return old;
3118}
3119
chaviwca27f252018-02-06 16:46:39 -08003120bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3121 for (const ComposerState& state : states) {
3122 // Here we need to check that the interface we're given is indeed
3123 // one of our own. A malicious client could give us a nullptr
3124 // IInterface, or one of its own or even one of our own but a
3125 // different type. All these situations would cause us to crash.
3126 if (state.client == nullptr) {
3127 return true;
3128 }
3129
3130 sp<IBinder> binder = IInterface::asBinder(state.client);
3131 if (binder == nullptr) {
3132 return true;
3133 }
3134
3135 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3136 return true;
3137 }
3138 }
3139 return false;
3140}
3141
Mathias Agopian8b33f032012-07-24 20:43:54 -07003142void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003143 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003144 const Vector<DisplayState>& displays,
3145 uint32_t flags)
3146{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003147 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003148 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003149 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003150
chaviwca27f252018-02-06 16:46:39 -08003151 if (containsAnyInvalidClientState(states)) {
3152 return;
3153 }
3154
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003155 if (flags & eAnimation) {
3156 // For window updates that are part of an animation we must wait for
3157 // previous animation "frames" to be handled.
3158 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003159 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003160 if (CC_UNLIKELY(err != NO_ERROR)) {
3161 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003162 // caller after a few seconds.
3163 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3164 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003165 mAnimTransactionPending = false;
3166 break;
3167 }
3168 }
3169 }
3170
chaviwca27f252018-02-06 16:46:39 -08003171 for (const DisplayState& display : displays) {
3172 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003173 }
3174
chaviwca27f252018-02-06 16:46:39 -08003175 for (const ComposerState& state : states) {
3176 transactionFlags |= setClientStateLocked(state);
3177 }
3178
3179 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3180 // as destroyed should only occur after setting all other states. This is to allow for a
3181 // child re-parent to happen before marking its original parent as destroyed (which would
3182 // then mark the child as destroyed).
3183 for (const ComposerState& state : states) {
3184 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003185 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003186
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003187 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3188 // anyway. This can be used as a flush mechanism for previous async transactions.
3189 // Empty animation transaction can be used to simulate back-pressure, so also force a
3190 // transaction for empty animation transactions.
3191 if (transactionFlags == 0 &&
3192 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003193 transactionFlags = eTransactionNeeded;
3194 }
3195
Mathias Agopian386aa982011-11-07 21:58:03 -08003196 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003197 if (mInterceptor->isEnabled()) {
3198 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003199 }
Irvel468051e2016-06-13 16:44:44 -07003200
Mathias Agopian386aa982011-11-07 21:58:03 -08003201 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003202 const auto start = (flags & eEarlyWakeup)
3203 ? VSyncModulator::TransactionStart::EARLY
3204 : VSyncModulator::TransactionStart::NORMAL;
3205 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003206
3207 // if this is a synchronous transaction, wait for it to take effect
3208 // before returning.
3209 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003210 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003211 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003212 if (flags & eAnimation) {
3213 mAnimTransactionPending = true;
3214 }
3215 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003216 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3217 if (CC_UNLIKELY(err != NO_ERROR)) {
3218 // just in case something goes wrong in SF, return to the
3219 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003220 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3221 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003222 break;
3223 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003224 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003225 }
3226}
3227
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003228uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3229 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3230 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003231
Mathias Agopiane57f2922012-08-09 16:29:12 -07003232 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003233 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3234
3235 const uint32_t what = s.what;
3236 if (what & DisplayState::eSurfaceChanged) {
3237 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3238 state.surface = s.surface;
3239 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003240 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003241 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003242 if (what & DisplayState::eLayerStackChanged) {
3243 if (state.layerStack != s.layerStack) {
3244 state.layerStack = s.layerStack;
3245 flags |= eDisplayTransactionNeeded;
3246 }
3247 }
3248 if (what & DisplayState::eDisplayProjectionChanged) {
3249 if (state.orientation != s.orientation) {
3250 state.orientation = s.orientation;
3251 flags |= eDisplayTransactionNeeded;
3252 }
3253 if (state.frame != s.frame) {
3254 state.frame = s.frame;
3255 flags |= eDisplayTransactionNeeded;
3256 }
3257 if (state.viewport != s.viewport) {
3258 state.viewport = s.viewport;
3259 flags |= eDisplayTransactionNeeded;
3260 }
3261 }
3262 if (what & DisplayState::eDisplaySizeChanged) {
3263 if (state.width != s.width) {
3264 state.width = s.width;
3265 flags |= eDisplayTransactionNeeded;
3266 }
3267 if (state.height != s.height) {
3268 state.height = s.height;
3269 flags |= eDisplayTransactionNeeded;
3270 }
3271 }
3272
Mathias Agopiane57f2922012-08-09 16:29:12 -07003273 return flags;
3274}
3275
Robert Carrd4ae7f32018-06-07 16:10:57 -07003276bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3277 IPCThreadState* ipc = IPCThreadState::self();
3278 const int pid = ipc->getCallingPid();
3279 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003280 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003281 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003282 return false;
3283 }
3284 return true;
3285}
3286
chaviwca27f252018-02-06 16:46:39 -08003287uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3288 const layer_state_t& s = composerState.state;
3289 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3290
Mathias Agopian13127d82013-03-05 17:47:11 -08003291 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003292 if (layer == nullptr) {
3293 return 0;
3294 }
3295
3296 if (layer->isPendingRemoval()) {
3297 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3298 return 0;
3299 }
3300
3301 uint32_t flags = 0;
3302
3303 const uint32_t what = s.what;
3304 bool geometryAppliesWithResize =
3305 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003306
3307 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3308 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003309 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003310 layer->pushPendingState();
3311 }
3312
chaviw8b3871a2017-11-01 17:41:01 -07003313 if (what & layer_state_t::ePositionChanged) {
3314 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3315 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003316 }
chaviw8b3871a2017-11-01 17:41:01 -07003317 }
3318 if (what & layer_state_t::eLayerChanged) {
3319 // NOTE: index needs to be calculated before we update the state
3320 const auto& p = layer->getParent();
3321 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003322 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003323 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003324 mCurrentState.layersSortedByZ.removeAt(idx);
3325 mCurrentState.layersSortedByZ.add(layer);
3326 // we need traversal (state changed)
3327 // AND transaction (list changed)
3328 flags |= eTransactionNeeded|eTraversalNeeded;
3329 }
chaviw8b3871a2017-11-01 17:41:01 -07003330 } else {
3331 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003332 flags |= eTransactionNeeded|eTraversalNeeded;
3333 }
3334 }
chaviw8b3871a2017-11-01 17:41:01 -07003335 }
3336 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003337 // NOTE: index needs to be calculated before we update the state
3338 const auto& p = layer->getParent();
3339 if (p == nullptr) {
3340 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3341 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3342 mCurrentState.layersSortedByZ.removeAt(idx);
3343 mCurrentState.layersSortedByZ.add(layer);
3344 // we need traversal (state changed)
3345 // AND transaction (list changed)
3346 flags |= eTransactionNeeded|eTraversalNeeded;
3347 }
3348 } else {
3349 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3350 flags |= eTransactionNeeded|eTraversalNeeded;
3351 }
chaviw8b3871a2017-11-01 17:41:01 -07003352 }
3353 }
3354 if (what & layer_state_t::eSizeChanged) {
3355 if (layer->setSize(s.w, s.h)) {
3356 flags |= eTraversalNeeded;
3357 }
3358 }
3359 if (what & layer_state_t::eAlphaChanged) {
3360 if (layer->setAlpha(s.alpha))
3361 flags |= eTraversalNeeded;
3362 }
3363 if (what & layer_state_t::eColorChanged) {
3364 if (layer->setColor(s.color))
3365 flags |= eTraversalNeeded;
3366 }
3367 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003368 // TODO: b/109894387
3369 //
3370 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3371 // rotation. To see the problem observe that if we have a square parent, and a child
3372 // of the same size, then we rotate the child 45 degrees around it's center, the child
3373 // must now be cropped to a non rectangular 8 sided region.
3374 //
3375 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3376 // private API, and the WindowManager only uses rotation in one case, which is on a top
3377 // level layer in which cropping is not an issue.
3378 //
3379 // However given that abuse of rotation matrices could lead to surfaces extending outside
3380 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3381 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3382 // transformations.
3383 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003384 flags |= eTraversalNeeded;
3385 }
3386 if (what & layer_state_t::eTransparentRegionChanged) {
3387 if (layer->setTransparentRegionHint(s.transparentRegion))
3388 flags |= eTraversalNeeded;
3389 }
3390 if (what & layer_state_t::eFlagsChanged) {
3391 if (layer->setFlags(s.flags, s.mask))
3392 flags |= eTraversalNeeded;
3393 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003394 if (what & layer_state_t::eCropChanged_legacy) {
3395 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003396 flags |= eTraversalNeeded;
3397 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003398 if (what & layer_state_t::eFinalCropChanged_legacy) {
3399 if (layer->setFinalCrop_legacy(s.finalCrop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003400 flags |= eTraversalNeeded;
3401 }
3402 if (what & layer_state_t::eLayerStackChanged) {
3403 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3404 // We only allow setting layer stacks for top level layers,
3405 // everything else inherits layer stack from its parent.
3406 if (layer->hasParent()) {
3407 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3408 layer->getName().string());
3409 } else if (idx < 0) {
3410 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3411 "that also does not appear in the top level layer list. Something"
3412 " has gone wrong.", layer->getName().string());
3413 } else if (layer->setLayerStack(s.layerStack)) {
3414 mCurrentState.layersSortedByZ.removeAt(idx);
3415 mCurrentState.layersSortedByZ.add(layer);
3416 // we need traversal (state changed)
3417 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003418 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003419 }
3420 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003421 if (what & layer_state_t::eDeferTransaction_legacy) {
3422 if (s.barrierHandle_legacy != nullptr) {
3423 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3424 } else if (s.barrierGbp_legacy != nullptr) {
3425 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003426 if (authenticateSurfaceTextureLocked(gbp)) {
3427 const auto& otherLayer =
3428 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003429 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003430 } else {
3431 ALOGE("Attempt to defer transaction to to an"
3432 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003433 }
3434 }
chaviw8b3871a2017-11-01 17:41:01 -07003435 // We don't trigger a traversal here because if no other state is
3436 // changed, we don't want this to cause any more work
3437 }
3438 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003439 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003440 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003441 if (!hadParent) {
3442 mCurrentState.layersSortedByZ.remove(layer);
3443 }
chaviw8b3871a2017-11-01 17:41:01 -07003444 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003445 }
chaviw8b3871a2017-11-01 17:41:01 -07003446 }
3447 if (what & layer_state_t::eReparentChildren) {
3448 if (layer->reparentChildren(s.reparentHandle)) {
3449 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003450 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003451 }
chaviw8b3871a2017-11-01 17:41:01 -07003452 if (what & layer_state_t::eDetachChildren) {
3453 layer->detachChildren();
3454 }
3455 if (what & layer_state_t::eOverrideScalingModeChanged) {
3456 layer->setOverrideScalingMode(s.overrideScalingMode);
3457 // We don't trigger a traversal here because if no other state is
3458 // changed, we don't want this to cause any more work
3459 }
Marissa Wall61c58622018-07-18 10:12:20 -07003460 if (what & layer_state_t::eTransformChanged) {
3461 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3462 }
3463 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3464 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3465 flags |= eTraversalNeeded;
3466 }
3467 if (what & layer_state_t::eCropChanged) {
3468 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3469 }
3470 if (what & layer_state_t::eBufferChanged) {
3471 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3472 }
3473 if (what & layer_state_t::eAcquireFenceChanged) {
3474 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3475 }
3476 if (what & layer_state_t::eDataspaceChanged) {
3477 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3478 }
3479 if (what & layer_state_t::eHdrMetadataChanged) {
3480 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3481 }
3482 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3483 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3484 }
3485 if (what & layer_state_t::eApiChanged) {
3486 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3487 }
3488 if (what & layer_state_t::eSidebandStreamChanged) {
3489 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3490 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003491 return flags;
3492}
3493
chaviwca27f252018-02-06 16:46:39 -08003494void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3495 const layer_state_t& state = composerState.state;
3496 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3497
3498 sp<Layer> layer(client->getLayerUser(state.surface));
3499 if (layer == nullptr) {
3500 return;
3501 }
3502
3503 if (layer->isPendingRemoval()) {
3504 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3505 return;
3506 }
3507
3508 if (state.what & layer_state_t::eDestroySurface) {
3509 removeLayerLocked(mStateLock, layer);
3510 }
3511}
3512
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003513status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003514 const String8& name,
3515 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003516 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003517 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003518 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003519{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003520 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003521 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003522 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003523 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003524 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003525
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003526 status_t result = NO_ERROR;
3527
3528 sp<Layer> layer;
3529
Cody Northropbc755282017-03-31 12:00:08 -06003530 String8 uniqueName = getUniqueLayerName(name);
3531
Mathias Agopian3165cc22012-08-08 19:42:09 -07003532 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003533 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003534 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3535 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003536
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003537 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003538 case ISurfaceComposerClient::eFXSurfaceBufferState:
3539 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3540 break;
chaviw13fdc492017-06-27 12:40:18 -07003541 case ISurfaceComposerClient::eFXSurfaceColor:
3542 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003543 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003544 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003545 break;
3546 default:
3547 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003548 break;
3549 }
3550
Dan Stoza7d89d062015-04-30 13:29:25 -07003551 if (result != NO_ERROR) {
3552 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003553 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003554
Chia-I Wuab0c3192017-08-01 11:29:00 -07003555 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3556 // TODO b/64227542
3557 if (windowType == 441731) {
3558 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3559 layer->setPrimaryDisplayOnly();
3560 }
3561
Albert Chaulk479c60c2017-01-27 14:21:34 -05003562 layer->setInfo(windowType, ownerUid);
3563
Robert Carr1f0a16a2016-10-24 16:27:39 -07003564 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003565 if (result != NO_ERROR) {
3566 return result;
3567 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003568 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003569
3570 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003571 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003572}
3573
Cody Northropbc755282017-03-31 12:00:08 -06003574String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3575{
3576 bool matchFound = true;
3577 uint32_t dupeCounter = 0;
3578
3579 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3580 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3581
Dan Stoza436ccf32018-06-21 12:10:12 -07003582 // Grab the state lock since we're accessing mCurrentState
3583 Mutex::Autolock lock(mStateLock);
3584
Cody Northropbc755282017-03-31 12:00:08 -06003585 // Loop over layers until we're sure there is no matching name
3586 while (matchFound) {
3587 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003588 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003589 if (layer->getName() == uniqueName) {
3590 matchFound = true;
3591 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3592 }
3593 });
3594 }
3595
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003596 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3597 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003598
3599 return uniqueName;
3600}
3601
Marissa Wallfd668622018-05-10 10:21:13 -07003602status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3603 uint32_t w, uint32_t h, uint32_t flags,
3604 PixelFormat& format, sp<IBinder>* handle,
3605 sp<IGraphicBufferProducer>* gbp,
3606 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003607 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003608 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003609 case PIXEL_FORMAT_TRANSPARENT:
3610 case PIXEL_FORMAT_TRANSLUCENT:
3611 format = PIXEL_FORMAT_RGBA_8888;
3612 break;
3613 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003614 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003615 break;
3616 }
3617
Marissa Wallfd668622018-05-10 10:21:13 -07003618 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3619 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003620 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003621 *handle = layer->getHandle();
3622 *gbp = layer->getProducer();
3623 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003624 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003625
Marissa Wallfd668622018-05-10 10:21:13 -07003626 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003627 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003628}
3629
Marissa Wall61c58622018-07-18 10:12:20 -07003630status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3631 uint32_t w, uint32_t h, uint32_t flags,
3632 sp<IBinder>* handle, sp<Layer>* outLayer) {
3633 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3634 *handle = layer->getHandle();
3635 *outLayer = layer;
3636
3637 return NO_ERROR;
3638}
3639
chaviw13fdc492017-06-27 12:40:18 -07003640status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003641 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003642 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003643{
chaviw13fdc492017-06-27 12:40:18 -07003644 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003645 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003646 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003647}
3648
Mathias Agopianac9fa422013-02-11 16:40:36 -08003649status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003650{
Robert Carr9524cb32017-02-13 11:32:32 -08003651 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003652 status_t err = NO_ERROR;
3653 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003654 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003655 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003656 err = removeLayer(l);
3657 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3658 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003659 }
3660 return err;
3661}
3662
Mathias Agopian13127d82013-03-05 17:47:11 -08003663status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003664{
Mathias Agopian67106042013-03-14 19:18:13 -07003665 // called by ~LayerCleaner() when all references to the IBinder (handle)
3666 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003667 sp<Layer> l = layer.promote();
3668 if (l == nullptr) {
3669 // The layer has already been removed, carry on
3670 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003671 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003672 // If we have a parent, then we can continue to live as long as it does.
3673 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003674}
3675
Mathias Agopianb60314a2012-04-10 22:09:54 -07003676// ---------------------------------------------------------------------------
3677
Andy McFadden13a082e2012-08-24 10:16:42 -07003678void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003679 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3680 if (!displayToken) return;
3681
Jesse Hall01e29052013-02-19 16:13:35 -08003682 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003683 Vector<ComposerState> state;
3684 Vector<DisplayState> displays;
3685 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003686 d.what = DisplayState::eDisplayProjectionChanged |
3687 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003688 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003689 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003690 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003691 d.frame.makeInvalid();
3692 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003693 d.width = 0;
3694 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003695 displays.add(d);
3696 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003697
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003698 const auto display = getDisplayDevice(displayToken);
3699 if (!display) return;
3700
3701 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3702
3703 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003704 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003705 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003706
Brian Andersond0010582017-03-07 13:20:31 -08003707 // Use phase of 0 since phase is not known.
3708 // Use latency of 0, which will snap to the ideal latency.
3709 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003710}
3711
3712void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003713 // Async since we may be called from the main thread.
3714 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003715}
3716
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003717void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3718 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003719 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003720 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003721
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003722 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003723 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003724 return;
3725 }
3726
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003727 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003728 ALOGW("Trying to set power mode for virtual display");
3729 return;
3730 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003731
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003732 display->setPowerMode(mode);
3733
Lloyd Pique4dccc412018-01-22 17:21:36 -08003734 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003735 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003736 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003737 if (idx < 0) {
3738 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3739 return;
3740 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003741 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003742 }
3743
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003744 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003745 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003746 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003747 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003748 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003749 // FIXME: eventthread only knows about the main display right now
3750 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003751 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003752 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003753
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003754 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003755 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003756 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003757
3758 struct sched_param param = {0};
3759 param.sched_priority = 1;
3760 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3761 ALOGW("Couldn't set SCHED_FIFO on display on");
3762 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003763 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003764 // Turn off the display
3765 struct sched_param param = {0};
3766 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3767 ALOGW("Couldn't set SCHED_OTHER on display off");
3768 }
3769
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003770 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003771 disableHardwareVsync(true); // also cancels any in-progress resync
3772
Mathias Agopiancde87a32012-09-13 14:09:01 -07003773 // FIXME: eventthread only knows about the main display right now
3774 mEventThread->onScreenReleased();
3775 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003776
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003777 getHwComposer().setPowerMode(type, mode);
3778 mVisibleRegionsDirty = true;
3779 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003780 } else if (mode == HWC_POWER_MODE_DOZE ||
3781 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003782 // Update display while dozing
3783 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003784 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003785 // FIXME: eventthread only knows about the main display right now
3786 mEventThread->onScreenAcquired();
3787 resyncToHardwareVsync(true);
3788 }
3789 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3790 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003791 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003792 disableHardwareVsync(true); // also cancels any in-progress resync
3793 // FIXME: eventthread only knows about the main display right now
3794 mEventThread->onScreenReleased();
3795 }
3796 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003797 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003798 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003799 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003800 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003801
3802 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003803}
3804
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003805void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003806 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003807 const auto display = getDisplayDevice(displayToken);
3808 if (!display) {
3809 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3810 displayToken.get());
3811 } else if (display->isVirtual()) {
3812 ALOGW("Attempt to set power mode %d for virtual display", mode);
3813 } else {
3814 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003815 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003816 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003817}
3818
3819// ---------------------------------------------------------------------------
3820
Lloyd Pique755e3192018-01-31 16:46:15 -08003821status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3822 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003823 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003824
Mathias Agopianbd115332013-04-18 16:41:04 -07003825 IPCThreadState* ipc = IPCThreadState::self();
3826 const int pid = ipc->getCallingPid();
3827 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003828
Mathias Agopianbd115332013-04-18 16:41:04 -07003829 if ((uid != AID_SHELL) &&
3830 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003831 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003832 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003833 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003834 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003835 // (this would indicate SF is stuck, but we want to be able to
3836 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003837 status_t err = mStateLock.timedLock(s2ns(1));
3838 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003839 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003840 result.appendFormat(
3841 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3842 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003843 }
3844
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003845 bool dumpAll = true;
3846 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003847 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003848
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003849 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003850 if ((index < numArgs) &&
3851 (args[index] == String16("--list"))) {
3852 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003853 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003854 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003855 }
3856
3857 if ((index < numArgs) &&
3858 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003859 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003860 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003861 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003862 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003863
3864 if ((index < numArgs) &&
3865 (args[index] == String16("--latency-clear"))) {
3866 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003867 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003868 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003869 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003870
3871 if ((index < numArgs) &&
3872 (args[index] == String16("--dispsync"))) {
3873 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07003874 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07003875 dumpAll = false;
3876 }
Dan Stozab90cf072015-03-05 11:05:59 -08003877
3878 if ((index < numArgs) &&
3879 (args[index] == String16("--static-screen"))) {
3880 index++;
3881 dumpStaticScreenStats(result);
3882 dumpAll = false;
3883 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003884
3885 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003886 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003887 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003888 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003889 dumpAll = false;
3890 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003891
3892 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3893 index++;
3894 dumpWideColorInfo(result);
3895 dumpAll = false;
3896 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003897
3898 if ((index < numArgs) &&
3899 (args[index] == String16("--enable-layer-stats"))) {
3900 index++;
3901 mLayerStats.enable();
3902 dumpAll = false;
3903 }
3904
3905 if ((index < numArgs) &&
3906 (args[index] == String16("--disable-layer-stats"))) {
3907 index++;
3908 mLayerStats.disable();
3909 dumpAll = false;
3910 }
3911
3912 if ((index < numArgs) &&
3913 (args[index] == String16("--clear-layer-stats"))) {
3914 index++;
3915 mLayerStats.clear();
3916 dumpAll = false;
3917 }
3918
3919 if ((index < numArgs) &&
3920 (args[index] == String16("--dump-layer-stats"))) {
3921 index++;
3922 mLayerStats.dump(result);
3923 dumpAll = false;
3924 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003925
3926 if ((index < numArgs) &&
3927 (args[index] == String16("--display-identification"))) {
3928 index++;
3929 dumpDisplayIdentificationData(result);
3930 dumpAll = false;
3931 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003932
3933 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3934 index++;
3935 mTimeStats.parseArgs(asProto, args, index, result);
3936 dumpAll = false;
3937 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003938 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003939
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003940 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003941 if (asProto) {
3942 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3943 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3944 } else {
3945 dumpAllLocked(args, index, result);
3946 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003947 }
3948
Mathias Agopian9795c422009-08-26 16:36:26 -07003949 if (locked) {
3950 mStateLock.unlock();
3951 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003952 }
3953 write(fd, result.string(), result.size());
3954 return NO_ERROR;
3955}
3956
Dan Stozac7014012014-02-14 15:03:43 -08003957void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3958 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003959{
Robert Carr2047fae2016-11-28 14:09:09 -08003960 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003961 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003962 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003963}
3964
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003965void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003966 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003967{
3968 String8 name;
3969 if (index < args.size()) {
3970 name = String8(args[index]);
3971 index++;
3972 }
3973
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003974 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
3975 getHwComposer().isConnected(displayId)) {
3976 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
3977 const nsecs_t period = activeConfig->getVsyncPeriod();
3978 result.appendFormat("%" PRId64 "\n", period);
3979 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003980
3981 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003982 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003983 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003984 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003985 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003986 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003987 }
Robert Carr2047fae2016-11-28 14:09:09 -08003988 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003989 }
3990}
3991
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003992void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003993 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003994{
3995 String8 name;
3996 if (index < args.size()) {
3997 name = String8(args[index]);
3998 index++;
3999 }
4000
Robert Carr2047fae2016-11-28 14:09:09 -08004001 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004002 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004003 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004004 }
Robert Carr2047fae2016-11-28 14:09:09 -08004005 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004006
Svetoslavd85084b2014-03-20 10:28:31 -07004007 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004008}
4009
Jamie Gennis6547ff42013-07-16 20:12:42 -07004010// This should only be called from the main thread. Otherwise it would need
4011// the lock and should use mCurrentState rather than mDrawingState.
4012void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004013 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004014 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004015 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004016
4017 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4018}
4019
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004020void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004021{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004022 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004023
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004024 if (isLayerTripleBufferingDisabled())
4025 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004026
4027 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004028 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004029 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004030 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004031 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4032 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004033 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004034}
4035
Dan Stozab90cf072015-03-05 11:05:59 -08004036void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4037{
4038 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004039 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4040 float bucketTimeSec = getBE().mFrameBuckets[b] / 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[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004043 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4044 b + 1, bucketTimeSec, percent);
4045 }
David Sodman4a36e932017-11-07 14:29:47 -08004046 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004047 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004048 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004049 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004050 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004051}
4052
Dan Stozae77c7662016-05-13 11:37:28 -07004053void SurfaceFlinger::recordBufferingStats(const char* layerName,
4054 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004055 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4056 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004057 for (const auto& segment : history) {
4058 if (!segment.usedThirdBuffer) {
4059 stats.twoBufferTime += segment.totalTime;
4060 }
4061 if (segment.occupancyAverage < 1.0f) {
4062 stats.doubleBufferedTime += segment.totalTime;
4063 } else if (segment.occupancyAverage < 2.0f) {
4064 stats.tripleBufferedTime += segment.totalTime;
4065 }
4066 ++stats.numSegments;
4067 stats.totalTime += segment.totalTime;
4068 }
4069}
4070
Brian Andersond6927fb2016-07-23 23:37:30 -07004071void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4072 result.appendFormat("Layer frame timestamps:\n");
4073
4074 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4075 const size_t count = currentLayers.size();
4076 for (size_t i=0 ; i<count ; i++) {
4077 currentLayers[i]->dumpFrameEvents(result);
4078 }
4079}
4080
Dan Stozae77c7662016-05-13 11:37:28 -07004081void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4082 result.append("Buffering stats:\n");
4083 result.append(" [Layer name] <Active time> <Two buffer> "
4084 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004085 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004086 typedef std::tuple<std::string, float, float, float> BufferTuple;
4087 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004088 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004089 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004090 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004091 if (stats.numSegments == 0) {
4092 continue;
4093 }
4094 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4095 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4096 stats.totalTime;
4097 float doubleBufferRatio = static_cast<float>(
4098 stats.doubleBufferedTime) / stats.totalTime;
4099 float tripleBufferRatio = static_cast<float>(
4100 stats.tripleBufferedTime) / stats.totalTime;
4101 sorted.insert({activeTime, {name, twoBufferRatio,
4102 doubleBufferRatio, tripleBufferRatio}});
4103 }
4104 for (const auto& sortedPair : sorted) {
4105 float activeTime = sortedPair.first;
4106 const BufferTuple& values = sortedPair.second;
4107 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4108 std::get<0>(values).c_str(), activeTime,
4109 std::get<1>(values), std::get<2>(values),
4110 std::get<3>(values));
4111 }
4112 result.append("\n");
4113}
4114
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004115void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004116 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004117 const int32_t displayId = display->getId();
4118 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4119 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004120 continue;
4121 }
4122
Dominik Laskowski7e045462018-05-30 13:02:02 -07004123 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004124 uint8_t port;
4125 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004126 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004127 result.append("no identification data\n");
4128 continue;
4129 }
4130
4131 if (!isEdid(data)) {
4132 result.append("unknown identification data: ");
4133 for (uint8_t byte : data) {
4134 result.appendFormat("%x ", byte);
4135 }
4136 result.append("\n");
4137 continue;
4138 }
4139
4140 const auto edid = parseEdid(data);
4141 if (!edid) {
4142 result.append("invalid EDID: ");
4143 for (uint8_t byte : data) {
4144 result.appendFormat("%x ", byte);
4145 }
4146 result.append("\n");
4147 continue;
4148 }
4149
4150 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4151 result.append(edid->displayName.data(), edid->displayName.length());
4152 result.append("\"\n");
4153 }
4154 result.append("\n");
4155}
4156
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004157void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004158 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4159 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004160 result.appendFormat("DisplayColorSetting: %s\n",
4161 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004162
4163 // TODO: print out if wide-color mode is active or not
4164
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004165 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004166 const int32_t displayId = display->getId();
4167 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004168 continue;
4169 }
4170
Dominik Laskowski7e045462018-05-30 13:02:02 -07004171 result.appendFormat("Display %d color modes:\n", displayId);
4172 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004173 for (auto&& mode : modes) {
4174 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4175 }
4176
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004177 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004178 result.appendFormat(" Current color mode: %s (%d)\n",
4179 decodeColorMode(currentMode).c_str(), currentMode);
4180 }
4181 result.append("\n");
4182}
4183
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004184LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004185 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004186 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4187 const State& state = useDrawing ? mDrawingState : mCurrentState;
4188 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004189 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004190 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004191 });
4192
4193 return layersProto;
4194}
4195
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004196LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004197 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004198
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004199 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004200 resolution->set_w(display.getWidth());
4201 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004202
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004203 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4204 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4205 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004206
Dominik Laskowski7e045462018-05-30 13:02:02 -07004207 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004208 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004209 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004210 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004211 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004212 }
4213 });
4214
4215 return layersProto;
4216}
4217
Mathias Agopian74d211a2013-04-22 16:55:35 +02004218void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4219 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004220{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004221 bool colorize = false;
4222 if (index < args.size()
4223 && (args[index] == String16("--color"))) {
4224 colorize = true;
4225 index++;
4226 }
4227
4228 Colorizer colorizer(colorize);
4229
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004230 // figure out if we're stuck somewhere
4231 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004232 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004233 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4234
4235 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004236 * Dump library configuration.
4237 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004238
4239 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004240 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004241 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004242 appendSfConfigString(result);
4243 appendUiConfigString(result);
4244 appendGuiConfigString(result);
4245 result.append("\n");
4246
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004247 result.append("\nDisplay identification data:\n");
4248 dumpDisplayIdentificationData(result);
4249
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004250 result.append("\nWide-Color information:\n");
4251 dumpWideColorInfo(result);
4252
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004253 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004254 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004255 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004256 result.append(SyncFeatures::getInstance().toString());
4257 result.append("\n");
4258
Andy McFadden41d67d72014-04-25 16:58:34 -07004259 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004260 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004261 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004262
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004263 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4264 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004265 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4266 getHwComposer().isConnected(displayId)) {
4267 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004268 result.appendFormat("Display %d: "
4269 "app phase %" PRId64 " ns, "
4270 "sf phase %" PRId64 " ns, "
4271 "early app phase %" PRId64 " ns, "
4272 "early sf phase %" PRId64 " ns, "
4273 "early app gl phase %" PRId64 " ns, "
4274 "early sf gl phase %" PRId64 " ns, "
4275 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4276 displayId,
4277 vsyncPhaseOffsetNs,
4278 sfVsyncPhaseOffsetNs,
4279 appEarlyOffset,
4280 sfEarlyOffset,
4281 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004282 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004283 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004284 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004285 result.append("\n");
4286
Dan Stozab90cf072015-03-05 11:05:59 -08004287 // Dump static screen stats
4288 result.append("\n");
4289 dumpStaticScreenStats(result);
4290 result.append("\n");
4291
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004292 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4293
Dan Stozae77c7662016-05-13 11:37:28 -07004294 dumpBufferingStats(result);
4295
Andy McFadden4803b742012-09-24 19:07:20 -07004296 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004297 * Dump the visible layer list
4298 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004299 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004300 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004301 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4302 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004303 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004304
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004305 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004306 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004307 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004308 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004309
4310 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004311 * Dump Display state
4312 */
4313
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004314 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004315 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004316 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004317 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004318 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004319 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004320 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004321
4322 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004323 * Dump SurfaceFlinger global state
4324 */
4325
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004326 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004327 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004328 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004329
Mathias Agopian888c8222012-08-04 21:10:38 -07004330 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004331 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004332
David Sodmanbc815282017-11-05 18:57:52 -08004333 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004334
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004335 if (display) {
4336 display->undefinedRegion.dump(result, "undefinedRegion");
4337 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4338 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004339 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004340 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004341 " gpu_to_cpu_unsupported : %d\n",
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004342 mTransactionFlags, !mGpuToCpuSupported);
4343
4344 if (display) {
4345 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4346 result.appendFormat(" refresh-rate : %f fps\n"
4347 " x-dpi : %f\n"
4348 " y-dpi : %f\n",
4349 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4350 activeConfig->getDpiY());
4351 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004352
Mathias Agopian74d211a2013-04-22 16:55:35 +02004353 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004354 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004355
4356 /*
4357 * VSYNC state
4358 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004359 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004360 result.append("\n");
4361
4362 /*
4363 * HWC layer minidump
4364 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004365 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004366 const int32_t displayId = display->getId();
4367 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004368 continue;
4369 }
4370
Dominik Laskowski7e045462018-05-30 13:02:02 -07004371 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004372 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004373 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004374 result.append("\n");
4375 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004376
4377 /*
4378 * Dump HWComposer state
4379 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004380 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004381 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004382 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004383 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004384 result.appendFormat(" h/w composer %s\n",
4385 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004386 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004387
4388 /*
4389 * Dump gralloc state
4390 */
4391 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4392 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004393
4394 /*
4395 * Dump VrFlinger state if in use.
4396 */
4397 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4398 result.append("VrFlinger state:\n");
4399 result.append(mVrFlinger->Dump().c_str());
4400 result.append("\n");
4401 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004402}
4403
Dominik Laskowski7e045462018-05-30 13:02:02 -07004404const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004405 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004406 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004407 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004408 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004409 }
4410 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004411
4412 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4413 static const Vector<sp<Layer>> empty;
4414 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004415}
4416
Keun young Park63f165f2012-08-31 10:53:36 -07004417bool SurfaceFlinger::startDdmConnection()
4418{
4419 void* libddmconnection_dso =
4420 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4421 if (!libddmconnection_dso) {
4422 return false;
4423 }
4424 void (*DdmConnection_start)(const char* name);
4425 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004426 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004427 if (!DdmConnection_start) {
4428 dlclose(libddmconnection_dso);
4429 return false;
4430 }
4431 (*DdmConnection_start)(getServiceName());
4432 return true;
4433}
4434
Chia-I Wu28f320b2018-05-03 11:02:56 -07004435void SurfaceFlinger::updateColorMatrixLocked() {
4436 mat4 colorMatrix;
4437 if (mGlobalSaturationFactor != 1.0f) {
4438 // Rec.709 luma coefficients
4439 float3 luminance{0.213f, 0.715f, 0.072f};
4440 luminance *= 1.0f - mGlobalSaturationFactor;
4441 mat4 saturationMatrix = mat4(
4442 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4443 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4444 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4445 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4446 );
4447 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4448 } else {
4449 colorMatrix = mClientColorMatrix * mDaltonizer();
4450 }
4451
4452 if (mCurrentState.colorMatrix != colorMatrix) {
4453 mCurrentState.colorMatrix = colorMatrix;
4454 mCurrentState.colorMatrixChanged = true;
4455 setTransactionFlags(eTransactionNeeded);
4456 }
4457}
4458
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004459status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004460#pragma clang diagnostic push
4461#pragma clang diagnostic error "-Wswitch-enum"
4462 switch (static_cast<ISurfaceComposerTag>(code)) {
4463 // These methods should at minimum make sure that the client requested
4464 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004465 case BOOT_FINISHED:
4466 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004467 case CREATE_CONNECTION:
4468 case CREATE_DISPLAY:
4469 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004470 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004471 case GET_ACTIVE_COLOR_MODE:
4472 case GET_ANIMATION_FRAME_STATS:
4473 case GET_HDR_CAPABILITIES:
4474 case SET_ACTIVE_CONFIG:
4475 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004476 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004477 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004478 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4479 IPCThreadState* ipc = IPCThreadState::self();
4480 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4481 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004482 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004483 }
Robert Carr1db73f62016-12-21 12:58:51 -08004484 return OK;
4485 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004486 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004487 IPCThreadState* ipc = IPCThreadState::self();
4488 const int pid = ipc->getCallingPid();
4489 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004490 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4491 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004492 return PERMISSION_DENIED;
4493 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004494 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004495 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004496 // Used by apps to hook Choreographer to SurfaceFlinger.
4497 case CREATE_DISPLAY_EVENT_CONNECTION:
4498 // The following calls are currently used by clients that do not
4499 // request necessary permissions. However, they do not expose any secret
4500 // information, so it is OK to pass them.
4501 case AUTHENTICATE_SURFACE:
4502 case GET_ACTIVE_CONFIG:
4503 case GET_BUILT_IN_DISPLAY:
4504 case GET_DISPLAY_COLOR_MODES:
4505 case GET_DISPLAY_CONFIGS:
4506 case GET_DISPLAY_STATS:
Yiwei Zhangcd3f9e92018-08-21 15:15:42 -07004507 case GET_DISPLAY_VIEWPORT:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004508 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4509 // Calling setTransactionState is safe, because you need to have been
4510 // granted a reference to Client* and Handle* to do anything with it.
4511 case SET_TRANSACTION_STATE:
4512 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4513 case CREATE_SCOPED_CONNECTION: {
4514 return OK;
4515 }
4516 case CAPTURE_LAYERS:
4517 case CAPTURE_SCREEN: {
4518 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004519 IPCThreadState* ipc = IPCThreadState::self();
4520 const int pid = ipc->getCallingPid();
4521 const int uid = ipc->getCallingUid();
4522 if ((uid != AID_GRAPHICS) &&
4523 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4524 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4525 return PERMISSION_DENIED;
4526 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004527 return OK;
4528 }
4529 // The following codes are deprecated and should never be allowed to access SF.
4530 case CONNECT_DISPLAY_UNUSED:
4531 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4532 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4533 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004534 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004535 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004536
4537 // These codes are used for the IBinder protocol to either interrogate the recipient
4538 // side of the transaction for its canonical interface descriptor or to dump its state.
4539 // We let them pass by default.
4540 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4541 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4542 code == IBinder::SYSPROPS_TRANSACTION) {
4543 return OK;
4544 }
4545 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4546 // in onTransact verifies that the user is root, and has access to use SF.
4547 if (code >= 1000 && code <= 1029) {
4548 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4549 return OK;
4550 }
4551 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4552 return PERMISSION_DENIED;
4553#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004554}
4555
Ana Krulec13be8ad2018-08-21 02:43:56 +00004556status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4557 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004558 status_t credentialCheck = CheckTransactCodeCredentials(code);
4559 if (credentialCheck != OK) {
4560 return credentialCheck;
4561 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004562
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004563 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4564 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004565 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004566 IPCThreadState* ipc = IPCThreadState::self();
4567 const int uid = ipc->getCallingUid();
4568 if (CC_UNLIKELY(uid != AID_SYSTEM
4569 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004570 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004571 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004572 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004573 return PERMISSION_DENIED;
4574 }
4575 int n;
4576 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004577 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004578 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004579 return NO_ERROR;
4580 case 1002: // SHOW_UPDATES
4581 n = data.readInt32();
4582 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004583 invalidateHwcGeometry();
4584 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004585 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004586 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004587 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004588 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004589 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004590 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004591 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004592 setTransactionFlags(
4593 eTransactionNeeded|
4594 eDisplayTransactionNeeded|
4595 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004596 return NO_ERROR;
4597 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004598 case 1006:{ // send empty update
4599 signalRefresh();
4600 return NO_ERROR;
4601 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004602 case 1008: // toggle use of hw composer
4603 n = data.readInt32();
4604 mDebugDisableHWC = n ? 1 : 0;
4605 invalidateHwcGeometry();
4606 repaintEverything();
4607 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004608 case 1009: // toggle use of transform hint
4609 n = data.readInt32();
4610 mDebugDisableTransformHint = n ? 1 : 0;
4611 invalidateHwcGeometry();
4612 repaintEverything();
4613 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004614 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004615 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004616 reply->writeInt32(0);
4617 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004618 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004619 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004620 return NO_ERROR;
4621 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004622 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004623 if (!display) {
4624 return NAME_NOT_FOUND;
4625 }
4626
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004627 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004628 return NO_ERROR;
4629 }
4630 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004631 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004632 // daltonize
4633 n = data.readInt32();
4634 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004635 case 1:
4636 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4637 break;
4638 case 2:
4639 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4640 break;
4641 case 3:
4642 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4643 break;
4644 default:
4645 mDaltonizer.setType(ColorBlindnessType::None);
4646 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004647 }
4648 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004649 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004650 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004651 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004652 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004653
4654 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004655 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004656 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004657 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004658 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004659 // apply a color matrix
4660 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004661 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004662 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004663 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004664 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004665 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004666 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004667 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004668 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004669 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004670 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004671
4672 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4673 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004674 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004675 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4676 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4677 }
4678
Chia-I Wu28f320b2018-05-03 11:02:56 -07004679 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004680 return NO_ERROR;
4681 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004682 // This is an experimental interface
4683 // Needs to be shifted to proper binder interface when we productize
4684 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004685 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07004686 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004687 return NO_ERROR;
4688 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004689 case 1017: {
4690 n = data.readInt32();
4691 mForceFullDamage = static_cast<bool>(n);
4692 return NO_ERROR;
4693 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004694 case 1018: { // Modify Choreographer's phase offset
4695 n = data.readInt32();
4696 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4697 return NO_ERROR;
4698 }
4699 case 1019: { // Modify SurfaceFlinger's phase offset
4700 n = data.readInt32();
4701 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4702 return NO_ERROR;
4703 }
Irvel468051e2016-06-13 16:44:44 -07004704 case 1020: { // Layer updates interceptor
4705 n = data.readInt32();
4706 if (n) {
4707 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004708 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004709 }
4710 else{
4711 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004712 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004713 }
4714 return NO_ERROR;
4715 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004716 case 1021: { // Disable HWC virtual displays
4717 n = data.readInt32();
4718 mUseHwcVirtualDisplays = !n;
4719 return NO_ERROR;
4720 }
Romain Guy0147a172017-06-01 13:53:56 -07004721 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004722 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004723 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004724
Chia-I Wu28f320b2018-05-03 11:02:56 -07004725 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004726 return NO_ERROR;
4727 }
Romain Guy54f154a2017-10-24 21:40:32 +01004728 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004729 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004730 invalidateHwcGeometry();
4731 repaintEverything();
4732 return NO_ERROR;
4733 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004734 // TODO(b/111505327): Find out whether the usage of 1024 can switch to 1030,
4735 // deprecate 1024 if they can.
4736 case 1024: { // Does device have wide color gamut display?
Romain Guy54f154a2017-10-24 21:40:32 +01004737 reply->writeBool(hasWideColorDisplay);
4738 return NO_ERROR;
4739 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004740 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004741 n = data.readInt32();
4742 if (n) {
4743 ALOGV("LayerTracing enabled");
4744 mTracing.enable();
4745 doTracing("tracing.enable");
4746 reply->writeInt32(NO_ERROR);
4747 } else {
4748 ALOGV("LayerTracing disabled");
4749 status_t err = mTracing.disable();
4750 reply->writeInt32(err);
4751 }
4752 return NO_ERROR;
4753 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004754 case 1026: { // Get layer tracing status
4755 reply->writeBool(mTracing.isEnabled());
4756 return NO_ERROR;
4757 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004758 // Is a DisplayColorSetting supported?
4759 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004760 const auto display = getDefaultDisplayDevice();
4761 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004762 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004763 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004764
4765 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4766 switch (setting) {
4767 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07004768 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004769 break;
4770 case DisplayColorSetting::UNMANAGED:
4771 reply->writeBool(true);
4772 break;
4773 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004774 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004775 break;
4776 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004777 reply->writeBool(
4778 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004779 break;
4780 }
4781 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004782 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004783 // Is VrFlinger active?
4784 case 1028: {
4785 Mutex::Autolock _l(mStateLock);
4786 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4787 return NO_ERROR;
4788 }
David Sodman6d46c1e2018-07-13 12:59:48 -07004789 case 1029: {
4790 // Code 1029 is an experimental feature that allows applications to
4791 // simulate a high frequency panel by setting a multiplier and divisor
4792 // on the VSYNC-sf clock. If either the multiplier or divisor are
4793 // 0, then the code will set both to 1 to return the VSYNC-sf clock
4794 // to it's normal frequency.
4795 int multiplier = data.readInt32();
4796 int divisor = data.readInt32();
4797
4798 if ((multiplier == 0) || (divisor == 0)) {
4799 multiplier = 1;
4800 divisor = 1;
4801 }
4802
4803 if ((multiplier == 1) && (divisor == 1)) {
4804 enableHardwareVsync();
4805 } else {
4806 disableHardwareVsync(true);
4807 }
4808 getBE().mHwc->getActiveConfig(DisplayDevice::DISPLAY_PRIMARY)
4809 ->scalePanelFrequency(multiplier, divisor);
4810 mPrimaryDispSync->scalePeriod(multiplier, divisor);
4811
4812 ATRACE_INT("PeriodMultiplier", multiplier);
4813 ATRACE_INT("PeriodDivisor", divisor);
4814 return NO_ERROR;
4815 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004816 // Is device color managed?
4817 case 1030: {
4818 reply->writeBool(useColorManagement);
4819 return NO_ERROR;
4820 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004821 }
4822 }
4823 return err;
4824}
4825
Steven Thomas6d8110b2017-08-31 18:24:21 -07004826void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004827 android_atomic_or(1, &mRepaintEverything);
4828 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004829}
4830
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004831// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4832class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004833public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004834 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4835 ~WindowDisconnector() {
4836 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004837 }
4838
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004839private:
4840 ANativeWindow* mWindow;
4841 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004842};
4843
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004844status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4845 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4846 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4847 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004848 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004849 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004850
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004851 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004852
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004853 const auto display = getDisplayDeviceLocked(displayToken);
4854 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004855
Yiwei Zhang06a58e22018-08-20 16:42:23 -07004856 const Rect& dispScissor = display->getScissor();
4857 if (!dispScissor.isEmpty()) {
4858 sourceCrop.set(dispScissor);
4859 // adb shell screencap will default reqWidth and reqHeight to zeros.
4860 if (reqWidth == 0 || reqHeight == 0) {
4861 reqWidth = uint32_t(dispScissor.width());
4862 reqHeight = uint32_t(dispScissor.height());
4863 }
4864 }
4865
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004866 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004867
4868 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004869 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004870 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004871}
4872
4873status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004874 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004875 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004876 ATRACE_CALL();
4877
4878 class LayerRenderArea : public RenderArea {
4879 public:
Robert Carr578038f2018-03-09 12:25:24 -08004880 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4881 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004882 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004883 mLayer(layer),
4884 mCrop(crop),
4885 mFlinger(flinger),
4886 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07004887 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004888 Rect getBounds() const override {
4889 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07004890 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07004891 }
Marissa Wall61c58622018-07-18 10:12:20 -07004892 int getHeight() const override {
4893 return mLayer->getActiveHeight(mLayer->getDrawingState());
4894 }
4895 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07004896 bool isSecure() const override { return false; }
4897 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004898 Rect getSourceCrop() const override {
4899 if (mCrop.isEmpty()) {
4900 return getBounds();
4901 } else {
4902 return mCrop;
4903 }
4904 }
Robert Carr578038f2018-03-09 12:25:24 -08004905 class ReparentForDrawing {
4906 public:
4907 const sp<Layer>& oldParent;
4908 const sp<Layer>& newParent;
4909
4910 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4911 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004912 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004913 }
Robert Carr15eae092018-03-23 13:43:53 -07004914 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004915 };
4916
4917 void render(std::function<void()> drawLayers) override {
4918 if (!mChildrenOnly) {
4919 mTransform = mLayer->getTransform().inverse();
4920 drawLayers();
4921 } else {
4922 Rect bounds = getBounds();
4923 screenshotParentLayer =
4924 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4925 bounds.getWidth(), bounds.getHeight(), 0);
4926
4927 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4928 drawLayers();
4929 }
4930 }
chaviwa76b2712017-09-20 12:02:26 -07004931
chaviwa76b2712017-09-20 12:02:26 -07004932 private:
chaviw7206d492017-11-10 16:16:12 -08004933 const sp<Layer> mLayer;
4934 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004935
4936 // In the "childrenOnly" case we reparent the children to a screenshot
4937 // layer which has no properties set and which does not draw.
4938 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07004939 ui::Transform mTransform;
Robert Carr578038f2018-03-09 12:25:24 -08004940
4941 SurfaceFlinger* mFlinger;
4942 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004943 };
4944
4945 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4946 auto parent = layerHandle->owner.promote();
4947
chaviw7206d492017-11-10 16:16:12 -08004948 if (parent == nullptr || parent->isPendingRemoval()) {
4949 ALOGE("captureLayers called with a removed parent");
4950 return NAME_NOT_FOUND;
4951 }
4952
Robert Carr578038f2018-03-09 12:25:24 -08004953 const int uid = IPCThreadState::self()->getCallingUid();
4954 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4955 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4956 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4957 return PERMISSION_DENIED;
4958 }
4959
chaviw7206d492017-11-10 16:16:12 -08004960 Rect crop(sourceCrop);
4961 if (sourceCrop.width() <= 0) {
4962 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07004963 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08004964 }
4965
4966 if (sourceCrop.height() <= 0) {
4967 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07004968 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08004969 }
4970
4971 int32_t reqWidth = crop.width() * frameScale;
4972 int32_t reqHeight = crop.height() * frameScale;
4973
Robert Carr578038f2018-03-09 12:25:24 -08004974 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004975
Robert Carr578038f2018-03-09 12:25:24 -08004976 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004977 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4978 if (!layer->isVisible()) {
4979 return;
Robert Carr578038f2018-03-09 12:25:24 -08004980 } else if (childrenOnly && layer == parent.get()) {
4981 return;
chaviwa76b2712017-09-20 12:02:26 -07004982 }
4983 visitor(layer);
4984 });
4985 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004986 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004987}
4988
4989status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4990 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004991 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004992 bool useIdentityTransform) {
4993 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004994
Iris Chang7501ed62018-04-30 14:45:42 +08004995 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004996
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004997 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4998 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4999 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5000 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005001
5002 // This mutex protects syncFd and captureResult for communication of the return values from the
5003 // main thread back to this Binder thread
5004 std::mutex captureMutex;
5005 std::condition_variable captureCondition;
5006 std::unique_lock<std::mutex> captureLock(captureMutex);
5007 int syncFd = -1;
5008 std::optional<status_t> captureResult;
5009
Robert Carr03480e22018-01-04 16:02:06 -08005010 const int uid = IPCThreadState::self()->getCallingUid();
5011 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5012
Dominik Laskowski8c001672018-05-30 16:52:06 -07005013 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005014 // If there is a refresh pending, bug out early and tell the binder thread to try again
5015 // after the refresh.
5016 if (mRefreshPending) {
5017 ATRACE_NAME("Skipping screenshot for now");
5018 std::unique_lock<std::mutex> captureLock(captureMutex);
5019 captureResult = std::make_optional<status_t>(EAGAIN);
5020 captureCondition.notify_one();
5021 return;
5022 }
5023
5024 status_t result = NO_ERROR;
5025 int fd = -1;
5026 {
5027 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005028 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005029 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5030 useIdentityTransform, forSystem, &fd);
5031 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005032 }
5033
5034 {
5035 std::unique_lock<std::mutex> captureLock(captureMutex);
5036 syncFd = fd;
5037 captureResult = std::make_optional<status_t>(result);
5038 captureCondition.notify_one();
5039 }
5040 });
5041
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005042 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005043 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005044 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005045 while (*captureResult == EAGAIN) {
5046 captureResult.reset();
5047 result = postMessageAsync(message);
5048 if (result != NO_ERROR) {
5049 return result;
5050 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005051 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005052 }
5053 result = *captureResult;
5054 }
5055
5056 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005057 sync_wait(syncFd, -1);
5058 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005059 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005060
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005061 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005062}
5063
chaviwa76b2712017-09-20 12:02:26 -07005064void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5065 TraverseLayersFunction traverseLayers, bool yswap,
5066 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005067 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005068
Lloyd Pique144e1162017-12-20 16:44:52 -08005069 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005070
5071 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005072 const auto raWidth = renderArea.getWidth();
5073 const auto raHeight = renderArea.getHeight();
5074
5075 const auto reqWidth = renderArea.getReqWidth();
5076 const auto reqHeight = renderArea.getReqHeight();
5077 Rect sourceCrop = renderArea.getSourceCrop();
5078
Iris Chang7501ed62018-04-30 14:45:42 +08005079 bool filtering = false;
5080 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5081 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5082 static_cast<int32_t>(reqHeight) != raWidth;
5083 } else {
5084 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5085 static_cast<int32_t>(reqHeight) != raHeight;
5086 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005087
Dan Stozac1879002014-05-22 15:59:05 -07005088 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005089 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005090 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005091 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005092 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
Peiyong Linefefaac2018-08-17 12:27:51 -07005093 ui::Transform tr;
Iris Chang7501ed62018-04-30 14:45:42 +08005094 uint32_t flags = 0x00;
5095 switch (mPrimaryDisplayOrientation) {
5096 case DisplayState::eOrientation90:
Peiyong Linefefaac2018-08-17 12:27:51 -07005097 flags = ui::Transform::ROT_90;
Iris Chang7501ed62018-04-30 14:45:42 +08005098 break;
5099 case DisplayState::eOrientation180:
Peiyong Linefefaac2018-08-17 12:27:51 -07005100 flags = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005101 break;
5102 case DisplayState::eOrientation270:
Peiyong Linefefaac2018-08-17 12:27:51 -07005103 flags = ui::Transform::ROT_270;
Iris Chang7501ed62018-04-30 14:45:42 +08005104 break;
5105 }
5106 tr.set(flags, raWidth, raHeight);
5107 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005108 }
5109
5110 // ensure that sourceCrop is inside screen
5111 if (sourceCrop.left < 0) {
5112 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5113 }
chaviwa76b2712017-09-20 12:02:26 -07005114 if (sourceCrop.right > raWidth) {
5115 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005116 }
5117 if (sourceCrop.top < 0) {
5118 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5119 }
chaviwa76b2712017-09-20 12:02:26 -07005120 if (sourceCrop.bottom > raHeight) {
5121 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005122 }
5123
Chia-I Wu36574d92018-05-16 10:54:36 -07005124 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5125 engine.setOutputDataSpace(Dataspace::SRGB);
5126 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005127
Mathias Agopian180f10d2013-04-10 22:55:41 -07005128 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005129 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005130
Peiyong Linefefaac2018-08-17 12:27:51 -07005131 ui::Transform::orientation_flags rotation = renderArea.getRotationFlags();
Iris Chang7501ed62018-04-30 14:45:42 +08005132 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5133 // convert hw orientation into flag presentation
5134 // here inverse transform needed
5135 uint8_t hw_rot_90 = 0x00;
5136 uint8_t hw_flip_hv = 0x00;
5137 switch (mPrimaryDisplayOrientation) {
5138 case DisplayState::eOrientation90:
Peiyong Linefefaac2018-08-17 12:27:51 -07005139 hw_rot_90 = ui::Transform::ROT_90;
5140 hw_flip_hv = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005141 break;
5142 case DisplayState::eOrientation180:
Peiyong Linefefaac2018-08-17 12:27:51 -07005143 hw_flip_hv = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005144 break;
5145 case DisplayState::eOrientation270:
Peiyong Linefefaac2018-08-17 12:27:51 -07005146 hw_rot_90 = ui::Transform::ROT_90;
Iris Chang7501ed62018-04-30 14:45:42 +08005147 break;
5148 }
5149
5150 // transform flags operation
5151 // 1) flip H V if both have ROT_90 flag
5152 // 2) XOR these flags
Peiyong Linefefaac2018-08-17 12:27:51 -07005153 uint8_t rotation_rot_90 = rotation & ui::Transform::ROT_90;
5154 uint8_t rotation_flip_hv = rotation & ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005155 if (rotation_rot_90 & hw_rot_90) {
Peiyong Linefefaac2018-08-17 12:27:51 -07005156 rotation_flip_hv = (~rotation_flip_hv) & ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005157 }
Peiyong Linefefaac2018-08-17 12:27:51 -07005158 rotation = static_cast<ui::Transform::orientation_flags>
Iris Chang7501ed62018-04-30 14:45:42 +08005159 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5160 }
5161
Mathias Agopian180f10d2013-04-10 22:55:41 -07005162 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005163 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005164 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005165 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005166
chaviw50da5042018-04-09 13:49:37 -07005167 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005168 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005169 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005170
chaviwa76b2712017-09-20 12:02:26 -07005171 traverseLayers([&](Layer* layer) {
5172 if (filtering) layer->setFiltering(true);
David Sodmanca10ed22018-04-16 14:10:25 -07005173 layer->drawNow(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005174 if (filtering) layer->setFiltering(false);
5175 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005176}
5177
chaviwa76b2712017-09-20 12:02:26 -07005178status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5179 TraverseLayersFunction traverseLayers,
5180 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005181 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005182 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005183 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005184 ATRACE_CALL();
5185
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005186 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005187
5188 traverseLayers([&](Layer* layer) {
5189 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5190 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005191
Robert Carr03480e22018-01-04 16:02:06 -08005192 // We allow the system server to take screenshots of secure layers for
5193 // use in situations like the Screen-rotation animation and place
5194 // the impetus on WindowManager to not persist them.
5195 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005196 ALOGW("FB is protected: PERMISSION_DENIED");
5197 return PERMISSION_DENIED;
5198 }
5199
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005200 // this binds the given EGLImage as a framebuffer for the
5201 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005202 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005203 if (bufferBond.getStatus() != NO_ERROR) {
5204 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005205 return INVALID_OPERATION;
5206 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005207
Dan Stozaabcda352017-06-01 14:37:39 -07005208 // this will in fact render into our dequeued buffer
5209 // via an FBO, which means we didn't have to create
5210 // an EGLSurface and therefore we're not
5211 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005212 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005213
Dan Stozaabcda352017-06-01 14:37:39 -07005214 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005215 getRenderEngine().finish();
5216 *outSyncFd = -1;
5217
chaviwa76b2712017-09-20 12:02:26 -07005218 const auto reqWidth = renderArea.getReqWidth();
5219 const auto reqHeight = renderArea.getReqHeight();
5220
Dan Stozaabcda352017-06-01 14:37:39 -07005221 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5222 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005223 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005224 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005225 } else {
5226 base::unique_fd syncFd = getRenderEngine().flush();
5227 if (syncFd < 0) {
5228 getRenderEngine().finish();
5229 }
5230 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005231 }
5232
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005233 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005234}
5235
Mathias Agopiand5556842013-09-19 17:08:37 -07005236void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005237 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005238 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005239 for (size_t y = 0; y < h; y++) {
5240 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5241 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005242 if (p[x] != 0xFF000000) return;
5243 }
5244 }
chaviwa76b2712017-09-20 12:02:26 -07005245 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005246
Robert Carr2047fae2016-11-28 14:09:09 -08005247 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005248 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005249 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005250 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5251 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5252 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5253 static_cast<float>(state.color.a));
5254 i++;
5255 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005256 }
5257}
5258
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005259// ---------------------------------------------------------------------------
5260
Dan Stoza412903f2017-04-27 13:42:17 -07005261void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5262 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005263}
5264
Dan Stoza412903f2017-04-27 13:42:17 -07005265void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5266 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005267}
5268
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005269void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5270 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005271 const LayerVector::Visitor& visitor) {
5272 // We loop through the first level of layers without traversing,
5273 // as we need to interpret min/max layer Z in the top level Z space.
5274 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005275 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005276 continue;
5277 }
5278 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005279 // relative layers are traversed in Layer::traverseInZOrder
5280 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005281 continue;
5282 }
5283 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005284 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005285 return;
5286 }
chaviwa76b2712017-09-20 12:02:26 -07005287 if (!layer->isVisible()) {
5288 return;
5289 }
5290 visitor(layer);
5291 });
5292 }
5293}
5294
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005295}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005296
Lloyd Pique074e8122018-07-26 12:57:23 -07005297
Mathias Agopian3f844832013-08-07 21:24:32 -07005298#if defined(__gl_h_)
5299#error "don't include gl/gl.h in this file"
5300#endif
5301
5302#if defined(__gl2_h_)
5303#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005304#endif