blob: 690f9361578d5e5f468c93d3c0653b38fbfeebbb [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
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700880int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
881 const auto display = getDisplayDevice(displayToken);
882 if (!display) {
883 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800884 return BAD_VALUE;
885 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700886
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700887 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700888}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700889
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700890void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
891 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700892 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700893 return;
894 }
895
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700896 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700897 ALOGW("Trying to set config for virtual display");
898 return;
899 }
900
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700901 display->setActiveConfig(mode);
902 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700903}
904
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700905status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700906 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700907 Vector<DisplayInfo> configs;
908 getDisplayConfigs(displayToken, &configs);
909 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
910 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
911 configs.size());
912 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700913 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700914 const auto display = getDisplayDevice(displayToken);
915 if (!display) {
916 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
917 displayToken.get());
918 } else if (display->isVirtual()) {
919 ALOGW("Attempt to set active config %d for virtual display", mode);
920 } else {
921 setActiveConfigInternal(display, mode);
922 }
923 }));
924
Mathias Agopian888c8222012-08-04 21:10:38 -0700925 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700926}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700927status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
928 Vector<ColorMode>* outColorModes) {
929 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700930 return BAD_VALUE;
931 }
932
Michael Wright28f24d02016-07-12 13:30:53 -0700933 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700934 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
935 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700936 type = i;
937 break;
938 }
939 }
940
941 if (type < 0) {
942 return type;
943 }
944
Peiyong Lina52f0292018-03-14 17:26:31 -0700945 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700946 {
947 ConditionalLock _l(mStateLock,
948 std::this_thread::get_id() != mMainThreadId);
949 modes = getHwComposer().getColorModes(type);
950 }
Michael Wright28f24d02016-07-12 13:30:53 -0700951 outColorModes->clear();
952 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
953
954 return NO_ERROR;
955}
956
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700957ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
958 if (const auto display = getDisplayDevice(displayToken)) {
959 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700960 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700961 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700962}
963
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700964void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
965 Dataspace dataSpace, RenderIntent renderIntent) {
966 ColorMode currentMode = display->getActiveColorMode();
967 Dataspace currentDataSpace = display->getCompositionDataSpace();
968 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -0700969
Peiyong Lin38e9a562018-04-10 16:24:20 -0700970 if (mode == currentMode && dataSpace == currentDataSpace &&
971 renderIntent == currentRenderIntent) {
972 return;
973 }
974
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700975 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -0700976 ALOGW("Trying to set config for virtual display");
977 return;
978 }
979
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700980 display->setActiveColorMode(mode);
981 display->setCompositionDataSpace(dataSpace);
982 display->setActiveRenderIntent(renderIntent);
983 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800984
985 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700986 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
987 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -0700988}
989
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700990status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700991 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700992 Vector<ColorMode> modes;
993 getDisplayColorModes(displayToken, &modes);
994 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
995 if (mode < ColorMode::NATIVE || !exists) {
996 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
997 decodeColorMode(mode).c_str(), mode, displayToken.get());
998 return;
Michael Wright28f24d02016-07-12 13:30:53 -0700999 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001000 const auto display = getDisplayDevice(displayToken);
1001 if (!display) {
1002 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1003 decodeColorMode(mode).c_str(), mode, displayToken.get());
1004 } else if (display->isVirtual()) {
1005 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1006 decodeColorMode(mode).c_str(), mode);
1007 } else {
1008 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1009 RenderIntent::COLORIMETRIC);
1010 }
1011 }));
1012
Michael Wright28f24d02016-07-12 13:30:53 -07001013 return NO_ERROR;
1014}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001015
Svetoslavd85084b2014-03-20 10:28:31 -07001016status_t SurfaceFlinger::clearAnimationFrameStats() {
1017 Mutex::Autolock _l(mStateLock);
1018 mAnimFrameTracker.clearStats();
1019 return NO_ERROR;
1020}
1021
1022status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1023 Mutex::Autolock _l(mStateLock);
1024 mAnimFrameTracker.getStats(outStats);
1025 return NO_ERROR;
1026}
1027
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001028status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1029 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001030 Mutex::Autolock _l(mStateLock);
1031
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001032 const auto display = getDisplayDeviceLocked(displayToken);
1033 if (!display) {
1034 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001035 return BAD_VALUE;
1036 }
1037
Peiyong Linfb069302018-04-25 14:34:31 -07001038 // At this point the DisplayDeivce should already be set up,
1039 // meaning the luminance information is already queried from
1040 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001041 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001042 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1043 capabilities.getDesiredMaxLuminance(),
1044 capabilities.getDesiredMaxAverageLuminance(),
1045 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001046
1047 return NO_ERROR;
1048}
1049
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001050status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001051 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001052 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001053
Chia-I Wu90f669f2017-10-05 14:24:41 -07001054 if (mInjectVSyncs == enable) {
1055 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001056 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001057
1058 if (enable) {
1059 ALOGV("VSync Injections enabled");
1060 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001061 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001062 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001063 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001064 impl::EventThread::InterceptVSyncsCallback(),
1065 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001066 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001067 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001068 } else {
1069 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001070 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001071 }
1072
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001073 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001074 }));
1075
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001076 return NO_ERROR;
1077}
1078
1079status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001080 Mutex::Autolock _l(mStateLock);
1081
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001082 if (!mInjectVSyncs) {
1083 ALOGE("VSync Injections not enabled");
1084 return BAD_VALUE;
1085 }
1086 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1087 ALOGV("Injecting VSync inside SurfaceFlinger");
1088 mVSyncInjector->onInjectSyncEvent(when);
1089 }
1090 return NO_ERROR;
1091}
1092
Lloyd Pique755e3192018-01-31 16:46:15 -08001093status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1094 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001095 // Try to acquire a lock for 1s, fail gracefully
1096 const status_t err = mStateLock.timedLock(s2ns(1));
1097 const bool locked = (err == NO_ERROR);
1098 if (!locked) {
1099 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1100 return TIMED_OUT;
1101 }
1102
1103 outLayers->clear();
1104 mCurrentState.traverseInZOrder([&](Layer* layer) {
1105 outLayers->push_back(layer->getLayerDebugInfo());
1106 });
1107
1108 mStateLock.unlock();
1109 return NO_ERROR;
1110}
1111
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001112// ----------------------------------------------------------------------------
1113
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001114sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1115 ISurfaceComposer::VsyncSource vsyncSource) {
1116 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1117 return mSFEventThread->createEventConnection();
1118 } else {
1119 return mEventThread->createEventConnection();
1120 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001121}
1122
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001123// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001124
1125void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001126 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001127}
1128
1129void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001130 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001131}
1132
1133void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001134 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001135}
1136
1137void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001138 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001139 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001140}
1141
1142status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001143 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001144 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001145}
1146
1147status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001148 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001149 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001150 if (res == NO_ERROR) {
1151 msg->wait();
1152 }
1153 return res;
1154}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001155
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001156void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001157 do {
1158 waitForEvent();
1159 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001160}
1161
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001162void SurfaceFlinger::enableHardwareVsync() {
1163 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001164 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001165 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001166 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001167 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001168 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001169}
1170
Jesse Hall948fe0c2013-10-14 12:56:09 -07001171void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001172 Mutex::Autolock _l(mHWVsyncLock);
1173
Jesse Hall948fe0c2013-10-14 12:56:09 -07001174 if (makeAvailable) {
1175 mHWVsyncAvailable = true;
1176 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001177 // Hardware vsync is not currently available, so abort the resync
1178 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001179 return;
1180 }
1181
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001182 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1183 if (!getHwComposer().isConnected(displayId)) {
1184 return;
1185 }
1186
1187 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001188 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001189
Lloyd Pique41be5d22018-06-21 13:11:48 -07001190 mPrimaryDispSync->reset();
1191 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001192
1193 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001194 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001195 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001196 mPrimaryHWVsyncEnabled = true;
1197 }
1198}
1199
Jesse Hall948fe0c2013-10-14 12:56:09 -07001200void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001201 Mutex::Autolock _l(mHWVsyncLock);
1202 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001203 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001204 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001205 mPrimaryHWVsyncEnabled = false;
1206 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001207 if (makeUnavailable) {
1208 mHWVsyncAvailable = false;
1209 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001210}
1211
Tim Murray4a4e4a22016-04-19 16:29:23 +00001212void SurfaceFlinger::resyncWithRateLimit() {
1213 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001214
1215 // No explicit locking is needed here since EventThread holds a lock while calling this method
1216 static nsecs_t sLastResyncAttempted = 0;
1217 const nsecs_t now = systemTime();
1218 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001219 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001220 }
Dan Stoza57164302017-05-08 14:03:54 -07001221 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001222}
1223
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001224void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1225 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001226 ATRACE_NAME("SF onVsync");
1227
Steven Thomas3cfac282017-02-06 12:29:30 -08001228 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001229 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001230 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001231 return;
1232 }
1233
1234 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001235 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001236 return;
1237 }
1238
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001239 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1240 // For now, we don't do anything with external display vsyncs.
1241 return;
1242 }
1243
Jamie Gennisd1700752013-10-14 12:22:52 -07001244 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001245
Jamie Gennisd1700752013-10-14 12:22:52 -07001246 { // Scope for the lock
1247 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001248 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001249 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001250 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001251 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001252
1253 if (needsHwVsync) {
1254 enableHardwareVsync();
1255 } else {
1256 disableHardwareVsync(false);
1257 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001258}
1259
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001260void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001261 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1262 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001263}
1264
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001265void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001266 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001267 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001268 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001269
Lloyd Piqueba04e622017-12-14 17:11:26 -08001270 // Ignore events that do not have the right sequenceId.
1271 if (sequenceId != getBE().mComposerSequenceId) {
1272 return;
1273 }
1274
Steven Thomasb02664d2017-07-26 18:48:28 -07001275 // Only lock if we're not on the main thread. This function is normally
1276 // called on a hwbinder thread, but for the primary display it's called on
1277 // the main thread with the state lock already held, so don't attempt to
1278 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001279 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001280
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001281 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001282
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001283 if (std::this_thread::get_id() == mMainThreadId) {
1284 // Process all pending hot plug events immediately if we are on the main thread.
1285 processDisplayHotplugEventsLocked();
1286 }
1287
Lloyd Piqueba04e622017-12-14 17:11:26 -08001288 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001289}
1290
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001291void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001292 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001293 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001294 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001295 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001296 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001297}
1298
Dan Stoza9e56aa02015-11-02 13:00:03 -08001299void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001300 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001301 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001302 getHwComposer().setVsyncEnabled(disp,
1303 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001304}
1305
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001306// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001307void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001308 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001309 // Clear the drawing state so that the logic inside of
1310 // handleTransactionLocked will fire. It will determine the delta between
1311 // mCurrentState and mDrawingState and re-apply all changes when we make the
1312 // transition.
1313 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001314 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001315 mDisplays.clear();
1316}
1317
Steven Thomas050b2c82017-03-06 11:45:16 -08001318void SurfaceFlinger::updateVrFlinger() {
1319 if (!mVrFlinger)
1320 return;
1321 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001322 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001323 return;
1324 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001325
David Sodman105b7dc2017-11-04 20:28:14 -07001326 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001327 ALOGE("Vr flinger is only supported for remote hardware composer"
1328 " service connections. Ignoring request to transition to vr"
1329 " flinger.");
1330 mVrFlingerRequestsDisplay = false;
1331 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001332 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001333
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001334 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001335
Steven Thomas0123ac62018-07-12 11:32:34 -07001336 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001337 LOG_ALWAYS_FATAL_IF(!display);
1338 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001339 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1340 // called below. Clear the reference now so we don't accidentally use it
1341 // later.
1342 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001343
Steven Thomasb02664d2017-07-26 18:48:28 -07001344 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001345 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001346 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001347
Steven Thomasb02664d2017-07-26 18:48:28 -07001348 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001349 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001350 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1351 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001352 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001353
David Sodman105b7dc2017-11-04 20:28:14 -07001354 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1355 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001356
1357 if (vrFlingerRequestsDisplay) {
1358 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001359 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001360
1361 mVisibleRegionsDirty = true;
1362 invalidateHwcGeometry();
1363
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001364 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001365 display = getDefaultDisplayDeviceLocked();
1366 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001367 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001368
Steven Thomasb02664d2017-07-26 18:48:28 -07001369 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001370 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001371 const nsecs_t period = activeConfig->getVsyncPeriod();
1372 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001373
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001374 // The present fences returned from vr_hwc are not an accurate
1375 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001376 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1377 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001378
Steven Thomasb02664d2017-07-26 18:48:28 -07001379 // Use phase of 0 since phase is not known.
1380 // Use latency of 0, which will snap to the ideal latency.
1381 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001382
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001383 resyncToHardwareVsync(false);
1384
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001385 android_atomic_or(1, &mRepaintEverything);
1386 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001387}
1388
Mathias Agopian4fec8732012-06-29 14:12:52 -07001389void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001390 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001391 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001392 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001393 bool frameMissed = !mHadClientComposition &&
1394 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001395 (mPreviousPresentFence->getSignalTime() ==
1396 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001397 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001398 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001399 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001400 mTimeStats.incrementMissedFrames();
1401 if (mPropagateBackpressure) {
1402 signalLayerUpdate();
1403 break;
1404 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001405 }
Dan Stoza50182882016-07-08 12:02:20 -07001406
Steven Thomas050b2c82017-03-06 11:45:16 -08001407 // Now that we're going to make it to the handleMessageTransaction()
1408 // call below it's safe to call updateVrFlinger(), which will
1409 // potentially trigger a display handoff.
1410 updateVrFlinger();
1411
Dan Stoza6b9454d2014-11-07 16:00:59 -08001412 bool refreshNeeded = handleMessageTransaction();
1413 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001414 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001415 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001416 // Signal a refresh if a transaction modified the window state,
1417 // a new buffer was latched, or if HWC has requested a full
1418 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001419 signalRefresh();
1420 }
1421 break;
1422 }
1423 case MessageQueue::REFRESH: {
1424 handleMessageRefresh();
1425 break;
1426 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001427 }
1428}
1429
Dan Stoza6b9454d2014-11-07 16:00:59 -08001430bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001431 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001432 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001433 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001434 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001435 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001436 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001437}
1438
Mathias Agopian4fec8732012-06-29 14:12:52 -07001439void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001440 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001441
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001442 mRefreshPending = false;
1443
David Sodmanfa9b2af2017-12-24 13:28:59 -08001444 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
David Sodman2b406362017-12-15 13:33:47 -08001445 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001446 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001447 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001448 for (const auto& [token, display] : mDisplays) {
1449 beginFrame(display);
1450 prepareFrame(display);
1451 doDebugFlashRegions(display, repaintEverything);
1452 doComposition(display, repaintEverything);
1453 }
1454
Adrian Roos1e1a1282017-11-01 19:05:31 +01001455 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001456 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001457
1458 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001459 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001460
Dan Stozabfbffeb2016-07-21 14:49:33 -07001461 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001462 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001463 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001464 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001465 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001466
Jorim Jaggi90535212018-05-23 23:44:06 +02001467 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001468
Dan Stoza9e56aa02015-11-02 13:00:03 -08001469 mLayersWithQueuedFrames.clear();
David Sodmanba340492018-08-05 21:51:33 -07001470 for (auto& compositionInfo : getBE().mCompositionInfo) {
1471 compositionInfo.hwc.hwcLayer = nullptr;
1472 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001473}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001474
David Sodmanfa9b2af2017-12-24 13:28:59 -08001475
1476bool SurfaceFlinger::handleMessageInvalidate() {
1477 ATRACE_CALL();
1478 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001479}
1480
David Sodman79bba0e2018-08-05 18:07:49 -07001481void SurfaceFlinger::calculateWorkingSet() {
1482 ATRACE_CALL();
1483 ALOGV(__FUNCTION__);
1484
David Sodman79bba0e2018-08-05 18:07:49 -07001485 // build the h/w work list
1486 if (CC_UNLIKELY(mGeometryInvalid)) {
1487 mGeometryInvalid = false;
1488 for (const auto& [token, display] : mDisplays) {
1489 const auto displayId = display->getId();
1490 if (displayId >= 0) {
1491 const Vector<sp<Layer>>& currentLayers(
1492 display->getVisibleLayersSortedByZ());
1493 for (size_t i = 0; i < currentLayers.size(); i++) {
1494 const auto& layer = currentLayers[i];
1495
1496 if (!layer->hasHwcLayer(displayId)) {
1497 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1498 layer->forceClientComposition(displayId);
1499 continue;
1500 }
1501 }
1502
1503 layer->setGeometry(display, i);
1504 if (mDebugDisableHWC || mDebugRegion) {
1505 layer->forceClientComposition(displayId);
1506 }
1507 }
1508 }
1509 }
1510 }
1511
1512 // Set the per-frame data
1513 for (const auto& [token, display] : mDisplays) {
1514 const auto displayId = display->getId();
1515 if (displayId < 0) {
1516 continue;
1517 }
1518
1519 if (mDrawingState.colorMatrixChanged) {
1520 display->setColorTransform(mDrawingState.colorMatrix);
1521 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1522 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1523 "display %d: %d", displayId, result);
1524 }
1525 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1526 if (layer->isHdrY410()) {
1527 layer->forceClientComposition(displayId);
1528 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1529 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1530 !display->hasHDR10Support()) {
1531 layer->forceClientComposition(displayId);
1532 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1533 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1534 !display->hasHLGSupport()) {
1535 layer->forceClientComposition(displayId);
1536 }
1537
1538 if (layer->getForceClientComposition(displayId)) {
1539 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1540 layer->setCompositionType(displayId, HWC2::Composition::Client);
1541 continue;
1542 }
1543
1544 layer->setPerFrameData(display);
1545 }
1546
Peiyong Lin13effd12018-07-24 17:01:47 -07001547 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001548 ColorMode colorMode;
1549 Dataspace dataSpace;
1550 RenderIntent renderIntent;
1551 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1552 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1553 }
1554 }
1555
1556 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001557 getBE().mCompositionInfo.clear();
1558
1559 for (const auto& [token, display] : mDisplays) {
1560 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1561 auto displayId = display->getId();
1562 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1563 if (!layer->setHwcLayer(displayId)) {
1564 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1565 }
1566 getBE().mCompositionInfo.push_back(layer->getBE().compositionInfo);
1567 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1568 }
1569 }
David Sodman79bba0e2018-08-05 18:07:49 -07001570}
1571
David Sodmanfa9b2af2017-12-24 13:28:59 -08001572void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001573{
1574 // is debugging enabled
1575 if (CC_LIKELY(!mDebugRegion))
1576 return;
1577
David Sodmanfa9b2af2017-12-24 13:28:59 -08001578 if (display->isPoweredOn()) {
1579 // transform the dirty region into this screen's coordinate space
1580 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1581 if (!dirtyRegion.isEmpty()) {
1582 // redraw the whole screen
1583 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001584
David Sodmanfa9b2af2017-12-24 13:28:59 -08001585 // and draw the dirty region
1586 const int32_t height = display->getHeight();
1587 auto& engine(getRenderEngine());
1588 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001589
David Sodmanfa9b2af2017-12-24 13:28:59 -08001590 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001591 }
1592 }
1593
David Sodmanfa9b2af2017-12-24 13:28:59 -08001594 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001595
1596 if (mDebugRegion > 1) {
1597 usleep(mDebugRegion * 1000);
1598 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001599
David Sodmanfa9b2af2017-12-24 13:28:59 -08001600 if (display->isPoweredOn()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001601 status_t result = display->prepareFrame(*getBE().mHwc);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001602 ALOGE_IF(result != NO_ERROR,
1603 "prepareFrame for display %d failed:"
1604 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001605 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001606 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001607}
1608
Adrian Roos1e1a1282017-11-01 19:05:31 +01001609void SurfaceFlinger::doTracing(const char* where) {
1610 ATRACE_CALL();
1611 ATRACE_NAME(where);
1612 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001613 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001614 }
1615}
1616
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001617void SurfaceFlinger::logLayerStats() {
1618 ATRACE_CALL();
1619 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001620 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001621 if (display->isPrimary()) {
1622 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001623 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001624 }
1625 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001626
1627 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001628 }
1629}
1630
David Sodman2b406362017-12-15 13:33:47 -08001631void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001632{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001633 ATRACE_CALL();
1634 ALOGV("preComposition");
1635
David Sodman2b406362017-12-15 13:33:47 -08001636 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1637
Mathias Agopiancd60f992012-08-16 16:28:27 -07001638 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001639 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001640 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001641 needExtraInvalidate = true;
1642 }
Robert Carr2047fae2016-11-28 14:09:09 -08001643 });
1644
Mathias Agopiancd60f992012-08-16 16:28:27 -07001645 if (needExtraInvalidate) {
1646 signalLayerUpdate();
1647 }
1648}
1649
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001650void SurfaceFlinger::updateCompositorTiming(
1651 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1652 std::shared_ptr<FenceTime>& presentFenceTime) {
1653 // Update queue of past composite+present times and determine the
1654 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001655 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001656 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001657 while (!getBE().mCompositePresentTimes.empty()) {
1658 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001659 // Cached values should have been updated before calling this method,
1660 // which helps avoid duplicate syscalls.
1661 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1662 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1663 break;
1664 }
1665 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001666 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001667 }
1668
1669 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001670 while (getBE().mCompositePresentTimes.size() > 16) {
1671 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001672 }
1673
Brian Andersond0010582017-03-07 13:20:31 -08001674 setCompositorTimingSnapped(
1675 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1676}
1677
1678void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1679 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001680 // Integer division and modulo round toward 0 not -inf, so we need to
1681 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001682 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001683 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1684 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1685
Brian Andersond0010582017-03-07 13:20:31 -08001686 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1687 if (idealLatency <= 0) {
1688 idealLatency = vsyncInterval;
1689 }
1690
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001691 // Snap the latency to a value that removes scheduling jitter from the
1692 // composition and present times, which often have >1ms of jitter.
1693 // Reducing jitter is important if an app attempts to extrapolate
1694 // something (such as user input) to an accurate diasplay time.
1695 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1696 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001697 nsecs_t bias = vsyncInterval / 2;
1698 int64_t extraVsyncs =
1699 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1700 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1701 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001702
David Sodman99974d22017-11-28 12:04:33 -08001703 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1704 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1705 getBE().mCompositorTiming.interval = vsyncInterval;
1706 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001707}
1708
David Sodman2b406362017-12-15 13:33:47 -08001709void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001710{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001711 ATRACE_CALL();
1712 ALOGV("postComposition");
1713
Brian Anderson3546a3f2016-07-14 11:51:14 -07001714 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001715 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001716 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001717 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001718 }
1719
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001720 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001721 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001722
David Sodman73beded2017-11-15 11:56:06 -08001723 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001724 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001725 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001726 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001727 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001728 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001729 } else {
1730 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1731 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001732
David Sodman73beded2017-11-15 11:56:06 -08001733 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001734 mPreviousPresentFence =
1735 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1736 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001737 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001738
Lloyd Pique41be5d22018-06-21 13:11:48 -07001739 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1740 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001741
David Sodman2b406362017-12-15 13:33:47 -08001742 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001743 // when we started doing work for this frame, but that should be okay
1744 // since updateCompositorTiming has snapping logic.
1745 updateCompositorTiming(
David Sodman2b406362017-12-15 13:33:47 -08001746 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001747 CompositorTiming compositorTiming;
1748 {
David Sodman99974d22017-11-28 12:04:33 -08001749 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1750 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001751 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001752
Robert Carr2047fae2016-11-28 14:09:09 -08001753 mDrawingState.traverseInZOrder([&](Layer* layer) {
1754 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001755 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001756 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001757 recordBufferingStats(layer->getName().string(),
1758 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001759 }
Robert Carr2047fae2016-11-28 14:09:09 -08001760 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001761
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001762 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001763 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001764 enableHardwareVsync();
1765 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001766 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001767 }
1768 }
1769
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001770 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001771 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001772 enableHardwareVsync();
1773 }
1774 }
1775
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001776 if (mAnimCompositionPending) {
1777 mAnimCompositionPending = false;
1778
Brian Anderson4e606e32017-03-16 15:34:57 -07001779 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001780 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001781 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001782 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001783 // The HWC doesn't support present fences, so use the refresh
1784 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001785 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001786 mAnimFrameTracker.setActualPresentTime(presentTime);
1787 }
1788 mAnimFrameTracker.advanceFrame();
1789 }
Dan Stozab90cf072015-03-05 11:05:59 -08001790
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001791 mTimeStats.incrementTotalFrames();
1792 if (mHadClientComposition) {
1793 mTimeStats.incrementClientCompositionFrames();
1794 }
1795
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001796 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001797 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001798 return;
1799 }
1800
1801 nsecs_t currentTime = systemTime();
1802 if (mHasPoweredOff) {
1803 mHasPoweredOff = false;
1804 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001805 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001806 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001807 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1808 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001809 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001810 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001811 }
David Sodman4a36e932017-11-07 14:29:47 -08001812 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001813 }
David Sodman4a36e932017-11-07 14:29:47 -08001814 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001815
1816 {
1817 std::lock_guard lock(mTexturePoolMutex);
1818 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1819 if (refillCount > 0) {
1820 const size_t offset = mTexturePool.size();
1821 mTexturePool.resize(mTexturePoolSize);
1822 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1823 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1824 }
1825 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001826}
1827
1828void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001829 ATRACE_CALL();
1830 ALOGV("rebuildLayerStacks");
1831
Mathias Agopiancd60f992012-08-16 16:28:27 -07001832 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001833 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001834 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001835 mVisibleRegionsDirty = false;
1836 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001837
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001838 for (const auto& pair : mDisplays) {
1839 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001840 Region opaqueRegion;
1841 Region dirtyRegion;
1842 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001843 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001844 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001845 const Rect bounds = display->getBounds();
1846 if (display->isPoweredOn()) {
1847 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001848
Jeff Sharkey76488112017-02-27 14:15:18 -07001849 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001850 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001851 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001852 Region drawRegion(tr.transform(
1853 layer->visibleNonTransparentRegion));
1854 drawRegion.andSelf(bounds);
1855 if (!drawRegion.isEmpty()) {
1856 layersSortedByZ.add(layer);
1857 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001858 // Clear out the HWC layer if this layer was
1859 // previously visible, but no longer is
1860 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001861 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001862 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001863 // WM changes display->layerStack upon sleep/awake.
1864 // Here we make sure we delete the HWC layers even if
1865 // WM changed their layer stack.
1866 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001867 }
1868
1869 // If a layer is not going to get a release fence because
1870 // it is invisible, but it is also going to release its
1871 // old buffer, add it to the list of layers needing
1872 // fences.
1873 if (hwcLayerDestroyed) {
1874 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1875 mLayersWithQueuedFrames.cend(), layer);
1876 if (found != mLayersWithQueuedFrames.cend()) {
1877 layersNeedingFences.add(layer);
1878 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001879 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001880 });
1881 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001882 display->setVisibleLayersSortedByZ(layersSortedByZ);
1883 display->setLayersNeedingFences(layersNeedingFences);
1884 display->undefinedRegion.set(bounds);
1885 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1886 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001887 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001888 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001889}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001890
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001891// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001892// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001893// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001894// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001895// The returned HDR data space is one of
1896// - Dataspace::UNKNOWN
1897// - Dataspace::BT2020_HLG
1898// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001899Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1900 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001901 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001902 *outHdrDataSpace = Dataspace::UNKNOWN;
1903
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001904 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001905 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001906 case Dataspace::V0_SCRGB:
1907 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001908 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001909 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001910 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001911 case Dataspace::BT2020_PQ:
1912 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001913 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001914 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001915 case Dataspace::BT2020_HLG:
1916 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001917 // When there's mixed PQ content and HLG content, we set the HDR
1918 // data space to be BT2020_PQ and convert HLG to PQ.
1919 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1920 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001921 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001922 break;
1923 default:
1924 break;
1925 }
Romain Guy54f154a2017-10-24 21:40:32 +01001926 }
1927
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001928 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001929}
1930
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001931// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001932void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1933 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001934 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1935 *outMode = ColorMode::NATIVE;
1936 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001937 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001938 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001939 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001940
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001941 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001942 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001943
Peiyong Lindfde5112018-06-05 10:58:41 -07001944 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001945 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001946 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001947 if (isHdr) {
1948 bestDataSpace = hdrDataSpace;
1949 }
1950
Chia-I Wu0d711262018-05-21 15:19:35 -07001951 RenderIntent intent;
1952 switch (mDisplayColorSetting) {
1953 case DisplayColorSetting::MANAGED:
1954 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001955 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001956 break;
1957 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001958 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001959 break;
1960 default: // vendor display color setting
1961 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1962 break;
1963 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001964
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001965 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001966}
1967
David Sodmanfa9b2af2017-12-24 13:28:59 -08001968void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08001969{
David Sodmanfa9b2af2017-12-24 13:28:59 -08001970 bool dirty = !display->getDirtyRegion(false).isEmpty();
1971 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
1972 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08001973
David Sodmanfa9b2af2017-12-24 13:28:59 -08001974 // If nothing has changed (!dirty), don't recompose.
1975 // If something changed, but we don't currently have any visible layers,
1976 // and didn't when we last did a composition, then skip it this time.
1977 // The second rule does two things:
1978 // - When all layers are removed from a display, we'll emit one black
1979 // frame, then nothing more until we get new layers.
1980 // - When a display is created with a private layer stack, we won't
1981 // emit any black frames until a layer is added to the layer stack.
1982 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08001983
David Sodmanfa9b2af2017-12-24 13:28:59 -08001984 ALOGV_IF(displayDevice->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1985 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1986 mustRecompose ? "doing" : "skipping",
1987 dirty ? "+" : "-",
1988 empty ? "+" : "-",
1989 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08001990
David Sodmanfa9b2af2017-12-24 13:28:59 -08001991 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08001992
David Sodmanfa9b2af2017-12-24 13:28:59 -08001993 if (mustRecompose) {
1994 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08001995 }
1996}
1997
David Sodmanfa9b2af2017-12-24 13:28:59 -08001998void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08001999{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002000 if (!display->isPoweredOn()) {
2001 return;
David Sodman2b406362017-12-15 13:33:47 -08002002 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002003
2004 status_t result = display->prepareFrame(*getBE().mHwc);
2005 ALOGE_IF(result != NO_ERROR,
2006 "prepareFrame for display %d failed:"
2007 " %d (%s)",
2008 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002009}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002010
David Sodmanfa9b2af2017-12-24 13:28:59 -08002011void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002012 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002013 ALOGV("doComposition");
2014
David Sodmanfa9b2af2017-12-24 13:28:59 -08002015 if (display->isPoweredOn()) {
2016 // transform the dirty region into this screen's coordinate space
2017 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002018
David Sodmanfa9b2af2017-12-24 13:28:59 -08002019 // repaint the framebuffer (if needed)
2020 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002021
David Sodmanfa9b2af2017-12-24 13:28:59 -08002022 display->dirtyRegion.clear();
2023 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002024 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002025 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002026}
2027
David Sodmanfa9b2af2017-12-24 13:28:59 -08002028void SurfaceFlinger::postFrame()
2029{
2030 // |mStateLock| not needed as we are on the main thread
2031 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2032 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2033 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2034 logFrameStats();
2035 }
2036 }
2037}
2038
2039void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002040{
Mathias Agopian841cde52012-03-01 15:44:37 -08002041 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002042 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002043
David Sodmanfa9b2af2017-12-24 13:28:59 -08002044 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002045
David Sodmanfa9b2af2017-12-24 13:28:59 -08002046 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002047 const auto displayId = display->getId();
2048 if (displayId >= 0) {
2049 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002050 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002051 display->onSwapBuffersCompleted();
2052 display->makeCurrent();
2053 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002054 sp<Fence> releaseFence = Fence::NO_FENCE;
2055
Chia-I Wu7b549592017-11-15 09:14:57 -08002056 // The layer buffer from the previous frame (if any) is released
2057 // by HWC only when the release fence from this frame (if any) is
2058 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002059 auto hwcLayer = layer->getHwcLayer(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002060 if (displayId >= 0) {
2061 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
2062 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002063
2064 // If the layer was client composited in the previous frame, we
2065 // need to merge with the previous client target acquire fence.
2066 // Since we do not track that, always merge with the current
2067 // client target acquire fence when it is available, even though
2068 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002069 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002070 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002071 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002072 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002073
David Sodmanb8af7922017-12-21 15:17:55 -08002074 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002075 }
Chia-I Wu83806892017-11-16 10:50:20 -08002076
2077 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002078 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002079 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002080 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002081 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002082 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002083 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002084 }
2085 }
2086
Dominik Laskowski7e045462018-05-30 13:02:02 -07002087 if (displayId >= 0) {
2088 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002089 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002090 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002091}
2092
Mathias Agopian87baae12012-07-31 12:38:26 -07002093void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002094{
Mathias Agopian841cde52012-03-01 15:44:37 -08002095 ATRACE_CALL();
2096
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002097 // here we keep a copy of the drawing state (that is the state that's
2098 // going to be overwritten by handleTransactionLocked()) outside of
2099 // mStateLock so that the side-effects of the State assignment
2100 // don't happen with mStateLock held (which can cause deadlocks).
2101 State drawingState(mDrawingState);
2102
Mathias Agopianca4d3602011-05-19 15:38:14 -07002103 Mutex::Autolock _l(mStateLock);
2104 const nsecs_t now = systemTime();
2105 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002106
Mathias Agopianca4d3602011-05-19 15:38:14 -07002107 // Here we're guaranteed that some transaction flags are set
2108 // so we can call handleTransactionLocked() unconditionally.
2109 // We call getTransactionFlags(), which will also clear the flags,
2110 // with mStateLock held to guarantee that mCurrentState won't change
2111 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002112
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002113 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002114 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002115 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002116
Mathias Agopianca4d3602011-05-19 15:38:14 -07002117 mLastTransactionTime = systemTime() - now;
2118 mDebugInTransaction = 0;
2119 invalidateHwcGeometry();
2120 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002121}
2122
Dominik Laskowski7e045462018-05-30 13:02:02 -07002123DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002124 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002125 // Figure out whether the event is for the primary display or an
2126 // external display by matching the Hwc display id against one for a
2127 // connected display. If we did not find a match, we then check what
2128 // displays are not already connected to determine the type. If we don't
2129 // have a connected primary display, we assume the new display is meant to
2130 // be the primary display, and then if we don't have an external display,
2131 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002132 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2133 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002134 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002135 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002136 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002137 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002138 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002139 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002140 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002141 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002142 return DisplayDevice::DISPLAY_EXTERNAL;
2143 }
2144
2145 return DisplayDevice::DISPLAY_ID_INVALID;
2146}
2147
Lloyd Piqueba04e622017-12-14 17:11:26 -08002148void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2149 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002150 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002151 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002152 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002153 continue;
2154 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002155
2156 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2157 ALOGE("External displays are not supported by the vr hardware composer.");
2158 continue;
2159 }
2160
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002161 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002162 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002163 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002164 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002165 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002166
2167 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002168 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002169 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002170 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002171 DisplayDeviceState info;
2172 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002173 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2174 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002175 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002176 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002177 mInterceptor->saveDisplayCreation(info);
2178 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002179 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002180 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002181
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002182 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002183 if (idx >= 0) {
2184 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002185 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002186 mCurrentState.displays.removeItemsAt(idx);
2187 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002188 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002189 }
2190
2191 processDisplayChangesLocked();
2192 }
2193
2194 mPendingHotplugEvents.clear();
2195}
2196
Lloyd Pique99d3da52018-01-22 17:48:03 -08002197sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002198 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002199 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002200 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002201 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002202 HdrCapabilities hdrCapabilities;
2203 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002204
Peiyong Lin13effd12018-07-24 17:01:47 -07002205 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002206 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002207 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002208 if (isWideColorMode(colorMode)) {
2209 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002210 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002211
Dominik Laskowski7e045462018-05-30 13:02:02 -07002212 std::vector<RenderIntent> renderIntents =
2213 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002214 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002215 }
tangrobin6753a022018-08-10 10:58:54 +08002216 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002217
tangrobin6753a022018-08-10 10:58:54 +08002218 if (displayId >= 0) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002219 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2220 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2221 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002222
2223 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2224 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2225
2226 /*
2227 * Create our display's surface
2228 */
2229 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2230 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002231 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002232 renderSurface->setNativeWindow(nativeWindow.get());
2233 const int displayWidth = renderSurface->queryWidth();
2234 const int displayHeight = renderSurface->queryHeight();
2235
2236 // Make sure that composition can never be stalled by a virtual display
2237 // consumer that isn't processing buffers fast enough. We have to do this
2238 // in two places:
2239 // * Here, in case the display is composed entirely by HWC.
2240 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2241 // window's swap interval in eglMakeCurrent, so they'll override the
2242 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002243 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002244 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2245 }
2246
2247 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002248 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002249
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002250 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002251 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2252 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2253 displayHeight, hasWideColorGamut, hdrCapabilities,
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002254 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002255
2256 if (maxFrameBufferAcquiredBuffers >= 3) {
2257 nativeWindowSurface->preallocateBuffers();
2258 }
2259
2260 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002261 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2262 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002263 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002264 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002265 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002266 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002267 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002268 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002269 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002270 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002271 display->setLayerStack(state.layerStack);
2272 display->setProjection(state.orientation, state.viewport, state.frame);
2273 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002274
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002275 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002276}
2277
Lloyd Pique347200f2017-12-14 17:00:15 -08002278void SurfaceFlinger::processDisplayChangesLocked() {
2279 // here we take advantage of Vector's copy-on-write semantics to
2280 // improve performance by skipping the transaction entirely when
2281 // know that the lists are identical
2282 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2283 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2284 if (!curr.isIdenticalTo(draw)) {
2285 mVisibleRegionsDirty = true;
2286 const size_t cc = curr.size();
2287 size_t dc = draw.size();
2288
2289 // find the displays that were removed
2290 // (ie: in drawing state but not in current state)
2291 // also handle displays that changed
2292 // (ie: displays that are in both lists)
2293 for (size_t i = 0; i < dc;) {
2294 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2295 if (j < 0) {
2296 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002297 // Call makeCurrent() on the primary display so we can
2298 // be sure that nothing associated with this display
2299 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002300 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2301 defaultDisplay->makeCurrent();
2302 }
2303 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2304 display->disconnect(getHwComposer());
2305 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002306 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2307 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2308 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2309 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2310 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002311 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002312 } else {
2313 // this display is in both lists. see if something changed.
2314 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002315 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002316 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2317 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2318 if (state_binder != draw_binder) {
2319 // changing the surface is like destroying and
2320 // recreating the DisplayDevice, so we just remove it
2321 // from the drawing state, so that it get re-added
2322 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002323 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2324 display->disconnect(getHwComposer());
2325 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002326 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002327 mDrawingState.displays.removeItemsAt(i);
2328 dc--;
2329 // at this point we must loop to the next item
2330 continue;
2331 }
2332
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002333 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002334 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002335 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002336 }
2337 if ((state.orientation != draw[i].orientation) ||
2338 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002339 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002340 }
2341 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002342 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002343 }
2344 }
2345 }
2346 ++i;
2347 }
2348
2349 // find displays that were added
2350 // (ie: in current state but not in drawing state)
2351 for (size_t i = 0; i < cc; i++) {
2352 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2353 const DisplayDeviceState& state(curr[i]);
2354
2355 sp<DisplaySurface> dispSurface;
2356 sp<IGraphicBufferProducer> producer;
2357 sp<IGraphicBufferProducer> bqProducer;
2358 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002359 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002360
Dominik Laskowski7e045462018-05-30 13:02:02 -07002361 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002362 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002363 // Virtual displays without a surface are dormant:
2364 // they have external state (layer stack, projection,
2365 // etc.) but no internal state (i.e. a DisplayDevice).
2366 if (state.surface != nullptr) {
2367 // Allow VR composer to use virtual displays.
2368 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2369 int width = 0;
2370 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2371 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2372 int height = 0;
2373 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2374 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2375 int intFormat = 0;
2376 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2377 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002378 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002379
Dominik Laskowski7e045462018-05-30 13:02:02 -07002380 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2381 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002382 }
2383
2384 // TODO: Plumb requested format back up to consumer
2385
2386 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002387 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002388 bqProducer, bqConsumer,
2389 state.displayName);
2390
2391 dispSurface = vds;
2392 producer = vds;
2393 }
2394 } else {
2395 ALOGE_IF(state.surface != nullptr,
2396 "adding a supported display, but rendering "
2397 "surface is provided (%p), ignoring it",
2398 state.surface.get());
2399
Dominik Laskowski7e045462018-05-30 13:02:02 -07002400 displayId = state.type;
2401 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002402 producer = bqProducer;
2403 }
2404
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002405 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002406 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002407 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002408 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002409 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002410 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002411 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2412 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2413 true);
2414 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2415 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2416 true);
2417 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002418 }
2419 }
2420 }
2421 }
2422 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002423
2424 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002425}
2426
Mathias Agopian87baae12012-07-31 12:38:26 -07002427void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002428{
Dan Stoza7dde5992015-05-22 09:51:44 -07002429 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002430 mCurrentState.traverseInZOrder([](Layer* layer) {
2431 layer->notifyAvailableFrames();
2432 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002433
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002434 /*
2435 * Traversal of the children
2436 * (perform the transaction for each of them if needed)
2437 */
2438
Mathias Agopian3559b072012-08-15 13:46:03 -07002439 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002440 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002441 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002442 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002443
2444 const uint32_t flags = layer->doTransaction(0);
2445 if (flags & Layer::eVisibleRegion)
2446 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002447 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002448 }
2449
2450 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002451 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002452 */
2453
Mathias Agopiane57f2922012-08-09 16:29:12 -07002454 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002455 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002456 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002457 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002458
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002459 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002460 // The transform hint might have changed for some layers
2461 // (either because a display has changed, or because a layer
2462 // as changed).
2463 //
2464 // Walk through all the layers in currentLayers,
2465 // and update their transform hint.
2466 //
2467 // If a layer is visible only on a single display, then that
2468 // display is used to calculate the hint, otherwise we use the
2469 // default display.
2470 //
2471 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2472 // the hint is set before we acquire a buffer from the surface texture.
2473 //
2474 // NOTE: layer transactions have taken place already, so we use their
2475 // drawing state. However, SurfaceFlinger's own transaction has not
2476 // happened yet, so we must use the current state layer list
2477 // (soon to become the drawing state list).
2478 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002479 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002480 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002481 bool first = true;
2482 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002483 // NOTE: we rely on the fact that layers are sorted by
2484 // layerStack first (so we don't have to traverse the list
2485 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002486 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002487 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002488 currentlayerStack = layerStack;
2489 // figure out if this layerstack is mirrored
2490 // (more than one display) if so, pick the default display,
2491 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002492 hintDisplay = nullptr;
2493 for (const auto& [token, display] : mDisplays) {
2494 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2495 if (hintDisplay) {
2496 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002497 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002498 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002499 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002500 }
2501 }
2502 }
2503 }
Chet Haase91d25932013-04-11 15:24:55 -07002504
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002505 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002506 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2507 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002508
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002509 // could be null when this layer is using a layerStack
2510 // that is not visible on any display. Also can occur at
2511 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002512 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002513 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002514
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002515 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002516 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002517 if (hintDisplay) {
2518 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002519 }
Robert Carr2047fae2016-11-28 14:09:09 -08002520
2521 first = false;
2522 });
Mathias Agopian84300952012-11-21 16:02:13 -08002523 }
2524
2525
Mathias Agopian3559b072012-08-15 13:46:03 -07002526 /*
2527 * Perform our own transaction if needed
2528 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002529
2530 if (mLayersAdded) {
2531 mLayersAdded = false;
2532 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002533 mVisibleRegionsDirty = true;
2534 }
2535
2536 // some layers might have been removed, so
2537 // we need to update the regions they're exposing.
2538 if (mLayersRemoved) {
2539 mLayersRemoved = false;
2540 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002541 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002542 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002543 // this layer is not visible anymore
2544 // TODO: we could traverse the tree from front to back and
2545 // compute the actual visible region
2546 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002547 Region visibleReg;
2548 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002549 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002550 }
Robert Carr2047fae2016-11-28 14:09:09 -08002551 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002552 }
2553
2554 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002555
2556 updateCursorAsync();
2557}
2558
2559void SurfaceFlinger::updateCursorAsync()
2560{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002561 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002562 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002563 continue;
2564 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002565
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002566 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2567 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002568 }
2569 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002570}
2571
2572void SurfaceFlinger::commitTransaction()
2573{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002574 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002575 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002576 for (const auto& l : mLayersPendingRemoval) {
2577 recordBufferingStats(l->getName().string(),
2578 l->getOccupancyHistory(true));
2579 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002580 }
2581 mLayersPendingRemoval.clear();
2582 }
2583
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002584 // If this transaction is part of a window animation then the next frame
2585 // we composite should be considered an animation as well.
2586 mAnimCompositionPending = mAnimTransactionPending;
2587
Mathias Agopian4fec8732012-06-29 14:12:52 -07002588 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002589 // clear the "changed" flags in current state
2590 mCurrentState.colorMatrixChanged = false;
2591
Robert Carr1f0a16a2016-10-24 16:27:39 -07002592 mDrawingState.traverseInZOrder([](Layer* layer) {
2593 layer->commitChildList();
2594 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002595 mTransactionPending = false;
2596 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002597 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002598}
2599
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002600void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2601 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002602 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002603 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002604
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002605 Region aboveOpaqueLayers;
2606 Region aboveCoveredLayers;
2607 Region dirty;
2608
Mathias Agopian87baae12012-07-31 12:38:26 -07002609 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002610
Robert Carr2047fae2016-11-28 14:09:09 -08002611 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002612 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002613 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002614
Jesse Hall01e29052013-02-19 16:13:35 -08002615 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002616 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002617 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002618 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002619
Mathias Agopianab028732010-03-16 16:41:46 -07002620 /*
2621 * opaqueRegion: area of a surface that is fully opaque.
2622 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002623 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002624
2625 /*
2626 * visibleRegion: area of a surface that is visible on screen
2627 * and not fully transparent. This is essentially the layer's
2628 * footprint minus the opaque regions above it.
2629 * Areas covered by a translucent surface are considered visible.
2630 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002631 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002632
2633 /*
2634 * coveredRegion: area of a surface that is covered by all
2635 * visible regions above it (which includes the translucent areas).
2636 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002637 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002638
Jesse Halla8026d22012-09-25 13:25:04 -07002639 /*
2640 * transparentRegion: area of a surface that is hinted to be completely
2641 * transparent. This is only used to tell when the layer has no visible
2642 * non-transparent regions and can be removed from the layer list. It
2643 * does not affect the visibleRegion of this layer or any layers
2644 * beneath it. The hint may not be correct if apps don't respect the
2645 * SurfaceView restrictions (which, sadly, some don't).
2646 */
2647 Region transparentRegion;
2648
Mathias Agopianab028732010-03-16 16:41:46 -07002649
2650 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002651 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002652 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002653 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002654 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002655 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002656 if (!visibleRegion.isEmpty()) {
2657 // Remove the transparent area from the visible region
2658 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002659 if (tr.preserveRects()) {
2660 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002661 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002662 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002663 // transformation too complex, can't do the
2664 // transparent region optimization.
2665 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002666 }
Mathias Agopianab028732010-03-16 16:41:46 -07002667 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002668
Mathias Agopianab028732010-03-16 16:41:46 -07002669 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002670 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002671 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002672 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002673 // the opaque region is the layer's footprint
2674 opaqueRegion = visibleRegion;
2675 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002676 }
2677 }
2678
Robert Carre5f4f692018-01-12 13:12:28 -08002679 if (visibleRegion.isEmpty()) {
2680 layer->clearVisibilityRegions();
2681 return;
2682 }
2683
Mathias Agopianab028732010-03-16 16:41:46 -07002684 // Clip the covered region to the visible region
2685 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2686
2687 // Update aboveCoveredLayers for next (lower) layer
2688 aboveCoveredLayers.orSelf(visibleRegion);
2689
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002690 // subtract the opaque region covered by the layers above us
2691 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002692
2693 // compute this layer's dirty region
2694 if (layer->contentDirty) {
2695 // we need to invalidate the whole region
2696 dirty = visibleRegion;
2697 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002698 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002699 layer->contentDirty = false;
2700 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002701 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002702 * the exposed region consists of two components:
2703 * 1) what's VISIBLE now and was COVERED before
2704 * 2) what's EXPOSED now less what was EXPOSED before
2705 *
2706 * note that (1) is conservative, we start with the whole
2707 * visible region but only keep what used to be covered by
2708 * something -- which mean it may have been exposed.
2709 *
2710 * (2) handles areas that were not covered by anything but got
2711 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002712 */
Mathias Agopianab028732010-03-16 16:41:46 -07002713 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002714 const Region oldVisibleRegion = layer->visibleRegion;
2715 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002716 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2717 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002718 }
2719 dirty.subtractSelf(aboveOpaqueLayers);
2720
2721 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002722 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002723
Mathias Agopianab028732010-03-16 16:41:46 -07002724 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002725 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002726
Jesse Halla8026d22012-09-25 13:25:04 -07002727 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002728 layer->setVisibleRegion(visibleRegion);
2729 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002730 layer->setVisibleNonTransparentRegion(
2731 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002732 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002733
Mathias Agopian87baae12012-07-31 12:38:26 -07002734 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002735}
2736
Chia-I Wuab0c3192017-08-01 11:29:00 -07002737void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002738 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002739 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2740 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002741 }
2742 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002743}
2744
Dan Stoza6b9454d2014-11-07 16:00:59 -08002745bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002746{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002747 ALOGV("handlePageFlip");
2748
Brian Andersond6927fb2016-07-23 23:37:30 -07002749 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002750
Mathias Agopian4fec8732012-06-29 14:12:52 -07002751 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002752 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002753 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002754
2755 // Store the set of layers that need updates. This set must not change as
2756 // buffers are being latched, as this could result in a deadlock.
2757 // Example: Two producers share the same command stream and:
2758 // 1.) Layer 0 is latched
2759 // 2.) Layer 0 gets a new frame
2760 // 2.) Layer 1 gets a new frame
2761 // 3.) Layer 1 is latched.
2762 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2763 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002764 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002765 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002766 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07002767 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002768 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002769 } else {
2770 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002771 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002772 } else {
2773 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002774 }
Robert Carr2047fae2016-11-28 14:09:09 -08002775 });
2776
Dan Stoza9e56aa02015-11-02 13:00:03 -08002777 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002778 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002779 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002780 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002781 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002782 newDataLatched = true;
2783 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002784 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002785
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002786 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002787
2788 // If we will need to wake up at some time in the future to deal with a
2789 // queued frame that shouldn't be displayed during this vsync period, wake
2790 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002791 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002792 signalLayerUpdate();
2793 }
2794
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002795 // enter boot animation on first buffer latch
2796 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2797 ALOGI("Enter boot animation");
2798 mBootStage = BootStage::BOOTANIMATION;
2799 }
2800
Dan Stoza6b9454d2014-11-07 16:00:59 -08002801 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002802 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002803}
2804
Mathias Agopianad456f92011-01-13 17:53:01 -08002805void SurfaceFlinger::invalidateHwcGeometry()
2806{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002807 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002808}
2809
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002810void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2811 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002812 // We only need to actually compose the display if:
2813 // 1) It is being handled by hardware composer, which may need this to
2814 // keep its virtual display state machine in sync, or
2815 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002816 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002817 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002818 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002819 return;
2820 }
2821
Dan Stoza9e56aa02015-11-02 13:00:03 -08002822 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002823 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002824
2825 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002826 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002827}
2828
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002829bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002830 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002831
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002832 const Region bounds(display->bounds());
2833 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002834 const auto displayId = display->getId();
2835 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002836 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002837
Chia-I Wu8e50e692018-05-04 10:12:37 -07002838 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002839 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002840
Dan Stoza9e56aa02015-11-02 13:00:03 -08002841 if (hasClientComposition) {
2842 ALOGV("hasClientComposition");
2843
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002844 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002845 if (display->hasWideColorGamut()) {
2846 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002847 }
2848 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002849 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002850 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002851
Dominik Laskowski7e045462018-05-30 13:02:02 -07002852 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002853 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2854 HWC2::Capability::SkipClientColorTransform);
2855
Chia-I Wud49d6692018-06-27 07:17:41 +08002856 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002857 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2858 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08002859 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002860 }
2861
Chia-I Wud49d6692018-06-27 07:17:41 +08002862 // The current enhanced saturation matrix is designed to enhance Display P3,
2863 // thus we only apply this matrix when the render intent is not colorimetric
2864 // and the output color space is Display P3.
2865 needsEnhancedColorMatrix =
2866 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2867 outputDataspace == Dataspace::DISPLAY_P3);
2868 if (needsEnhancedColorMatrix) {
2869 colorMatrix *= mEnhancedSaturationMatrix;
2870 }
2871
2872 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002873
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002874 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002875 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002876 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002877 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002878
2879 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002880 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2881 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2882 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002883 }
2884 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002885 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002886
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002887 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002888 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002889 // when using overlays, we assume a fully transparent framebuffer
2890 // NOTE: we could reduce how much we need to clear, for instance
2891 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002892 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002893 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002894 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002895 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002896 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002897 // we're left with the letterbox region
2898 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002899 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07002900
2901 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002902 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07002903
Mathias Agopianb9494d52012-04-18 02:28:45 -07002904 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002905 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002906 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002907 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002908 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002909 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002910
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002911 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002912 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002913 // scissor on the main display. It should never be needed
2914 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002915 const Rect& bounds = display->getBounds();
2916 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07002917 if (scissor != bounds) {
2918 // scissor doesn't match the screen's dimensions, so we
2919 // need to clear everything outside of it and enable
2920 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002921
Mathias Agopianf45c5102012-10-24 16:29:17 -07002922 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002923 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002924 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002925 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002926 }
2927 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002928 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002929
Mathias Agopian85d751c2012-08-29 16:59:24 -07002930 /*
2931 * and then, render the layers targeted at the framebuffer
2932 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002933
Dan Stoza9e56aa02015-11-02 13:00:03 -08002934 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07002935 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002936 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002937 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002938 const Region clip(bounds.intersect(
2939 displayTransform.transform(layer->visibleRegion)));
2940 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002941 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002942 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002943 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002944 case HWC2::Composition::Cursor:
2945 case HWC2::Composition::Device:
2946 case HWC2::Composition::Sideband:
2947 case HWC2::Composition::SolidColor: {
2948 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002949 if (layer->getClearClientTarget(displayId) && !firstLayer &&
Rajavenu Kyatham2eae6d32018-04-10 12:34:05 +05302950 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
2951 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002952 // never clear the very first layer since we're
2953 // guaranteed the FB is already cleared
2954 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002955 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002956 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002957 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002958 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002959 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002960 break;
2961 }
2962 default:
2963 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002964 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002965 } else {
2966 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002967 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002968 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002969 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002970
Chia-I Wud49d6692018-06-27 07:17:41 +08002971 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002972 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002973 }
2974
Mathias Agopianf45c5102012-10-24 16:29:17 -07002975 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002976 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002977 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002978}
2979
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002980void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
2981 const Region& region) const {
2982 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002983 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002984 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002985}
2986
Dan Stoza7d89d062015-04-30 13:29:25 -07002987status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002988 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002989 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002990 const sp<Layer>& lbc,
2991 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002992{
Dan Stoza7d89d062015-04-30 13:29:25 -07002993 // add this layer to the current state list
2994 {
2995 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002996 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002997 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2998 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002999 return NO_MEMORY;
3000 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003001 if (parent == nullptr) {
3002 mCurrentState.layersSortedByZ.add(lbc);
3003 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003004 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003005 ALOGE("addClientLayer called with a removed parent");
3006 return NAME_NOT_FOUND;
3007 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003008 parent->addChild(lbc);
3009 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003010
Yiwei Zhang243b3782018-05-15 17:40:04 -07003011 if (gbc != nullptr) {
3012 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3013 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3014 mMaxGraphicBufferProducerListSize,
3015 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3016 mGraphicBufferProducerList.size(),
3017 mMaxGraphicBufferProducerListSize, mNumLayers);
3018 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003019 mLayersAdded = true;
3020 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003021 }
3022
Mathias Agopian96f08192010-06-02 23:28:45 -07003023 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003024 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003025
Dan Stoza7d89d062015-04-30 13:29:25 -07003026 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003027}
3028
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003029status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003030 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003031 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3032}
Robert Carr7f9b8992017-03-10 11:08:39 -08003033
chaviwca27f252018-02-06 16:46:39 -08003034status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3035 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003036 if (layer->isPendingRemoval()) {
3037 return NO_ERROR;
3038 }
3039
Robert Carr1f0a16a2016-10-24 16:27:39 -07003040 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003041 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003042 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003043 if (topLevelOnly) {
3044 return NO_ERROR;
3045 }
3046
Chia-I Wu98f1c102017-05-30 14:54:08 -07003047 sp<Layer> ancestor = p;
3048 while (ancestor->getParent() != nullptr) {
3049 ancestor = ancestor->getParent();
3050 }
3051 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3052 ALOGE("removeLayer called with a layer whose parent has been removed");
3053 return NAME_NOT_FOUND;
3054 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003055
3056 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003057 } else {
3058 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003059 }
3060
Robert Carr136e2f62017-02-08 17:54:29 -08003061 // As a matter of normal operation, the LayerCleaner will produce a second
3062 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3063 // so we will succeed in promoting it, but it's already been removed
3064 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3065 // otherwise something has gone wrong and we are leaking the layer.
3066 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003067 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3068 layer->getName().string(),
3069 (p != nullptr) ? p->getName().string() : "no-parent");
3070 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003071 } else if (index < 0) {
3072 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003073 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003074
Chia-I Wuc6657022017-08-15 11:18:17 -07003075 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003076 mLayersPendingRemoval.add(layer);
3077 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003078 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003079 setTransactionFlags(eTransactionNeeded);
3080 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003081}
3082
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003083uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003084 return android_atomic_release_load(&mTransactionFlags);
3085}
3086
Mathias Agopian3f844832013-08-07 21:24:32 -07003087uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003088 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3089}
3090
Mathias Agopian3f844832013-08-07 21:24:32 -07003091uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003092 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3093}
3094
3095uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3096 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003097 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003098 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003099 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003100 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003101 }
3102 return old;
3103}
3104
chaviwca27f252018-02-06 16:46:39 -08003105bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3106 for (const ComposerState& state : states) {
3107 // Here we need to check that the interface we're given is indeed
3108 // one of our own. A malicious client could give us a nullptr
3109 // IInterface, or one of its own or even one of our own but a
3110 // different type. All these situations would cause us to crash.
3111 if (state.client == nullptr) {
3112 return true;
3113 }
3114
3115 sp<IBinder> binder = IInterface::asBinder(state.client);
3116 if (binder == nullptr) {
3117 return true;
3118 }
3119
3120 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3121 return true;
3122 }
3123 }
3124 return false;
3125}
3126
Mathias Agopian8b33f032012-07-24 20:43:54 -07003127void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003128 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003129 const Vector<DisplayState>& displays,
3130 uint32_t flags)
3131{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003132 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003133 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003134 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003135
chaviwca27f252018-02-06 16:46:39 -08003136 if (containsAnyInvalidClientState(states)) {
3137 return;
3138 }
3139
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003140 if (flags & eAnimation) {
3141 // For window updates that are part of an animation we must wait for
3142 // previous animation "frames" to be handled.
3143 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003144 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003145 if (CC_UNLIKELY(err != NO_ERROR)) {
3146 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003147 // caller after a few seconds.
3148 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3149 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003150 mAnimTransactionPending = false;
3151 break;
3152 }
3153 }
3154 }
3155
chaviwca27f252018-02-06 16:46:39 -08003156 for (const DisplayState& display : displays) {
3157 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003158 }
3159
chaviwca27f252018-02-06 16:46:39 -08003160 for (const ComposerState& state : states) {
3161 transactionFlags |= setClientStateLocked(state);
3162 }
3163
3164 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3165 // as destroyed should only occur after setting all other states. This is to allow for a
3166 // child re-parent to happen before marking its original parent as destroyed (which would
3167 // then mark the child as destroyed).
3168 for (const ComposerState& state : states) {
3169 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003170 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003171
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003172 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3173 // anyway. This can be used as a flush mechanism for previous async transactions.
3174 // Empty animation transaction can be used to simulate back-pressure, so also force a
3175 // transaction for empty animation transactions.
3176 if (transactionFlags == 0 &&
3177 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003178 transactionFlags = eTransactionNeeded;
3179 }
3180
Mathias Agopian386aa982011-11-07 21:58:03 -08003181 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003182 if (mInterceptor->isEnabled()) {
3183 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003184 }
Irvel468051e2016-06-13 16:44:44 -07003185
Mathias Agopian386aa982011-11-07 21:58:03 -08003186 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003187 const auto start = (flags & eEarlyWakeup)
3188 ? VSyncModulator::TransactionStart::EARLY
3189 : VSyncModulator::TransactionStart::NORMAL;
3190 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003191
3192 // if this is a synchronous transaction, wait for it to take effect
3193 // before returning.
3194 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003195 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003196 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003197 if (flags & eAnimation) {
3198 mAnimTransactionPending = true;
3199 }
3200 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003201 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3202 if (CC_UNLIKELY(err != NO_ERROR)) {
3203 // just in case something goes wrong in SF, return to the
3204 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003205 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3206 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003207 break;
3208 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003209 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003210 }
3211}
3212
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003213uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3214 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3215 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003216
Mathias Agopiane57f2922012-08-09 16:29:12 -07003217 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003218 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3219
3220 const uint32_t what = s.what;
3221 if (what & DisplayState::eSurfaceChanged) {
3222 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3223 state.surface = s.surface;
3224 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003225 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003226 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003227 if (what & DisplayState::eLayerStackChanged) {
3228 if (state.layerStack != s.layerStack) {
3229 state.layerStack = s.layerStack;
3230 flags |= eDisplayTransactionNeeded;
3231 }
3232 }
3233 if (what & DisplayState::eDisplayProjectionChanged) {
3234 if (state.orientation != s.orientation) {
3235 state.orientation = s.orientation;
3236 flags |= eDisplayTransactionNeeded;
3237 }
3238 if (state.frame != s.frame) {
3239 state.frame = s.frame;
3240 flags |= eDisplayTransactionNeeded;
3241 }
3242 if (state.viewport != s.viewport) {
3243 state.viewport = s.viewport;
3244 flags |= eDisplayTransactionNeeded;
3245 }
3246 }
3247 if (what & DisplayState::eDisplaySizeChanged) {
3248 if (state.width != s.width) {
3249 state.width = s.width;
3250 flags |= eDisplayTransactionNeeded;
3251 }
3252 if (state.height != s.height) {
3253 state.height = s.height;
3254 flags |= eDisplayTransactionNeeded;
3255 }
3256 }
3257
Mathias Agopiane57f2922012-08-09 16:29:12 -07003258 return flags;
3259}
3260
Robert Carrd4ae7f32018-06-07 16:10:57 -07003261bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3262 IPCThreadState* ipc = IPCThreadState::self();
3263 const int pid = ipc->getCallingPid();
3264 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003265 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003266 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003267 return false;
3268 }
3269 return true;
3270}
3271
chaviwca27f252018-02-06 16:46:39 -08003272uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3273 const layer_state_t& s = composerState.state;
3274 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3275
Mathias Agopian13127d82013-03-05 17:47:11 -08003276 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003277 if (layer == nullptr) {
3278 return 0;
3279 }
3280
3281 if (layer->isPendingRemoval()) {
3282 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3283 return 0;
3284 }
3285
3286 uint32_t flags = 0;
3287
3288 const uint32_t what = s.what;
3289 bool geometryAppliesWithResize =
3290 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003291
3292 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3293 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003294 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003295 layer->pushPendingState();
3296 }
3297
chaviw8b3871a2017-11-01 17:41:01 -07003298 if (what & layer_state_t::ePositionChanged) {
3299 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3300 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003301 }
chaviw8b3871a2017-11-01 17:41:01 -07003302 }
3303 if (what & layer_state_t::eLayerChanged) {
3304 // NOTE: index needs to be calculated before we update the state
3305 const auto& p = layer->getParent();
3306 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003307 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003308 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003309 mCurrentState.layersSortedByZ.removeAt(idx);
3310 mCurrentState.layersSortedByZ.add(layer);
3311 // we need traversal (state changed)
3312 // AND transaction (list changed)
3313 flags |= eTransactionNeeded|eTraversalNeeded;
3314 }
chaviw8b3871a2017-11-01 17:41:01 -07003315 } else {
3316 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003317 flags |= eTransactionNeeded|eTraversalNeeded;
3318 }
3319 }
chaviw8b3871a2017-11-01 17:41:01 -07003320 }
3321 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003322 // NOTE: index needs to be calculated before we update the state
3323 const auto& p = layer->getParent();
3324 if (p == nullptr) {
3325 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3326 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3327 mCurrentState.layersSortedByZ.removeAt(idx);
3328 mCurrentState.layersSortedByZ.add(layer);
3329 // we need traversal (state changed)
3330 // AND transaction (list changed)
3331 flags |= eTransactionNeeded|eTraversalNeeded;
3332 }
3333 } else {
3334 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3335 flags |= eTransactionNeeded|eTraversalNeeded;
3336 }
chaviw8b3871a2017-11-01 17:41:01 -07003337 }
3338 }
3339 if (what & layer_state_t::eSizeChanged) {
3340 if (layer->setSize(s.w, s.h)) {
3341 flags |= eTraversalNeeded;
3342 }
3343 }
3344 if (what & layer_state_t::eAlphaChanged) {
3345 if (layer->setAlpha(s.alpha))
3346 flags |= eTraversalNeeded;
3347 }
3348 if (what & layer_state_t::eColorChanged) {
3349 if (layer->setColor(s.color))
3350 flags |= eTraversalNeeded;
3351 }
3352 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003353 // TODO: b/109894387
3354 //
3355 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3356 // rotation. To see the problem observe that if we have a square parent, and a child
3357 // of the same size, then we rotate the child 45 degrees around it's center, the child
3358 // must now be cropped to a non rectangular 8 sided region.
3359 //
3360 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3361 // private API, and the WindowManager only uses rotation in one case, which is on a top
3362 // level layer in which cropping is not an issue.
3363 //
3364 // However given that abuse of rotation matrices could lead to surfaces extending outside
3365 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3366 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3367 // transformations.
3368 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003369 flags |= eTraversalNeeded;
3370 }
3371 if (what & layer_state_t::eTransparentRegionChanged) {
3372 if (layer->setTransparentRegionHint(s.transparentRegion))
3373 flags |= eTraversalNeeded;
3374 }
3375 if (what & layer_state_t::eFlagsChanged) {
3376 if (layer->setFlags(s.flags, s.mask))
3377 flags |= eTraversalNeeded;
3378 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003379 if (what & layer_state_t::eCropChanged_legacy) {
3380 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003381 flags |= eTraversalNeeded;
3382 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003383 if (what & layer_state_t::eFinalCropChanged_legacy) {
3384 if (layer->setFinalCrop_legacy(s.finalCrop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003385 flags |= eTraversalNeeded;
3386 }
3387 if (what & layer_state_t::eLayerStackChanged) {
3388 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3389 // We only allow setting layer stacks for top level layers,
3390 // everything else inherits layer stack from its parent.
3391 if (layer->hasParent()) {
3392 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3393 layer->getName().string());
3394 } else if (idx < 0) {
3395 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3396 "that also does not appear in the top level layer list. Something"
3397 " has gone wrong.", layer->getName().string());
3398 } else if (layer->setLayerStack(s.layerStack)) {
3399 mCurrentState.layersSortedByZ.removeAt(idx);
3400 mCurrentState.layersSortedByZ.add(layer);
3401 // we need traversal (state changed)
3402 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003403 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003404 }
3405 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003406 if (what & layer_state_t::eDeferTransaction_legacy) {
3407 if (s.barrierHandle_legacy != nullptr) {
3408 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3409 } else if (s.barrierGbp_legacy != nullptr) {
3410 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003411 if (authenticateSurfaceTextureLocked(gbp)) {
3412 const auto& otherLayer =
3413 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003414 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003415 } else {
3416 ALOGE("Attempt to defer transaction to to an"
3417 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003418 }
3419 }
chaviw8b3871a2017-11-01 17:41:01 -07003420 // We don't trigger a traversal here because if no other state is
3421 // changed, we don't want this to cause any more work
3422 }
3423 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003424 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003425 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003426 if (!hadParent) {
3427 mCurrentState.layersSortedByZ.remove(layer);
3428 }
chaviw8b3871a2017-11-01 17:41:01 -07003429 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003430 }
chaviw8b3871a2017-11-01 17:41:01 -07003431 }
3432 if (what & layer_state_t::eReparentChildren) {
3433 if (layer->reparentChildren(s.reparentHandle)) {
3434 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003435 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003436 }
chaviw8b3871a2017-11-01 17:41:01 -07003437 if (what & layer_state_t::eDetachChildren) {
3438 layer->detachChildren();
3439 }
3440 if (what & layer_state_t::eOverrideScalingModeChanged) {
3441 layer->setOverrideScalingMode(s.overrideScalingMode);
3442 // We don't trigger a traversal here because if no other state is
3443 // changed, we don't want this to cause any more work
3444 }
Marissa Wall61c58622018-07-18 10:12:20 -07003445 if (what & layer_state_t::eTransformChanged) {
3446 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3447 }
3448 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3449 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3450 flags |= eTraversalNeeded;
3451 }
3452 if (what & layer_state_t::eCropChanged) {
3453 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3454 }
3455 if (what & layer_state_t::eBufferChanged) {
3456 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3457 }
3458 if (what & layer_state_t::eAcquireFenceChanged) {
3459 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3460 }
3461 if (what & layer_state_t::eDataspaceChanged) {
3462 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3463 }
3464 if (what & layer_state_t::eHdrMetadataChanged) {
3465 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3466 }
3467 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3468 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3469 }
3470 if (what & layer_state_t::eApiChanged) {
3471 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3472 }
3473 if (what & layer_state_t::eSidebandStreamChanged) {
3474 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3475 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003476 return flags;
3477}
3478
chaviwca27f252018-02-06 16:46:39 -08003479void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3480 const layer_state_t& state = composerState.state;
3481 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3482
3483 sp<Layer> layer(client->getLayerUser(state.surface));
3484 if (layer == nullptr) {
3485 return;
3486 }
3487
3488 if (layer->isPendingRemoval()) {
3489 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3490 return;
3491 }
3492
3493 if (state.what & layer_state_t::eDestroySurface) {
3494 removeLayerLocked(mStateLock, layer);
3495 }
3496}
3497
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003498status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003499 const String8& name,
3500 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003501 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003502 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003503 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003504{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003505 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003506 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003507 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003508 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003509 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003510
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003511 status_t result = NO_ERROR;
3512
3513 sp<Layer> layer;
3514
Cody Northropbc755282017-03-31 12:00:08 -06003515 String8 uniqueName = getUniqueLayerName(name);
3516
Mathias Agopian3165cc22012-08-08 19:42:09 -07003517 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003518 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003519 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3520 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003521
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003522 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003523 case ISurfaceComposerClient::eFXSurfaceBufferState:
3524 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3525 break;
chaviw13fdc492017-06-27 12:40:18 -07003526 case ISurfaceComposerClient::eFXSurfaceColor:
3527 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003528 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003529 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003530 break;
3531 default:
3532 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003533 break;
3534 }
3535
Dan Stoza7d89d062015-04-30 13:29:25 -07003536 if (result != NO_ERROR) {
3537 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003538 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003539
Chia-I Wuab0c3192017-08-01 11:29:00 -07003540 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3541 // TODO b/64227542
3542 if (windowType == 441731) {
3543 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3544 layer->setPrimaryDisplayOnly();
3545 }
3546
Albert Chaulk479c60c2017-01-27 14:21:34 -05003547 layer->setInfo(windowType, ownerUid);
3548
Robert Carr1f0a16a2016-10-24 16:27:39 -07003549 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003550 if (result != NO_ERROR) {
3551 return result;
3552 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003553 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003554
3555 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003556 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003557}
3558
Cody Northropbc755282017-03-31 12:00:08 -06003559String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3560{
3561 bool matchFound = true;
3562 uint32_t dupeCounter = 0;
3563
3564 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3565 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3566
Dan Stoza436ccf32018-06-21 12:10:12 -07003567 // Grab the state lock since we're accessing mCurrentState
3568 Mutex::Autolock lock(mStateLock);
3569
Cody Northropbc755282017-03-31 12:00:08 -06003570 // Loop over layers until we're sure there is no matching name
3571 while (matchFound) {
3572 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003573 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003574 if (layer->getName() == uniqueName) {
3575 matchFound = true;
3576 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3577 }
3578 });
3579 }
3580
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003581 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3582 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003583
3584 return uniqueName;
3585}
3586
Marissa Wallfd668622018-05-10 10:21:13 -07003587status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3588 uint32_t w, uint32_t h, uint32_t flags,
3589 PixelFormat& format, sp<IBinder>* handle,
3590 sp<IGraphicBufferProducer>* gbp,
3591 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003592 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003593 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003594 case PIXEL_FORMAT_TRANSPARENT:
3595 case PIXEL_FORMAT_TRANSLUCENT:
3596 format = PIXEL_FORMAT_RGBA_8888;
3597 break;
3598 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003599 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003600 break;
3601 }
3602
Marissa Wallfd668622018-05-10 10:21:13 -07003603 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3604 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003605 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003606 *handle = layer->getHandle();
3607 *gbp = layer->getProducer();
3608 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003609 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003610
Marissa Wallfd668622018-05-10 10:21:13 -07003611 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003612 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003613}
3614
Marissa Wall61c58622018-07-18 10:12:20 -07003615status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3616 uint32_t w, uint32_t h, uint32_t flags,
3617 sp<IBinder>* handle, sp<Layer>* outLayer) {
3618 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3619 *handle = layer->getHandle();
3620 *outLayer = layer;
3621
3622 return NO_ERROR;
3623}
3624
chaviw13fdc492017-06-27 12:40:18 -07003625status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003626 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003627 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003628{
chaviw13fdc492017-06-27 12:40:18 -07003629 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003630 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003631 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003632}
3633
Mathias Agopianac9fa422013-02-11 16:40:36 -08003634status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003635{
Robert Carr9524cb32017-02-13 11:32:32 -08003636 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003637 status_t err = NO_ERROR;
3638 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003639 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003640 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003641 err = removeLayer(l);
3642 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3643 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003644 }
3645 return err;
3646}
3647
Mathias Agopian13127d82013-03-05 17:47:11 -08003648status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003649{
Mathias Agopian67106042013-03-14 19:18:13 -07003650 // called by ~LayerCleaner() when all references to the IBinder (handle)
3651 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003652 sp<Layer> l = layer.promote();
3653 if (l == nullptr) {
3654 // The layer has already been removed, carry on
3655 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003656 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003657 // If we have a parent, then we can continue to live as long as it does.
3658 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003659}
3660
Mathias Agopianb60314a2012-04-10 22:09:54 -07003661// ---------------------------------------------------------------------------
3662
Andy McFadden13a082e2012-08-24 10:16:42 -07003663void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003664 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3665 if (!displayToken) return;
3666
Jesse Hall01e29052013-02-19 16:13:35 -08003667 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003668 Vector<ComposerState> state;
3669 Vector<DisplayState> displays;
3670 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003671 d.what = DisplayState::eDisplayProjectionChanged |
3672 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003673 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003674 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003675 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003676 d.frame.makeInvalid();
3677 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003678 d.width = 0;
3679 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003680 displays.add(d);
3681 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003682
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003683 const auto display = getDisplayDevice(displayToken);
3684 if (!display) return;
3685
3686 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3687
3688 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003689 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003690 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003691
Brian Andersond0010582017-03-07 13:20:31 -08003692 // Use phase of 0 since phase is not known.
3693 // Use latency of 0, which will snap to the ideal latency.
3694 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003695}
3696
3697void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003698 // Async since we may be called from the main thread.
3699 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003700}
3701
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003702void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3703 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003704 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003705 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003706
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003707 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003708 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003709 return;
3710 }
3711
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003712 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003713 ALOGW("Trying to set power mode for virtual display");
3714 return;
3715 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003716
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003717 display->setPowerMode(mode);
3718
Lloyd Pique4dccc412018-01-22 17:21:36 -08003719 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003720 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003721 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003722 if (idx < 0) {
3723 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3724 return;
3725 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003726 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003727 }
3728
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003729 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003730 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003731 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003732 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003733 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003734 // FIXME: eventthread only knows about the main display right now
3735 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003736 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003737 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003738
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003739 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003740 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003741 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003742
3743 struct sched_param param = {0};
3744 param.sched_priority = 1;
3745 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3746 ALOGW("Couldn't set SCHED_FIFO on display on");
3747 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003748 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003749 // Turn off the display
3750 struct sched_param param = {0};
3751 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3752 ALOGW("Couldn't set SCHED_OTHER on display off");
3753 }
3754
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003755 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003756 disableHardwareVsync(true); // also cancels any in-progress resync
3757
Mathias Agopiancde87a32012-09-13 14:09:01 -07003758 // FIXME: eventthread only knows about the main display right now
3759 mEventThread->onScreenReleased();
3760 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003761
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003762 getHwComposer().setPowerMode(type, mode);
3763 mVisibleRegionsDirty = true;
3764 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003765 } else if (mode == HWC_POWER_MODE_DOZE ||
3766 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003767 // Update display while dozing
3768 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003769 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003770 // FIXME: eventthread only knows about the main display right now
3771 mEventThread->onScreenAcquired();
3772 resyncToHardwareVsync(true);
3773 }
3774 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3775 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003776 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003777 disableHardwareVsync(true); // also cancels any in-progress resync
3778 // FIXME: eventthread only knows about the main display right now
3779 mEventThread->onScreenReleased();
3780 }
3781 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003782 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003783 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003784 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003785 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003786
3787 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003788}
3789
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003790void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003791 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003792 const auto display = getDisplayDevice(displayToken);
3793 if (!display) {
3794 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3795 displayToken.get());
3796 } else if (display->isVirtual()) {
3797 ALOGW("Attempt to set power mode %d for virtual display", mode);
3798 } else {
3799 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003800 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003801 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003802}
3803
3804// ---------------------------------------------------------------------------
3805
Lloyd Pique755e3192018-01-31 16:46:15 -08003806status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3807 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003808 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003809
Mathias Agopianbd115332013-04-18 16:41:04 -07003810 IPCThreadState* ipc = IPCThreadState::self();
3811 const int pid = ipc->getCallingPid();
3812 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003813
Mathias Agopianbd115332013-04-18 16:41:04 -07003814 if ((uid != AID_SHELL) &&
3815 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003816 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003817 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003818 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003819 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003820 // (this would indicate SF is stuck, but we want to be able to
3821 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003822 status_t err = mStateLock.timedLock(s2ns(1));
3823 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003824 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003825 result.appendFormat(
3826 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3827 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003828 }
3829
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003830 bool dumpAll = true;
3831 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003832 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003833
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003834 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003835 if ((index < numArgs) &&
3836 (args[index] == String16("--list"))) {
3837 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003838 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003839 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003840 }
3841
3842 if ((index < numArgs) &&
3843 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003844 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003845 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003846 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003847 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003848
3849 if ((index < numArgs) &&
3850 (args[index] == String16("--latency-clear"))) {
3851 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003852 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003853 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003854 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003855
3856 if ((index < numArgs) &&
3857 (args[index] == String16("--dispsync"))) {
3858 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07003859 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07003860 dumpAll = false;
3861 }
Dan Stozab90cf072015-03-05 11:05:59 -08003862
3863 if ((index < numArgs) &&
3864 (args[index] == String16("--static-screen"))) {
3865 index++;
3866 dumpStaticScreenStats(result);
3867 dumpAll = false;
3868 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003869
3870 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003871 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003872 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003873 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003874 dumpAll = false;
3875 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003876
3877 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3878 index++;
3879 dumpWideColorInfo(result);
3880 dumpAll = false;
3881 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003882
3883 if ((index < numArgs) &&
3884 (args[index] == String16("--enable-layer-stats"))) {
3885 index++;
3886 mLayerStats.enable();
3887 dumpAll = false;
3888 }
3889
3890 if ((index < numArgs) &&
3891 (args[index] == String16("--disable-layer-stats"))) {
3892 index++;
3893 mLayerStats.disable();
3894 dumpAll = false;
3895 }
3896
3897 if ((index < numArgs) &&
3898 (args[index] == String16("--clear-layer-stats"))) {
3899 index++;
3900 mLayerStats.clear();
3901 dumpAll = false;
3902 }
3903
3904 if ((index < numArgs) &&
3905 (args[index] == String16("--dump-layer-stats"))) {
3906 index++;
3907 mLayerStats.dump(result);
3908 dumpAll = false;
3909 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003910
3911 if ((index < numArgs) &&
3912 (args[index] == String16("--display-identification"))) {
3913 index++;
3914 dumpDisplayIdentificationData(result);
3915 dumpAll = false;
3916 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003917
3918 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3919 index++;
3920 mTimeStats.parseArgs(asProto, args, index, result);
3921 dumpAll = false;
3922 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003923 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003924
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003925 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003926 if (asProto) {
3927 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3928 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3929 } else {
3930 dumpAllLocked(args, index, result);
3931 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003932 }
3933
Mathias Agopian9795c422009-08-26 16:36:26 -07003934 if (locked) {
3935 mStateLock.unlock();
3936 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003937 }
3938 write(fd, result.string(), result.size());
3939 return NO_ERROR;
3940}
3941
Dan Stozac7014012014-02-14 15:03:43 -08003942void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3943 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003944{
Robert Carr2047fae2016-11-28 14:09:09 -08003945 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003946 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003947 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003948}
3949
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003950void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003951 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003952{
3953 String8 name;
3954 if (index < args.size()) {
3955 name = String8(args[index]);
3956 index++;
3957 }
3958
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003959 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
3960 getHwComposer().isConnected(displayId)) {
3961 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
3962 const nsecs_t period = activeConfig->getVsyncPeriod();
3963 result.appendFormat("%" PRId64 "\n", period);
3964 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003965
3966 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003967 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003968 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003969 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003970 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003971 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003972 }
Robert Carr2047fae2016-11-28 14:09:09 -08003973 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003974 }
3975}
3976
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003977void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003978 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003979{
3980 String8 name;
3981 if (index < args.size()) {
3982 name = String8(args[index]);
3983 index++;
3984 }
3985
Robert Carr2047fae2016-11-28 14:09:09 -08003986 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003987 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003988 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003989 }
Robert Carr2047fae2016-11-28 14:09:09 -08003990 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003991
Svetoslavd85084b2014-03-20 10:28:31 -07003992 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003993}
3994
Jamie Gennis6547ff42013-07-16 20:12:42 -07003995// This should only be called from the main thread. Otherwise it would need
3996// the lock and should use mCurrentState rather than mDrawingState.
3997void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003998 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003999 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004000 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004001
4002 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4003}
4004
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004005void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004006{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004007 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004008
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004009 if (isLayerTripleBufferingDisabled())
4010 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004011
4012 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004013 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004014 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004015 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004016 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4017 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004018 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004019}
4020
Dan Stozab90cf072015-03-05 11:05:59 -08004021void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4022{
4023 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004024 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4025 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004026 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004027 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004028 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4029 b + 1, bucketTimeSec, percent);
4030 }
David Sodman4a36e932017-11-07 14:29:47 -08004031 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004032 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004033 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004034 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004035 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004036}
4037
Dan Stozae77c7662016-05-13 11:37:28 -07004038void SurfaceFlinger::recordBufferingStats(const char* layerName,
4039 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004040 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4041 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004042 for (const auto& segment : history) {
4043 if (!segment.usedThirdBuffer) {
4044 stats.twoBufferTime += segment.totalTime;
4045 }
4046 if (segment.occupancyAverage < 1.0f) {
4047 stats.doubleBufferedTime += segment.totalTime;
4048 } else if (segment.occupancyAverage < 2.0f) {
4049 stats.tripleBufferedTime += segment.totalTime;
4050 }
4051 ++stats.numSegments;
4052 stats.totalTime += segment.totalTime;
4053 }
4054}
4055
Brian Andersond6927fb2016-07-23 23:37:30 -07004056void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4057 result.appendFormat("Layer frame timestamps:\n");
4058
4059 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4060 const size_t count = currentLayers.size();
4061 for (size_t i=0 ; i<count ; i++) {
4062 currentLayers[i]->dumpFrameEvents(result);
4063 }
4064}
4065
Dan Stozae77c7662016-05-13 11:37:28 -07004066void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4067 result.append("Buffering stats:\n");
4068 result.append(" [Layer name] <Active time> <Two buffer> "
4069 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004070 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004071 typedef std::tuple<std::string, float, float, float> BufferTuple;
4072 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004073 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004074 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004075 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004076 if (stats.numSegments == 0) {
4077 continue;
4078 }
4079 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4080 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4081 stats.totalTime;
4082 float doubleBufferRatio = static_cast<float>(
4083 stats.doubleBufferedTime) / stats.totalTime;
4084 float tripleBufferRatio = static_cast<float>(
4085 stats.tripleBufferedTime) / stats.totalTime;
4086 sorted.insert({activeTime, {name, twoBufferRatio,
4087 doubleBufferRatio, tripleBufferRatio}});
4088 }
4089 for (const auto& sortedPair : sorted) {
4090 float activeTime = sortedPair.first;
4091 const BufferTuple& values = sortedPair.second;
4092 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4093 std::get<0>(values).c_str(), activeTime,
4094 std::get<1>(values), std::get<2>(values),
4095 std::get<3>(values));
4096 }
4097 result.append("\n");
4098}
4099
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004100void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004101 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004102 const int32_t displayId = display->getId();
4103 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4104 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004105 continue;
4106 }
4107
Dominik Laskowski7e045462018-05-30 13:02:02 -07004108 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004109 uint8_t port;
4110 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004111 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004112 result.append("no identification data\n");
4113 continue;
4114 }
4115
4116 if (!isEdid(data)) {
4117 result.append("unknown identification data: ");
4118 for (uint8_t byte : data) {
4119 result.appendFormat("%x ", byte);
4120 }
4121 result.append("\n");
4122 continue;
4123 }
4124
4125 const auto edid = parseEdid(data);
4126 if (!edid) {
4127 result.append("invalid EDID: ");
4128 for (uint8_t byte : data) {
4129 result.appendFormat("%x ", byte);
4130 }
4131 result.append("\n");
4132 continue;
4133 }
4134
4135 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4136 result.append(edid->displayName.data(), edid->displayName.length());
4137 result.append("\"\n");
4138 }
4139 result.append("\n");
4140}
4141
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004142void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004143 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4144 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004145 result.appendFormat("DisplayColorSetting: %s\n",
4146 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004147
4148 // TODO: print out if wide-color mode is active or not
4149
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004150 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004151 const int32_t displayId = display->getId();
4152 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004153 continue;
4154 }
4155
Dominik Laskowski7e045462018-05-30 13:02:02 -07004156 result.appendFormat("Display %d color modes:\n", displayId);
4157 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004158 for (auto&& mode : modes) {
4159 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4160 }
4161
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004162 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004163 result.appendFormat(" Current color mode: %s (%d)\n",
4164 decodeColorMode(currentMode).c_str(), currentMode);
4165 }
4166 result.append("\n");
4167}
4168
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004169LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004170 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004171 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4172 const State& state = useDrawing ? mDrawingState : mCurrentState;
4173 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004174 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004175 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004176 });
4177
4178 return layersProto;
4179}
4180
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004181LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004182 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004183
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004184 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004185 resolution->set_w(display.getWidth());
4186 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004187
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004188 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4189 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4190 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004191
Dominik Laskowski7e045462018-05-30 13:02:02 -07004192 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004193 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004194 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004195 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004196 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004197 }
4198 });
4199
4200 return layersProto;
4201}
4202
Mathias Agopian74d211a2013-04-22 16:55:35 +02004203void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4204 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004205{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004206 bool colorize = false;
4207 if (index < args.size()
4208 && (args[index] == String16("--color"))) {
4209 colorize = true;
4210 index++;
4211 }
4212
4213 Colorizer colorizer(colorize);
4214
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004215 // figure out if we're stuck somewhere
4216 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004217 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004218 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4219
4220 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004221 * Dump library configuration.
4222 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004223
4224 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004225 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004226 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004227 appendSfConfigString(result);
4228 appendUiConfigString(result);
4229 appendGuiConfigString(result);
4230 result.append("\n");
4231
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004232 result.append("\nDisplay identification data:\n");
4233 dumpDisplayIdentificationData(result);
4234
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004235 result.append("\nWide-Color information:\n");
4236 dumpWideColorInfo(result);
4237
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004238 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004239 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004240 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004241 result.append(SyncFeatures::getInstance().toString());
4242 result.append("\n");
4243
Andy McFadden41d67d72014-04-25 16:58:34 -07004244 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004245 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004246 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004247
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004248 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4249 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004250 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4251 getHwComposer().isConnected(displayId)) {
4252 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004253 result.appendFormat("Display %d: "
4254 "app phase %" PRId64 " ns, "
4255 "sf phase %" PRId64 " ns, "
4256 "early app phase %" PRId64 " ns, "
4257 "early sf phase %" PRId64 " ns, "
4258 "early app gl phase %" PRId64 " ns, "
4259 "early sf gl phase %" PRId64 " ns, "
4260 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4261 displayId,
4262 vsyncPhaseOffsetNs,
4263 sfVsyncPhaseOffsetNs,
4264 appEarlyOffset,
4265 sfEarlyOffset,
4266 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004267 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004268 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004269 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004270 result.append("\n");
4271
Dan Stozab90cf072015-03-05 11:05:59 -08004272 // Dump static screen stats
4273 result.append("\n");
4274 dumpStaticScreenStats(result);
4275 result.append("\n");
4276
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004277 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4278
Dan Stozae77c7662016-05-13 11:37:28 -07004279 dumpBufferingStats(result);
4280
Andy McFadden4803b742012-09-24 19:07:20 -07004281 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004282 * Dump the visible layer list
4283 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004284 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004285 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004286 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4287 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004288 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004289
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004290 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004291 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004292 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004293 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004294
4295 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004296 * Dump Display state
4297 */
4298
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004299 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004300 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004301 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004302 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004303 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004304 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004305 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004306
4307 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004308 * Dump SurfaceFlinger global state
4309 */
4310
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004311 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004312 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004313 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004314
Mathias Agopian888c8222012-08-04 21:10:38 -07004315 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004316 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004317
David Sodmanbc815282017-11-05 18:57:52 -08004318 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004319
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004320 if (display) {
4321 display->undefinedRegion.dump(result, "undefinedRegion");
4322 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4323 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004324 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004325 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004326 " gpu_to_cpu_unsupported : %d\n",
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004327 mTransactionFlags, !mGpuToCpuSupported);
4328
4329 if (display) {
4330 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4331 result.appendFormat(" refresh-rate : %f fps\n"
4332 " x-dpi : %f\n"
4333 " y-dpi : %f\n",
4334 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4335 activeConfig->getDpiY());
4336 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004337
Mathias Agopian74d211a2013-04-22 16:55:35 +02004338 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004339 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004340
4341 /*
4342 * VSYNC state
4343 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004344 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004345 result.append("\n");
4346
4347 /*
4348 * HWC layer minidump
4349 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004350 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004351 const int32_t displayId = display->getId();
4352 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004353 continue;
4354 }
4355
Dominik Laskowski7e045462018-05-30 13:02:02 -07004356 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004357 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004358 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004359 result.append("\n");
4360 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004361
4362 /*
4363 * Dump HWComposer state
4364 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004365 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004366 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004367 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004368 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004369 result.appendFormat(" h/w composer %s\n",
4370 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004371 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004372
4373 /*
4374 * Dump gralloc state
4375 */
4376 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4377 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004378
4379 /*
4380 * Dump VrFlinger state if in use.
4381 */
4382 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4383 result.append("VrFlinger state:\n");
4384 result.append(mVrFlinger->Dump().c_str());
4385 result.append("\n");
4386 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004387}
4388
Dominik Laskowski7e045462018-05-30 13:02:02 -07004389const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004390 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004391 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004392 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004393 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004394 }
4395 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004396
4397 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4398 static const Vector<sp<Layer>> empty;
4399 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004400}
4401
Keun young Park63f165f2012-08-31 10:53:36 -07004402bool SurfaceFlinger::startDdmConnection()
4403{
4404 void* libddmconnection_dso =
4405 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4406 if (!libddmconnection_dso) {
4407 return false;
4408 }
4409 void (*DdmConnection_start)(const char* name);
4410 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004411 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004412 if (!DdmConnection_start) {
4413 dlclose(libddmconnection_dso);
4414 return false;
4415 }
4416 (*DdmConnection_start)(getServiceName());
4417 return true;
4418}
4419
Chia-I Wu28f320b2018-05-03 11:02:56 -07004420void SurfaceFlinger::updateColorMatrixLocked() {
4421 mat4 colorMatrix;
4422 if (mGlobalSaturationFactor != 1.0f) {
4423 // Rec.709 luma coefficients
4424 float3 luminance{0.213f, 0.715f, 0.072f};
4425 luminance *= 1.0f - mGlobalSaturationFactor;
4426 mat4 saturationMatrix = mat4(
4427 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4428 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4429 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4430 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4431 );
4432 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4433 } else {
4434 colorMatrix = mClientColorMatrix * mDaltonizer();
4435 }
4436
4437 if (mCurrentState.colorMatrix != colorMatrix) {
4438 mCurrentState.colorMatrix = colorMatrix;
4439 mCurrentState.colorMatrixChanged = true;
4440 setTransactionFlags(eTransactionNeeded);
4441 }
4442}
4443
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004444status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004445#pragma clang diagnostic push
4446#pragma clang diagnostic error "-Wswitch-enum"
4447 switch (static_cast<ISurfaceComposerTag>(code)) {
4448 // These methods should at minimum make sure that the client requested
4449 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004450 case BOOT_FINISHED:
4451 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004452 case CREATE_CONNECTION:
4453 case CREATE_DISPLAY:
4454 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004455 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004456 case GET_ACTIVE_COLOR_MODE:
4457 case GET_ANIMATION_FRAME_STATS:
4458 case GET_HDR_CAPABILITIES:
4459 case SET_ACTIVE_CONFIG:
4460 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004461 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004462 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004463 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4464 IPCThreadState* ipc = IPCThreadState::self();
4465 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4466 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004467 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004468 }
Robert Carr1db73f62016-12-21 12:58:51 -08004469 return OK;
4470 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004471 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004472 IPCThreadState* ipc = IPCThreadState::self();
4473 const int pid = ipc->getCallingPid();
4474 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004475 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4476 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004477 return PERMISSION_DENIED;
4478 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004479 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004480 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004481 // Used by apps to hook Choreographer to SurfaceFlinger.
4482 case CREATE_DISPLAY_EVENT_CONNECTION:
4483 // The following calls are currently used by clients that do not
4484 // request necessary permissions. However, they do not expose any secret
4485 // information, so it is OK to pass them.
4486 case AUTHENTICATE_SURFACE:
4487 case GET_ACTIVE_CONFIG:
4488 case GET_BUILT_IN_DISPLAY:
4489 case GET_DISPLAY_COLOR_MODES:
4490 case GET_DISPLAY_CONFIGS:
4491 case GET_DISPLAY_STATS:
4492 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4493 // Calling setTransactionState is safe, because you need to have been
4494 // granted a reference to Client* and Handle* to do anything with it.
4495 case SET_TRANSACTION_STATE:
4496 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4497 case CREATE_SCOPED_CONNECTION: {
4498 return OK;
4499 }
4500 case CAPTURE_LAYERS:
4501 case CAPTURE_SCREEN: {
4502 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004503 IPCThreadState* ipc = IPCThreadState::self();
4504 const int pid = ipc->getCallingPid();
4505 const int uid = ipc->getCallingUid();
4506 if ((uid != AID_GRAPHICS) &&
4507 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4508 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4509 return PERMISSION_DENIED;
4510 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004511 return OK;
4512 }
4513 // The following codes are deprecated and should never be allowed to access SF.
4514 case CONNECT_DISPLAY_UNUSED:
4515 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4516 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4517 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004518 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004519 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004520
4521 // These codes are used for the IBinder protocol to either interrogate the recipient
4522 // side of the transaction for its canonical interface descriptor or to dump its state.
4523 // We let them pass by default.
4524 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4525 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4526 code == IBinder::SYSPROPS_TRANSACTION) {
4527 return OK;
4528 }
4529 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4530 // in onTransact verifies that the user is root, and has access to use SF.
4531 if (code >= 1000 && code <= 1029) {
4532 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4533 return OK;
4534 }
4535 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4536 return PERMISSION_DENIED;
4537#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004538}
4539
Ana Krulec13be8ad2018-08-21 02:43:56 +00004540status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4541 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004542 status_t credentialCheck = CheckTransactCodeCredentials(code);
4543 if (credentialCheck != OK) {
4544 return credentialCheck;
4545 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004546
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004547 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4548 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004549 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004550 IPCThreadState* ipc = IPCThreadState::self();
4551 const int uid = ipc->getCallingUid();
4552 if (CC_UNLIKELY(uid != AID_SYSTEM
4553 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004554 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004555 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004556 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004557 return PERMISSION_DENIED;
4558 }
4559 int n;
4560 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004561 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004562 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004563 return NO_ERROR;
4564 case 1002: // SHOW_UPDATES
4565 n = data.readInt32();
4566 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004567 invalidateHwcGeometry();
4568 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004569 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004570 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004571 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004572 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004573 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004574 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004575 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004576 setTransactionFlags(
4577 eTransactionNeeded|
4578 eDisplayTransactionNeeded|
4579 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004580 return NO_ERROR;
4581 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004582 case 1006:{ // send empty update
4583 signalRefresh();
4584 return NO_ERROR;
4585 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004586 case 1008: // toggle use of hw composer
4587 n = data.readInt32();
4588 mDebugDisableHWC = n ? 1 : 0;
4589 invalidateHwcGeometry();
4590 repaintEverything();
4591 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004592 case 1009: // toggle use of transform hint
4593 n = data.readInt32();
4594 mDebugDisableTransformHint = n ? 1 : 0;
4595 invalidateHwcGeometry();
4596 repaintEverything();
4597 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004598 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004599 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004600 reply->writeInt32(0);
4601 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004602 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004603 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004604 return NO_ERROR;
4605 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004606 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004607 if (!display) {
4608 return NAME_NOT_FOUND;
4609 }
4610
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004611 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004612 return NO_ERROR;
4613 }
4614 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004615 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004616 // daltonize
4617 n = data.readInt32();
4618 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004619 case 1:
4620 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4621 break;
4622 case 2:
4623 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4624 break;
4625 case 3:
4626 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4627 break;
4628 default:
4629 mDaltonizer.setType(ColorBlindnessType::None);
4630 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004631 }
4632 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004633 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004634 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004635 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004636 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004637
4638 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004639 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004640 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004641 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004642 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004643 // apply a color matrix
4644 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004645 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004646 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004647 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004648 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004649 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004650 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004651 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004652 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004653 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004654 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004655
4656 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4657 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004658 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004659 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4660 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4661 }
4662
Chia-I Wu28f320b2018-05-03 11:02:56 -07004663 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004664 return NO_ERROR;
4665 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004666 // This is an experimental interface
4667 // Needs to be shifted to proper binder interface when we productize
4668 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004669 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07004670 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004671 return NO_ERROR;
4672 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004673 case 1017: {
4674 n = data.readInt32();
4675 mForceFullDamage = static_cast<bool>(n);
4676 return NO_ERROR;
4677 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004678 case 1018: { // Modify Choreographer's phase offset
4679 n = data.readInt32();
4680 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4681 return NO_ERROR;
4682 }
4683 case 1019: { // Modify SurfaceFlinger's phase offset
4684 n = data.readInt32();
4685 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4686 return NO_ERROR;
4687 }
Irvel468051e2016-06-13 16:44:44 -07004688 case 1020: { // Layer updates interceptor
4689 n = data.readInt32();
4690 if (n) {
4691 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004692 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004693 }
4694 else{
4695 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004696 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004697 }
4698 return NO_ERROR;
4699 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004700 case 1021: { // Disable HWC virtual displays
4701 n = data.readInt32();
4702 mUseHwcVirtualDisplays = !n;
4703 return NO_ERROR;
4704 }
Romain Guy0147a172017-06-01 13:53:56 -07004705 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004706 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004707 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004708
Chia-I Wu28f320b2018-05-03 11:02:56 -07004709 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004710 return NO_ERROR;
4711 }
Romain Guy54f154a2017-10-24 21:40:32 +01004712 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004713 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004714 invalidateHwcGeometry();
4715 repaintEverything();
4716 return NO_ERROR;
4717 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004718 // TODO(b/111505327): Find out whether the usage of 1024 can switch to 1030,
4719 // deprecate 1024 if they can.
4720 case 1024: { // Does device have wide color gamut display?
Romain Guy54f154a2017-10-24 21:40:32 +01004721 reply->writeBool(hasWideColorDisplay);
4722 return NO_ERROR;
4723 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004724 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004725 n = data.readInt32();
4726 if (n) {
4727 ALOGV("LayerTracing enabled");
4728 mTracing.enable();
4729 doTracing("tracing.enable");
4730 reply->writeInt32(NO_ERROR);
4731 } else {
4732 ALOGV("LayerTracing disabled");
4733 status_t err = mTracing.disable();
4734 reply->writeInt32(err);
4735 }
4736 return NO_ERROR;
4737 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004738 case 1026: { // Get layer tracing status
4739 reply->writeBool(mTracing.isEnabled());
4740 return NO_ERROR;
4741 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004742 // Is a DisplayColorSetting supported?
4743 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004744 const auto display = getDefaultDisplayDevice();
4745 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004746 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004747 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004748
4749 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4750 switch (setting) {
4751 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07004752 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004753 break;
4754 case DisplayColorSetting::UNMANAGED:
4755 reply->writeBool(true);
4756 break;
4757 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004758 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004759 break;
4760 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004761 reply->writeBool(
4762 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004763 break;
4764 }
4765 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004766 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004767 // Is VrFlinger active?
4768 case 1028: {
4769 Mutex::Autolock _l(mStateLock);
4770 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4771 return NO_ERROR;
4772 }
David Sodman6d46c1e2018-07-13 12:59:48 -07004773 case 1029: {
4774 // Code 1029 is an experimental feature that allows applications to
4775 // simulate a high frequency panel by setting a multiplier and divisor
4776 // on the VSYNC-sf clock. If either the multiplier or divisor are
4777 // 0, then the code will set both to 1 to return the VSYNC-sf clock
4778 // to it's normal frequency.
4779 int multiplier = data.readInt32();
4780 int divisor = data.readInt32();
4781
4782 if ((multiplier == 0) || (divisor == 0)) {
4783 multiplier = 1;
4784 divisor = 1;
4785 }
4786
4787 if ((multiplier == 1) && (divisor == 1)) {
4788 enableHardwareVsync();
4789 } else {
4790 disableHardwareVsync(true);
4791 }
4792 getBE().mHwc->getActiveConfig(DisplayDevice::DISPLAY_PRIMARY)
4793 ->scalePanelFrequency(multiplier, divisor);
4794 mPrimaryDispSync->scalePeriod(multiplier, divisor);
4795
4796 ATRACE_INT("PeriodMultiplier", multiplier);
4797 ATRACE_INT("PeriodDivisor", divisor);
4798 return NO_ERROR;
4799 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004800 // Is device color managed?
4801 case 1030: {
4802 reply->writeBool(useColorManagement);
4803 return NO_ERROR;
4804 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004805 }
4806 }
4807 return err;
4808}
4809
Steven Thomas6d8110b2017-08-31 18:24:21 -07004810void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004811 android_atomic_or(1, &mRepaintEverything);
4812 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004813}
4814
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004815// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4816class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004817public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004818 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4819 ~WindowDisconnector() {
4820 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004821 }
4822
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004823private:
4824 ANativeWindow* mWindow;
4825 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004826};
4827
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004828status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4829 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4830 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4831 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004832 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004833 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004834
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004835 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004836
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004837 const auto display = getDisplayDeviceLocked(displayToken);
4838 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004839
Yiwei Zhang06a58e22018-08-20 16:42:23 -07004840 const Rect& dispScissor = display->getScissor();
4841 if (!dispScissor.isEmpty()) {
4842 sourceCrop.set(dispScissor);
4843 // adb shell screencap will default reqWidth and reqHeight to zeros.
4844 if (reqWidth == 0 || reqHeight == 0) {
4845 reqWidth = uint32_t(dispScissor.width());
4846 reqHeight = uint32_t(dispScissor.height());
4847 }
4848 }
4849
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004850 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004851
4852 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004853 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004854 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004855}
4856
4857status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004858 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004859 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004860 ATRACE_CALL();
4861
4862 class LayerRenderArea : public RenderArea {
4863 public:
Robert Carr578038f2018-03-09 12:25:24 -08004864 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4865 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004866 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004867 mLayer(layer),
4868 mCrop(crop),
4869 mFlinger(flinger),
4870 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07004871 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004872 Rect getBounds() const override {
4873 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07004874 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07004875 }
Marissa Wall61c58622018-07-18 10:12:20 -07004876 int getHeight() const override {
4877 return mLayer->getActiveHeight(mLayer->getDrawingState());
4878 }
4879 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07004880 bool isSecure() const override { return false; }
4881 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004882 Rect getSourceCrop() const override {
4883 if (mCrop.isEmpty()) {
4884 return getBounds();
4885 } else {
4886 return mCrop;
4887 }
4888 }
Robert Carr578038f2018-03-09 12:25:24 -08004889 class ReparentForDrawing {
4890 public:
4891 const sp<Layer>& oldParent;
4892 const sp<Layer>& newParent;
4893
4894 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4895 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004896 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004897 }
Robert Carr15eae092018-03-23 13:43:53 -07004898 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004899 };
4900
4901 void render(std::function<void()> drawLayers) override {
4902 if (!mChildrenOnly) {
4903 mTransform = mLayer->getTransform().inverse();
4904 drawLayers();
4905 } else {
4906 Rect bounds = getBounds();
4907 screenshotParentLayer =
4908 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4909 bounds.getWidth(), bounds.getHeight(), 0);
4910
4911 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4912 drawLayers();
4913 }
4914 }
chaviwa76b2712017-09-20 12:02:26 -07004915
chaviwa76b2712017-09-20 12:02:26 -07004916 private:
chaviw7206d492017-11-10 16:16:12 -08004917 const sp<Layer> mLayer;
4918 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004919
4920 // In the "childrenOnly" case we reparent the children to a screenshot
4921 // layer which has no properties set and which does not draw.
4922 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07004923 ui::Transform mTransform;
Robert Carr578038f2018-03-09 12:25:24 -08004924
4925 SurfaceFlinger* mFlinger;
4926 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004927 };
4928
4929 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4930 auto parent = layerHandle->owner.promote();
4931
chaviw7206d492017-11-10 16:16:12 -08004932 if (parent == nullptr || parent->isPendingRemoval()) {
4933 ALOGE("captureLayers called with a removed parent");
4934 return NAME_NOT_FOUND;
4935 }
4936
Robert Carr578038f2018-03-09 12:25:24 -08004937 const int uid = IPCThreadState::self()->getCallingUid();
4938 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4939 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4940 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4941 return PERMISSION_DENIED;
4942 }
4943
chaviw7206d492017-11-10 16:16:12 -08004944 Rect crop(sourceCrop);
4945 if (sourceCrop.width() <= 0) {
4946 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07004947 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08004948 }
4949
4950 if (sourceCrop.height() <= 0) {
4951 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07004952 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08004953 }
4954
4955 int32_t reqWidth = crop.width() * frameScale;
4956 int32_t reqHeight = crop.height() * frameScale;
4957
Robert Carr578038f2018-03-09 12:25:24 -08004958 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004959
Robert Carr578038f2018-03-09 12:25:24 -08004960 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004961 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4962 if (!layer->isVisible()) {
4963 return;
Robert Carr578038f2018-03-09 12:25:24 -08004964 } else if (childrenOnly && layer == parent.get()) {
4965 return;
chaviwa76b2712017-09-20 12:02:26 -07004966 }
4967 visitor(layer);
4968 });
4969 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004970 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004971}
4972
4973status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4974 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004975 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004976 bool useIdentityTransform) {
4977 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004978
Iris Chang7501ed62018-04-30 14:45:42 +08004979 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004980
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004981 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4982 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4983 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4984 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004985
4986 // This mutex protects syncFd and captureResult for communication of the return values from the
4987 // main thread back to this Binder thread
4988 std::mutex captureMutex;
4989 std::condition_variable captureCondition;
4990 std::unique_lock<std::mutex> captureLock(captureMutex);
4991 int syncFd = -1;
4992 std::optional<status_t> captureResult;
4993
Robert Carr03480e22018-01-04 16:02:06 -08004994 const int uid = IPCThreadState::self()->getCallingUid();
4995 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4996
Dominik Laskowski8c001672018-05-30 16:52:06 -07004997 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004998 // If there is a refresh pending, bug out early and tell the binder thread to try again
4999 // after the refresh.
5000 if (mRefreshPending) {
5001 ATRACE_NAME("Skipping screenshot for now");
5002 std::unique_lock<std::mutex> captureLock(captureMutex);
5003 captureResult = std::make_optional<status_t>(EAGAIN);
5004 captureCondition.notify_one();
5005 return;
5006 }
5007
5008 status_t result = NO_ERROR;
5009 int fd = -1;
5010 {
5011 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005012 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005013 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5014 useIdentityTransform, forSystem, &fd);
5015 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005016 }
5017
5018 {
5019 std::unique_lock<std::mutex> captureLock(captureMutex);
5020 syncFd = fd;
5021 captureResult = std::make_optional<status_t>(result);
5022 captureCondition.notify_one();
5023 }
5024 });
5025
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005026 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005027 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005028 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005029 while (*captureResult == EAGAIN) {
5030 captureResult.reset();
5031 result = postMessageAsync(message);
5032 if (result != NO_ERROR) {
5033 return result;
5034 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005035 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005036 }
5037 result = *captureResult;
5038 }
5039
5040 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005041 sync_wait(syncFd, -1);
5042 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005043 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005044
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005045 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005046}
5047
chaviwa76b2712017-09-20 12:02:26 -07005048void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5049 TraverseLayersFunction traverseLayers, bool yswap,
5050 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005051 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005052
Lloyd Pique144e1162017-12-20 16:44:52 -08005053 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005054
5055 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005056 const auto raWidth = renderArea.getWidth();
5057 const auto raHeight = renderArea.getHeight();
5058
5059 const auto reqWidth = renderArea.getReqWidth();
5060 const auto reqHeight = renderArea.getReqHeight();
5061 Rect sourceCrop = renderArea.getSourceCrop();
5062
Iris Chang7501ed62018-04-30 14:45:42 +08005063 bool filtering = false;
5064 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5065 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5066 static_cast<int32_t>(reqHeight) != raWidth;
5067 } else {
5068 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5069 static_cast<int32_t>(reqHeight) != raHeight;
5070 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005071
Dan Stozac1879002014-05-22 15:59:05 -07005072 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005073 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005074 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005075 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005076 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
Peiyong Linefefaac2018-08-17 12:27:51 -07005077 ui::Transform tr;
Iris Chang7501ed62018-04-30 14:45:42 +08005078 uint32_t flags = 0x00;
5079 switch (mPrimaryDisplayOrientation) {
5080 case DisplayState::eOrientation90:
Peiyong Linefefaac2018-08-17 12:27:51 -07005081 flags = ui::Transform::ROT_90;
Iris Chang7501ed62018-04-30 14:45:42 +08005082 break;
5083 case DisplayState::eOrientation180:
Peiyong Linefefaac2018-08-17 12:27:51 -07005084 flags = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005085 break;
5086 case DisplayState::eOrientation270:
Peiyong Linefefaac2018-08-17 12:27:51 -07005087 flags = ui::Transform::ROT_270;
Iris Chang7501ed62018-04-30 14:45:42 +08005088 break;
5089 }
5090 tr.set(flags, raWidth, raHeight);
5091 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005092 }
5093
5094 // ensure that sourceCrop is inside screen
5095 if (sourceCrop.left < 0) {
5096 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5097 }
chaviwa76b2712017-09-20 12:02:26 -07005098 if (sourceCrop.right > raWidth) {
5099 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005100 }
5101 if (sourceCrop.top < 0) {
5102 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5103 }
chaviwa76b2712017-09-20 12:02:26 -07005104 if (sourceCrop.bottom > raHeight) {
5105 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005106 }
5107
Chia-I Wu36574d92018-05-16 10:54:36 -07005108 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5109 engine.setOutputDataSpace(Dataspace::SRGB);
5110 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005111
Mathias Agopian180f10d2013-04-10 22:55:41 -07005112 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005113 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005114
Peiyong Linefefaac2018-08-17 12:27:51 -07005115 ui::Transform::orientation_flags rotation = renderArea.getRotationFlags();
Iris Chang7501ed62018-04-30 14:45:42 +08005116 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5117 // convert hw orientation into flag presentation
5118 // here inverse transform needed
5119 uint8_t hw_rot_90 = 0x00;
5120 uint8_t hw_flip_hv = 0x00;
5121 switch (mPrimaryDisplayOrientation) {
5122 case DisplayState::eOrientation90:
Peiyong Linefefaac2018-08-17 12:27:51 -07005123 hw_rot_90 = ui::Transform::ROT_90;
5124 hw_flip_hv = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005125 break;
5126 case DisplayState::eOrientation180:
Peiyong Linefefaac2018-08-17 12:27:51 -07005127 hw_flip_hv = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005128 break;
5129 case DisplayState::eOrientation270:
Peiyong Linefefaac2018-08-17 12:27:51 -07005130 hw_rot_90 = ui::Transform::ROT_90;
Iris Chang7501ed62018-04-30 14:45:42 +08005131 break;
5132 }
5133
5134 // transform flags operation
5135 // 1) flip H V if both have ROT_90 flag
5136 // 2) XOR these flags
Peiyong Linefefaac2018-08-17 12:27:51 -07005137 uint8_t rotation_rot_90 = rotation & ui::Transform::ROT_90;
5138 uint8_t rotation_flip_hv = rotation & ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005139 if (rotation_rot_90 & hw_rot_90) {
Peiyong Linefefaac2018-08-17 12:27:51 -07005140 rotation_flip_hv = (~rotation_flip_hv) & ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005141 }
Peiyong Linefefaac2018-08-17 12:27:51 -07005142 rotation = static_cast<ui::Transform::orientation_flags>
Iris Chang7501ed62018-04-30 14:45:42 +08005143 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5144 }
5145
Mathias Agopian180f10d2013-04-10 22:55:41 -07005146 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005147 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005148 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005149 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005150
chaviw50da5042018-04-09 13:49:37 -07005151 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005152 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005153 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005154
chaviwa76b2712017-09-20 12:02:26 -07005155 traverseLayers([&](Layer* layer) {
5156 if (filtering) layer->setFiltering(true);
David Sodmanca10ed22018-04-16 14:10:25 -07005157 layer->drawNow(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005158 if (filtering) layer->setFiltering(false);
5159 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005160}
5161
chaviwa76b2712017-09-20 12:02:26 -07005162status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5163 TraverseLayersFunction traverseLayers,
5164 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005165 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005166 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005167 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005168 ATRACE_CALL();
5169
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005170 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005171
5172 traverseLayers([&](Layer* layer) {
5173 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5174 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005175
Robert Carr03480e22018-01-04 16:02:06 -08005176 // We allow the system server to take screenshots of secure layers for
5177 // use in situations like the Screen-rotation animation and place
5178 // the impetus on WindowManager to not persist them.
5179 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005180 ALOGW("FB is protected: PERMISSION_DENIED");
5181 return PERMISSION_DENIED;
5182 }
5183
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005184 // this binds the given EGLImage as a framebuffer for the
5185 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005186 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005187 if (bufferBond.getStatus() != NO_ERROR) {
5188 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005189 return INVALID_OPERATION;
5190 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005191
Dan Stozaabcda352017-06-01 14:37:39 -07005192 // this will in fact render into our dequeued buffer
5193 // via an FBO, which means we didn't have to create
5194 // an EGLSurface and therefore we're not
5195 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005196 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005197
Dan Stozaabcda352017-06-01 14:37:39 -07005198 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005199 getRenderEngine().finish();
5200 *outSyncFd = -1;
5201
chaviwa76b2712017-09-20 12:02:26 -07005202 const auto reqWidth = renderArea.getReqWidth();
5203 const auto reqHeight = renderArea.getReqHeight();
5204
Dan Stozaabcda352017-06-01 14:37:39 -07005205 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5206 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005207 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005208 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005209 } else {
5210 base::unique_fd syncFd = getRenderEngine().flush();
5211 if (syncFd < 0) {
5212 getRenderEngine().finish();
5213 }
5214 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005215 }
5216
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005217 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005218}
5219
Mathias Agopiand5556842013-09-19 17:08:37 -07005220void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005221 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005222 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005223 for (size_t y = 0; y < h; y++) {
5224 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5225 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005226 if (p[x] != 0xFF000000) return;
5227 }
5228 }
chaviwa76b2712017-09-20 12:02:26 -07005229 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005230
Robert Carr2047fae2016-11-28 14:09:09 -08005231 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005232 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005233 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005234 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5235 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5236 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5237 static_cast<float>(state.color.a));
5238 i++;
5239 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005240 }
5241}
5242
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005243// ---------------------------------------------------------------------------
5244
Dan Stoza412903f2017-04-27 13:42:17 -07005245void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5246 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005247}
5248
Dan Stoza412903f2017-04-27 13:42:17 -07005249void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5250 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005251}
5252
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005253void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5254 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005255 const LayerVector::Visitor& visitor) {
5256 // We loop through the first level of layers without traversing,
5257 // as we need to interpret min/max layer Z in the top level Z space.
5258 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005259 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005260 continue;
5261 }
5262 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005263 // relative layers are traversed in Layer::traverseInZOrder
5264 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005265 continue;
5266 }
5267 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005268 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005269 return;
5270 }
chaviwa76b2712017-09-20 12:02:26 -07005271 if (!layer->isVisible()) {
5272 return;
5273 }
5274 visitor(layer);
5275 });
5276 }
5277}
5278
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005279}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005280
Lloyd Pique074e8122018-07-26 12:57:23 -07005281
Mathias Agopian3f844832013-08-07 21:24:32 -07005282#if defined(__gl_h_)
5283#error "don't include gl/gl.h in this file"
5284#endif
5285
5286#if defined(__gl2_h_)
5287#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005288#endif