blob: 842e5dee583dfe5e54343f0c38cfaa1a460d354c [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Chia-I Wud49d6692018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070050
51#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070066#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070067#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020070#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080072#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080073#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Steven Thomasb02664d2017-07-26 18:48:28 -070079#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070080#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include "Effects/Daltonizer.h"
Mathias Agopian875d8e12013-06-07 15:35:48 -070085#include "RenderEngine/RenderEngine.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070086#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070087#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070088#include "Scheduler/EventControlThread.h"
89#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070090#include "Scheduler/InjectVSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070091
Mathias Agopianff2ed702013-09-01 21:36:12 -070092#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070093
Jiyong Park4b20c2e2017-01-14 19:45:11 +090094#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080095#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -070096#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080097#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090098#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090099
chaviw1d044282017-09-27 12:19:28 -0700100#include <layerproto/LayerProtoParser.h>
101
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800102#define DISPLAY_COUNT 1
103
Mathias Agopianfee2b462013-07-03 12:34:01 -0700104/*
105 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
106 * black pixels.
107 */
108#define DEBUG_SCREENSHOTS false
109
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800110namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700111
Jaesoo Lee43518572017-01-23 19:03:16 +0900112using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900113using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700114using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700115using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700116using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700117using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900118
Steven Thomasb02664d2017-07-26 18:48:28 -0700119namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700120
121#pragma clang diagnostic push
122#pragma clang diagnostic error "-Wswitch-enum"
123
124bool isWideColorMode(const ColorMode colorMode) {
125 switch (colorMode) {
126 case ColorMode::DISPLAY_P3:
127 case ColorMode::ADOBE_RGB:
128 case ColorMode::DCI_P3:
129 case ColorMode::BT2020:
130 case ColorMode::BT2100_PQ:
131 case ColorMode::BT2100_HLG:
132 return true;
133 case ColorMode::NATIVE:
134 case ColorMode::STANDARD_BT601_625:
135 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
136 case ColorMode::STANDARD_BT601_525:
137 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
138 case ColorMode::STANDARD_BT709:
139 case ColorMode::SRGB:
140 return false;
141 }
142 return false;
143}
144
145#pragma clang diagnostic pop
146
Steven Thomasb02664d2017-07-26 18:48:28 -0700147class ConditionalLock {
148public:
149 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
150 if (lock) {
151 mMutex.lock();
152 }
153 }
154 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
155private:
156 Mutex& mMutex;
157 bool mLocked;
158};
Peiyong Linfca547f2018-07-09 13:03:33 -0700159
Steven Thomasb02664d2017-07-26 18:48:28 -0700160} // namespace anonymous
161
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800162// ---------------------------------------------------------------------------
163
Mathias Agopian99b49842011-06-27 16:05:52 -0700164const String16 sHardwareTest("android.permission.HARDWARE_TEST");
165const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
166const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
167const String16 sDump("android.permission.DUMP");
168
169// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800170int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
171int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700172int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700173bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800174uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800175bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800176bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800177int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800178// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600179bool SurfaceFlinger::hasWideColorDisplay;
Peiyong Lin13effd12018-07-24 17:01:47 -0700180bool SurfaceFlinger::useColorManagement;
Mathias Agopian99b49842011-06-27 16:05:52 -0700181
Kalle Raitaa099a242017-01-11 11:17:29 -0800182
183std::string getHwcServiceName() {
184 char value[PROPERTY_VALUE_MAX] = {};
185 property_get("debug.sf.hwc_service_name", value, "default");
186 ALOGI("Using HWComposer service: '%s'", value);
187 return std::string(value);
188}
189
190bool useTrebleTestingOverride() {
191 char value[PROPERTY_VALUE_MAX] = {};
192 property_get("debug.sf.treble_testing_override", value, "false");
193 ALOGI("Treble testing override: '%s'", value);
194 return std::string(value) == "true";
195}
196
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800197std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
198 switch(displayColorSetting) {
199 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700200 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800201 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700202 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800203 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700204 return std::string("Enhanced");
205 default:
206 return std::string("Unknown ") +
207 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800208 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800209}
210
Lloyd Pique99d3da52018-01-22 17:48:03 -0800211NativeWindowSurface::~NativeWindowSurface() = default;
212
213namespace impl {
214
215class NativeWindowSurface final : public android::NativeWindowSurface {
216public:
217 static std::unique_ptr<android::NativeWindowSurface> create(
218 const sp<IGraphicBufferProducer>& producer) {
219 return std::make_unique<NativeWindowSurface>(producer);
220 }
221
222 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
223 : surface(new Surface(producer, false)) {}
224
225 ~NativeWindowSurface() override = default;
226
227private:
228 sp<ANativeWindow> getNativeWindow() const override { return surface; }
229
230 void preallocateBuffers() override { surface->allocateBuffers(); }
231
232 sp<Surface> surface;
233};
234
235} // namespace impl
236
David Sodmanbc815282017-11-05 18:57:52 -0800237SurfaceFlingerBE::SurfaceFlingerBE()
238 : mHwcServiceName(getHwcServiceName()),
239 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800240 mFrameBuckets(),
241 mTotalTime(0),
242 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800243 mComposerSequenceId(0) {
244}
245
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800246SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800247 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800248 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700249 mTransactionPending(false),
250 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700251 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700252 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700253 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800254 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700255 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800256 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800257 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800258 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800259 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800260 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700261 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700262 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700263 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700264 mDebugInTransaction(0),
265 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700266 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700267 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700268 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800269 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800270 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800271 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700272 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800273 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800274 mCreateBufferQueue(&BufferQueue::createBufferQueue),
275 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800276
277SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800278 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800279
280 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
281 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
282
283 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
284 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
285
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800286 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
287 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700289 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
290 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
291
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700292 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
293 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
294
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800295 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
296 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
297
Steven Thomas050b2c82017-03-06 11:45:16 -0800298 // Vr flinger is only enabled on Daydream ready devices.
299 useVrFlinger = getBool< ISurfaceFlingerConfigs,
300 &ISurfaceFlingerConfigs::useVrFlinger>(false);
301
Fabien Sanglard1971b632017-03-10 14:50:03 -0800302 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
303 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
304
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600305 hasWideColorDisplay =
306 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700307 useColorManagement =
308 getBool<V1_2::ISurfaceFlingerConfigs, &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600309
Iris Chang7501ed62018-04-30 14:45:42 +0800310 V1_1::DisplayOrientation primaryDisplayOrientation =
311 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
312 V1_1::DisplayOrientation::ORIENTATION_0);
313
314 switch (primaryDisplayOrientation) {
315 case V1_1::DisplayOrientation::ORIENTATION_90:
316 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
317 break;
318 case V1_1::DisplayOrientation::ORIENTATION_180:
319 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
320 break;
321 case V1_1::DisplayOrientation::ORIENTATION_270:
322 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
323 break;
324 default:
325 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
326 break;
327 }
328 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
329
Lloyd Pique41be5d22018-06-21 13:11:48 -0700330 // Note: We create a local temporary with the real DispSync implementation
331 // type temporarily so we can initialize it with the configured values,
332 // before storing it for more generic use using the interface type.
333 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
334 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
335 SurfaceFlinger::dispSyncPresentTimeOffset);
336 mPrimaryDispSync = std::move(primaryDispSync);
Saurabh Shahf4174532017-07-13 10:45:07 -0700337
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800338 // debugging stuff...
339 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700340
Mathias Agopianb4b17302013-03-20 18:36:41 -0700341 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700342 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700343
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800344 property_get("debug.sf.showupdates", value, "0");
345 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700346
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700347 property_get("debug.sf.ddms", value, "0");
348 mDebugDDMS = atoi(value);
349 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700350 if (!startDdmConnection()) {
351 // start failed, and DDMS debugging not enabled
352 mDebugDDMS = 0;
353 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700354 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700355 ALOGI_IF(mDebugRegion, "showupdates enabled");
356 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700357
358 property_get("debug.sf.disable_backpressure", value, "0");
359 mPropagateBackpressure = !atoi(value);
360 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700361
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800362 property_get("debug.sf.enable_hwc_vds", value, "0");
363 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800364 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800365
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800366 property_get("ro.sf.disable_triple_buffer", value, "1");
367 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800368 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700369
Yiwei Zhang243b3782018-05-15 17:40:04 -0700370 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700371 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
372 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
373
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200374 property_get("debug.sf.early_phase_offset_ns", value, "-1");
375 const int earlySfOffsetNs = atoi(value);
376
377 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
378 const int earlyGlSfOffsetNs = atoi(value);
379
380 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
381 const int earlyAppOffsetNs = atoi(value);
382
383 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
384 const int earlyGlAppOffsetNs = atoi(value);
385
386 const VSyncModulator::Offsets earlyOffsets =
387 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
388 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
389 const VSyncModulator::Offsets earlyGlOffsets =
390 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
391 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
392 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
393 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700394
Romain Guy11d63f42017-07-20 12:47:14 -0700395 // We should be reading 'persist.sys.sf.color_saturation' here
396 // but since /data may be encrypted, we need to wait until after vold
397 // comes online to attempt to read the property. The property is
398 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800399
400 if (useTrebleTestingOverride()) {
401 // Without the override SurfaceFlinger cannot connect to HIDL
402 // services that are not listed in the manifests. Considered
403 // deriving the setting from the set service name, but it
404 // would be brittle if the name that's not 'default' is used
405 // for production purposes later on.
406 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
407 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800408}
409
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800410void SurfaceFlinger::onFirstRef()
411{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800412 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800413}
414
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800415SurfaceFlinger::~SurfaceFlinger()
416{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800417}
418
Dan Stozac7014012014-02-14 15:03:43 -0800419void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800420{
421 // the window manager died on us. prepare its eulogy.
422
Andy McFadden13a082e2012-08-24 10:16:42 -0700423 // restore initial conditions (default device unblank, etc)
424 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800425
426 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700427 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800428}
429
Robert Carr1db73f62016-12-21 12:58:51 -0800430static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700431 status_t err = client->initCheck();
432 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800433 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800434 }
Robert Carr1db73f62016-12-21 12:58:51 -0800435 return nullptr;
436}
437
438sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
439 return initClient(new Client(this));
440}
441
442sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
443 const sp<IGraphicBufferProducer>& gbp) {
444 if (authenticateSurfaceTexture(gbp) == false) {
445 return nullptr;
446 }
447 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
448 if (layer == nullptr) {
449 return nullptr;
450 }
451
452 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800453}
454
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700455sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
456 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700457{
458 class DisplayToken : public BBinder {
459 sp<SurfaceFlinger> flinger;
460 virtual ~DisplayToken() {
461 // no more references, this display must be terminated
462 Mutex::Autolock _l(flinger->mStateLock);
463 flinger->mCurrentState.displays.removeItem(this);
464 flinger->setTransactionFlags(eDisplayTransactionNeeded);
465 }
466 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700467 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700468 : flinger(flinger) {
469 }
470 };
471
472 sp<BBinder> token = new DisplayToken(this);
473
474 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700475 DisplayDeviceState info;
476 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700477 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700478 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700479 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800480 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700481 return token;
482}
483
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700484void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700485 Mutex::Autolock _l(mStateLock);
486
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700487 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700488 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700489 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700490 return;
491 }
492
493 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700494 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700495 ALOGE("destroyDisplay called for non-virtual display");
496 return;
497 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700498 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700499 mCurrentState.displays.removeItemsAt(idx);
500 setTransactionFlags(eDisplayTransactionNeeded);
501}
502
Mathias Agopiane57f2922012-08-09 16:29:12 -0700503sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700504 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700505 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800506 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700507 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700508 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700509}
510
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800511void SurfaceFlinger::bootFinished()
512{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700513 if (mStartPropertySetThread->join() != NO_ERROR) {
514 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800515 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800516 const nsecs_t now = systemTime();
517 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000518 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700519
520 // wait patiently for the window manager death
521 const String16 name("window");
522 sp<IBinder> window(defaultServiceManager()->getService(name));
523 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700524 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700525 }
526
Steven Thomas050b2c82017-03-06 11:45:16 -0800527 if (mVrFlinger) {
528 mVrFlinger->OnBootFinished();
529 }
530
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700531 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700532 // formerly we would just kill the process, but we now ask it to exit so it
533 // can choose where to stop the animation.
534 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700535
536 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
537 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
538 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700539
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800540 postMessageAsync(new LambdaMessage([this] {
541 readPersistentProperties();
542 mBootStage = BootStage::FINISHED;
543 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800544}
545
Dan Stoza436ccf32018-06-21 12:10:12 -0700546uint32_t SurfaceFlinger::getNewTexture() {
547 {
548 std::lock_guard lock(mTexturePoolMutex);
549 if (!mTexturePool.empty()) {
550 uint32_t name = mTexturePool.back();
551 mTexturePool.pop_back();
552 ATRACE_INT("TexturePoolSize", mTexturePool.size());
553 return name;
554 }
555
556 // The pool was too small, so increase it for the future
557 ++mTexturePoolSize;
558 }
559
560 // The pool was empty, so we need to get a new texture name directly using a
561 // blocking call to the main thread
562 uint32_t name = 0;
563 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
564 return name;
565}
566
Mathias Agopian3f844832013-08-07 21:24:32 -0700567void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700568 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700569}
570
Wei Wangf9b05ee2017-07-19 20:59:39 -0700571// Do not call property_set on main thread which will be blocked by init
572// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700573void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700574 ALOGI( "SurfaceFlinger's main thread ready to run. "
575 "Initializing graphics H/W...");
576
Thierry Strudel2924d012017-08-14 15:19:37 -0700577 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900578
Steven Thomasb02664d2017-07-26 18:48:28 -0700579 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800580
Steven Thomasb02664d2017-07-26 18:48:28 -0700581 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800582 mEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700583 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
584 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800585 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700586 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800587 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800588 "appEventThread");
589 mSfEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700590 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800591 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800592
Lloyd Pique24b0a482018-03-09 18:52:26 -0800593 mSFEventThread =
594 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700595 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800596 [this](nsecs_t timestamp) {
597 mInterceptor->saveVSyncEvent(timestamp);
598 },
599 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800600 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200601 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800602
Steven Thomasb02664d2017-07-26 18:48:28 -0700603 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700604 int32_t renderEngineFeature = 0;
605 renderEngineFeature |= (useColorManagement ? RE::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Lloyd Pique144e1162017-12-20 16:44:52 -0800606 getBE().mRenderEngine =
Peiyong Lin13effd12018-07-24 17:01:47 -0700607 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888, renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800608 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700609
610 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
611 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800612 getBE().mHwc.reset(
613 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700614 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800615 // Process any initial hotplug and resulting display changes.
616 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700617 const auto display = getDefaultDisplayDeviceLocked();
618 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
619 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
620 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800621
Lloyd Piquefcd86612017-12-14 17:15:36 -0800622 // make the default display GLContext current so that we can create textures
623 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700624 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800625
Steven Thomas050b2c82017-03-06 11:45:16 -0800626 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700627 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700628 // This callback is called from the vr flinger dispatch thread. We
629 // need to call signalTransaction(), which requires holding
630 // mStateLock when we're not on the main thread. Acquiring
631 // mStateLock from the vr flinger dispatch thread might trigger a
632 // deadlock in surface flinger (see b/66916578), so post a message
633 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700634 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700635 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
636 mVrFlingerRequestsDisplay = requestDisplay;
637 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700638 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800639 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700640 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
641 getHwComposer()
642 .getHwcDisplayId(display->getId())
643 .value_or(0),
644 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800645 if (!mVrFlinger) {
646 ALOGE("Failed to start vrflinger");
647 }
648 }
649
Lloyd Pique379adc12018-01-22 17:31:47 -0800650 mEventControlThread = std::make_unique<impl::EventControlThread>(
651 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700652
Mathias Agopian92a979a2012-08-02 18:32:23 -0700653 // initialize our drawing state
654 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700655
Andy McFadden13a082e2012-08-24 10:16:42 -0700656 // set initial conditions (e.g. unblank default device)
657 initializeDisplays();
658
David Sodmanbc815282017-11-05 18:57:52 -0800659 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700660
Wei Wangf9b05ee2017-07-19 20:59:39 -0700661 // Inform native graphics APIs whether the present timestamp is supported:
662 if (getHwComposer().hasCapability(
663 HWC2::Capability::PresentFenceIsNotReliable)) {
664 mStartPropertySetThread = new StartPropertySetThread(false);
665 } else {
666 mStartPropertySetThread = new StartPropertySetThread(true);
667 }
668
669 if (mStartPropertySetThread->Start() != NO_ERROR) {
670 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800671 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800672
Chia-I Wud49d6692018-06-27 07:17:41 +0800673 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
674 // is used to saturate legacy sRGB content. However, to make sure the same color under
675 // Display P3 will be saturated to the same color, we intentionally break the API spec
676 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
677 // such saturation matrix on Display P3 is understood fully, the API should always return
678 // identify matrix.
679 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
680 Dataspace::SRGB_LINEAR);
681
682 // we will apply this on Display P3.
683 if (mEnhancedSaturationMatrix != mat4()) {
684 ColorSpace srgb(ColorSpace::sRGB());
685 ColorSpace displayP3(ColorSpace::DisplayP3());
686 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
687 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
688 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
689 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800690
Dan Stoza9e56aa02015-11-02 13:00:03 -0800691 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700692}
693
Romain Guy11d63f42017-07-20 12:47:14 -0700694void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700695 Mutex::Autolock _l(mStateLock);
696
Romain Guy11d63f42017-07-20 12:47:14 -0700697 char value[PROPERTY_VALUE_MAX];
698
699 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800700 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700701 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800702 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100703
704 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700705 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700706}
707
Mathias Agopiana67e4182012-06-19 17:26:12 -0700708void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800709 // Start boot animation service by setting a property mailbox
710 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700711 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800712 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700713 if (mStartPropertySetThread->join() != NO_ERROR) {
714 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800715 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700716}
717
Mathias Agopian875d8e12013-06-07 15:35:48 -0700718size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800719 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700720}
721
Mathias Agopian875d8e12013-06-07 15:35:48 -0700722size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800723 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700724}
725
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800726// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800727
Jamie Gennis582270d2011-08-17 18:19:00 -0700728bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800729 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800730 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800731 return authenticateSurfaceTextureLocked(bufferProducer);
732}
733
734bool SurfaceFlinger::authenticateSurfaceTextureLocked(
735 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800736 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800737 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800738}
739
Brian Anderson6b376712017-04-04 10:51:39 -0700740status_t SurfaceFlinger::getSupportedFrameTimestamps(
741 std::vector<FrameEvent>* outSupported) const {
742 *outSupported = {
743 FrameEvent::REQUESTED_PRESENT,
744 FrameEvent::ACQUIRE,
745 FrameEvent::LATCH,
746 FrameEvent::FIRST_REFRESH_START,
747 FrameEvent::LAST_REFRESH_START,
748 FrameEvent::GPU_COMPOSITION_DONE,
749 FrameEvent::DEQUEUE_READY,
750 FrameEvent::RELEASE,
751 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700752 ConditionalLock _l(mStateLock,
753 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700754 if (!getHwComposer().hasCapability(
755 HWC2::Capability::PresentFenceIsNotReliable)) {
756 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
757 }
758 return NO_ERROR;
759}
760
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700761status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
762 Vector<DisplayInfo>* configs) {
763 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700764 return BAD_VALUE;
765 }
766
Jesse Hall692c7232012-11-08 15:41:56 -0800767 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700768 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
769 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700770 type = i;
771 break;
772 }
773 }
774
775 if (type < 0) {
776 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700777 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700778
Mathias Agopian8b736f12012-08-13 17:54:26 -0700779 // TODO: Not sure if display density should handled by SF any longer
780 class Density {
781 static int getDensityFromProperty(char const* propName) {
782 char property[PROPERTY_VALUE_MAX];
783 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800784 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700785 density = atoi(property);
786 }
787 return density;
788 }
789 public:
790 static int getEmuDensity() {
791 return getDensityFromProperty("qemu.sf.lcd_density"); }
792 static int getBuildDensity() {
793 return getDensityFromProperty("ro.sf.lcd_density"); }
794 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700795
Dan Stoza7f7da322014-05-02 15:26:25 -0700796 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700797
Steven Thomas6d8110b2017-08-31 18:24:21 -0700798 ConditionalLock _l(mStateLock,
799 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800800 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700801 DisplayInfo info = DisplayInfo();
802
Dan Stoza9e56aa02015-11-02 13:00:03 -0800803 float xdpi = hwConfig->getDpiX();
804 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700805
806 if (type == DisplayDevice::DISPLAY_PRIMARY) {
807 // The density of the device is provided by a build property
808 float density = Density::getBuildDensity() / 160.0f;
809 if (density == 0) {
810 // the build doesn't provide a density -- this is wrong!
811 // use xdpi instead
812 ALOGE("ro.sf.lcd_density must be defined as a build property");
813 density = xdpi / 160.0f;
814 }
815 if (Density::getEmuDensity()) {
816 // if "qemu.sf.lcd_density" is specified, it overrides everything
817 xdpi = ydpi = density = Density::getEmuDensity();
818 density /= 160.0f;
819 }
820 info.density = density;
821
822 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700823 const auto display = getDefaultDisplayDeviceLocked();
824 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700825 } else {
826 // TODO: where should this value come from?
827 static const int TV_DENSITY = 213;
828 info.density = TV_DENSITY / 160.0f;
829 info.orientation = 0;
830 }
831
Dan Stoza9e56aa02015-11-02 13:00:03 -0800832 info.w = hwConfig->getWidth();
833 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700834 info.xdpi = xdpi;
835 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800836 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900837 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800838
Andy McFadden91b2ca82014-06-13 14:04:23 -0700839 // This is how far in advance a buffer must be queued for
840 // presentation at a given time. If you want a buffer to appear
841 // on the screen at time N, you must submit the buffer before
842 // (N - presentationDeadline).
843 //
844 // Normally it's one full refresh period (to give SF a chance to
845 // latch the buffer), but this can be reduced by configuring a
846 // DispSync offset. Any additional delays introduced by the hardware
847 // composer or panel must be accounted for here.
848 //
849 // We add an additional 1ms to allow for processing time and
850 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800851 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800852 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700853
854 // All non-virtual displays are currently considered secure.
855 info.secure = true;
856
Iris Chang7501ed62018-04-30 14:45:42 +0800857 if (type == DisplayDevice::DISPLAY_PRIMARY &&
858 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
859 std::swap(info.w, info.h);
860 }
861
Michael Wright28f24d02016-07-12 13:30:53 -0700862 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700863 }
864
Dan Stoza7f7da322014-05-02 15:26:25 -0700865 return NO_ERROR;
866}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700867
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700868status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
869 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700870 return BAD_VALUE;
871 }
872
873 // FIXME for now we always return stats for the primary display
874 memset(stats, 0, sizeof(*stats));
Lloyd Pique41be5d22018-06-21 13:11:48 -0700875 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
876 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700877 return NO_ERROR;
878}
879
Yiwei Zhangcd3f9e92018-08-21 15:15:42 -0700880status_t SurfaceFlinger::getDisplayViewport(const sp<IBinder>& display, Rect* outViewport) {
881 if (outViewport == nullptr || display.get() == nullptr) {
882 return BAD_VALUE;
883 }
884
885 sp<const DisplayDevice> device(getDisplayDevice(display));
886 if (device == nullptr) {
887 return BAD_VALUE;
888 }
889
890 *outViewport = device->getViewport();
891
892 return NO_ERROR;
893}
894
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700895int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
896 const auto display = getDisplayDevice(displayToken);
897 if (!display) {
898 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800899 return BAD_VALUE;
900 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700901
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700902 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700903}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700904
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700905void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
906 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700907 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700908 return;
909 }
910
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700911 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700912 ALOGW("Trying to set config for virtual display");
913 return;
914 }
915
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700916 display->setActiveConfig(mode);
917 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700918}
919
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700920status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700921 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700922 Vector<DisplayInfo> configs;
923 getDisplayConfigs(displayToken, &configs);
924 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
925 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
926 configs.size());
927 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700928 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700929 const auto display = getDisplayDevice(displayToken);
930 if (!display) {
931 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
932 displayToken.get());
933 } else if (display->isVirtual()) {
934 ALOGW("Attempt to set active config %d for virtual display", mode);
935 } else {
936 setActiveConfigInternal(display, mode);
937 }
938 }));
939
Mathias Agopian888c8222012-08-04 21:10:38 -0700940 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700941}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700942status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
943 Vector<ColorMode>* outColorModes) {
944 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700945 return BAD_VALUE;
946 }
947
Michael Wright28f24d02016-07-12 13:30:53 -0700948 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700949 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
950 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700951 type = i;
952 break;
953 }
954 }
955
956 if (type < 0) {
957 return type;
958 }
959
Peiyong Lina52f0292018-03-14 17:26:31 -0700960 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700961 {
962 ConditionalLock _l(mStateLock,
963 std::this_thread::get_id() != mMainThreadId);
964 modes = getHwComposer().getColorModes(type);
965 }
Michael Wright28f24d02016-07-12 13:30:53 -0700966 outColorModes->clear();
967 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
968
969 return NO_ERROR;
970}
971
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700972ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
973 if (const auto display = getDisplayDevice(displayToken)) {
974 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700975 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700976 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700977}
978
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700979void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
980 Dataspace dataSpace, RenderIntent renderIntent) {
981 ColorMode currentMode = display->getActiveColorMode();
982 Dataspace currentDataSpace = display->getCompositionDataSpace();
983 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -0700984
Peiyong Lin38e9a562018-04-10 16:24:20 -0700985 if (mode == currentMode && dataSpace == currentDataSpace &&
986 renderIntent == currentRenderIntent) {
987 return;
988 }
989
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700990 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -0700991 ALOGW("Trying to set config for virtual display");
992 return;
993 }
994
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700995 display->setActiveColorMode(mode);
996 display->setCompositionDataSpace(dataSpace);
997 display->setActiveRenderIntent(renderIntent);
998 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800999
1000 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001001 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1002 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001003}
1004
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001005status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001006 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001007 Vector<ColorMode> modes;
1008 getDisplayColorModes(displayToken, &modes);
1009 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1010 if (mode < ColorMode::NATIVE || !exists) {
1011 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1012 decodeColorMode(mode).c_str(), mode, displayToken.get());
1013 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001014 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001015 const auto display = getDisplayDevice(displayToken);
1016 if (!display) {
1017 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1018 decodeColorMode(mode).c_str(), mode, displayToken.get());
1019 } else if (display->isVirtual()) {
1020 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1021 decodeColorMode(mode).c_str(), mode);
1022 } else {
1023 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1024 RenderIntent::COLORIMETRIC);
1025 }
1026 }));
1027
Michael Wright28f24d02016-07-12 13:30:53 -07001028 return NO_ERROR;
1029}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001030
Svetoslavd85084b2014-03-20 10:28:31 -07001031status_t SurfaceFlinger::clearAnimationFrameStats() {
1032 Mutex::Autolock _l(mStateLock);
1033 mAnimFrameTracker.clearStats();
1034 return NO_ERROR;
1035}
1036
1037status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1038 Mutex::Autolock _l(mStateLock);
1039 mAnimFrameTracker.getStats(outStats);
1040 return NO_ERROR;
1041}
1042
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001043status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1044 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001045 Mutex::Autolock _l(mStateLock);
1046
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001047 const auto display = getDisplayDeviceLocked(displayToken);
1048 if (!display) {
1049 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001050 return BAD_VALUE;
1051 }
1052
Peiyong Linfb069302018-04-25 14:34:31 -07001053 // At this point the DisplayDeivce should already be set up,
1054 // meaning the luminance information is already queried from
1055 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001056 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001057 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1058 capabilities.getDesiredMaxLuminance(),
1059 capabilities.getDesiredMaxAverageLuminance(),
1060 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001061
1062 return NO_ERROR;
1063}
1064
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001065status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001066 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001067 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001068
Chia-I Wu90f669f2017-10-05 14:24:41 -07001069 if (mInjectVSyncs == enable) {
1070 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001071 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001072
1073 if (enable) {
1074 ALOGV("VSync Injections enabled");
1075 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001076 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001077 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001078 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001079 impl::EventThread::InterceptVSyncsCallback(),
1080 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001081 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001082 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001083 } else {
1084 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001085 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001086 }
1087
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001088 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001089 }));
1090
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001091 return NO_ERROR;
1092}
1093
1094status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001095 Mutex::Autolock _l(mStateLock);
1096
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001097 if (!mInjectVSyncs) {
1098 ALOGE("VSync Injections not enabled");
1099 return BAD_VALUE;
1100 }
1101 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1102 ALOGV("Injecting VSync inside SurfaceFlinger");
1103 mVSyncInjector->onInjectSyncEvent(when);
1104 }
1105 return NO_ERROR;
1106}
1107
Lloyd Pique755e3192018-01-31 16:46:15 -08001108status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1109 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001110 // Try to acquire a lock for 1s, fail gracefully
1111 const status_t err = mStateLock.timedLock(s2ns(1));
1112 const bool locked = (err == NO_ERROR);
1113 if (!locked) {
1114 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1115 return TIMED_OUT;
1116 }
1117
1118 outLayers->clear();
1119 mCurrentState.traverseInZOrder([&](Layer* layer) {
1120 outLayers->push_back(layer->getLayerDebugInfo());
1121 });
1122
1123 mStateLock.unlock();
1124 return NO_ERROR;
1125}
1126
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001127// ----------------------------------------------------------------------------
1128
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001129sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1130 ISurfaceComposer::VsyncSource vsyncSource) {
1131 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1132 return mSFEventThread->createEventConnection();
1133 } else {
1134 return mEventThread->createEventConnection();
1135 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001136}
1137
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001138// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001139
1140void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001141 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001142}
1143
1144void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001145 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001146}
1147
1148void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001149 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001150}
1151
1152void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001153 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001154 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001155}
1156
1157status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001158 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001159 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001160}
1161
1162status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001163 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001164 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001165 if (res == NO_ERROR) {
1166 msg->wait();
1167 }
1168 return res;
1169}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001170
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001171void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001172 do {
1173 waitForEvent();
1174 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001175}
1176
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001177void SurfaceFlinger::enableHardwareVsync() {
1178 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001179 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001180 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001181 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001182 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001183 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001184}
1185
Jesse Hall948fe0c2013-10-14 12:56:09 -07001186void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001187 Mutex::Autolock _l(mHWVsyncLock);
1188
Jesse Hall948fe0c2013-10-14 12:56:09 -07001189 if (makeAvailable) {
1190 mHWVsyncAvailable = true;
1191 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001192 // Hardware vsync is not currently available, so abort the resync
1193 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001194 return;
1195 }
1196
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001197 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1198 if (!getHwComposer().isConnected(displayId)) {
1199 return;
1200 }
1201
1202 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001203 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001204
Lloyd Pique41be5d22018-06-21 13:11:48 -07001205 mPrimaryDispSync->reset();
1206 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001207
1208 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001209 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001210 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001211 mPrimaryHWVsyncEnabled = true;
1212 }
1213}
1214
Jesse Hall948fe0c2013-10-14 12:56:09 -07001215void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001216 Mutex::Autolock _l(mHWVsyncLock);
1217 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001218 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001219 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001220 mPrimaryHWVsyncEnabled = false;
1221 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001222 if (makeUnavailable) {
1223 mHWVsyncAvailable = false;
1224 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001225}
1226
Tim Murray4a4e4a22016-04-19 16:29:23 +00001227void SurfaceFlinger::resyncWithRateLimit() {
1228 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001229
1230 // No explicit locking is needed here since EventThread holds a lock while calling this method
1231 static nsecs_t sLastResyncAttempted = 0;
1232 const nsecs_t now = systemTime();
1233 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001234 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001235 }
Dan Stoza57164302017-05-08 14:03:54 -07001236 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001237}
1238
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001239void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1240 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001241 ATRACE_NAME("SF onVsync");
1242
Steven Thomas3cfac282017-02-06 12:29:30 -08001243 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001244 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001245 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001246 return;
1247 }
1248
1249 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001250 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001251 return;
1252 }
1253
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001254 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1255 // For now, we don't do anything with external display vsyncs.
1256 return;
1257 }
1258
Jamie Gennisd1700752013-10-14 12:22:52 -07001259 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001260
Jamie Gennisd1700752013-10-14 12:22:52 -07001261 { // Scope for the lock
1262 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001263 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001264 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001265 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001266 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001267
1268 if (needsHwVsync) {
1269 enableHardwareVsync();
1270 } else {
1271 disableHardwareVsync(false);
1272 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001273}
1274
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001275void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001276 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1277 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001278}
1279
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001280void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001281 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001282 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001283 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001284
Lloyd Piqueba04e622017-12-14 17:11:26 -08001285 // Ignore events that do not have the right sequenceId.
1286 if (sequenceId != getBE().mComposerSequenceId) {
1287 return;
1288 }
1289
Steven Thomasb02664d2017-07-26 18:48:28 -07001290 // Only lock if we're not on the main thread. This function is normally
1291 // called on a hwbinder thread, but for the primary display it's called on
1292 // the main thread with the state lock already held, so don't attempt to
1293 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001294 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001295
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001296 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001297
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001298 if (std::this_thread::get_id() == mMainThreadId) {
1299 // Process all pending hot plug events immediately if we are on the main thread.
1300 processDisplayHotplugEventsLocked();
1301 }
1302
Lloyd Piqueba04e622017-12-14 17:11:26 -08001303 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001304}
1305
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001306void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001307 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001308 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001309 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001310 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001311 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001312}
1313
Dan Stoza9e56aa02015-11-02 13:00:03 -08001314void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001315 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001316 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001317 getHwComposer().setVsyncEnabled(disp,
1318 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001319}
1320
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001321// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001322void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001323 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001324 // Clear the drawing state so that the logic inside of
1325 // handleTransactionLocked will fire. It will determine the delta between
1326 // mCurrentState and mDrawingState and re-apply all changes when we make the
1327 // transition.
1328 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001329 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001330 mDisplays.clear();
1331}
1332
Steven Thomas050b2c82017-03-06 11:45:16 -08001333void SurfaceFlinger::updateVrFlinger() {
1334 if (!mVrFlinger)
1335 return;
1336 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001337 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001338 return;
1339 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001340
David Sodman105b7dc2017-11-04 20:28:14 -07001341 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001342 ALOGE("Vr flinger is only supported for remote hardware composer"
1343 " service connections. Ignoring request to transition to vr"
1344 " flinger.");
1345 mVrFlingerRequestsDisplay = false;
1346 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001347 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001348
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001349 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001350
Steven Thomas0123ac62018-07-12 11:32:34 -07001351 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001352 LOG_ALWAYS_FATAL_IF(!display);
1353 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001354 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1355 // called below. Clear the reference now so we don't accidentally use it
1356 // later.
1357 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001358
Steven Thomasb02664d2017-07-26 18:48:28 -07001359 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001360 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001361 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001362
Steven Thomasb02664d2017-07-26 18:48:28 -07001363 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001364 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001365 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1366 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001367 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001368
David Sodman105b7dc2017-11-04 20:28:14 -07001369 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1370 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001371
1372 if (vrFlingerRequestsDisplay) {
1373 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001374 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001375
1376 mVisibleRegionsDirty = true;
1377 invalidateHwcGeometry();
1378
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001379 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001380 display = getDefaultDisplayDeviceLocked();
1381 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001382 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001383
Steven Thomasb02664d2017-07-26 18:48:28 -07001384 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001385 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001386 const nsecs_t period = activeConfig->getVsyncPeriod();
1387 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001388
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001389 // The present fences returned from vr_hwc are not an accurate
1390 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001391 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1392 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001393
Steven Thomasb02664d2017-07-26 18:48:28 -07001394 // Use phase of 0 since phase is not known.
1395 // Use latency of 0, which will snap to the ideal latency.
1396 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001397
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001398 resyncToHardwareVsync(false);
1399
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001400 android_atomic_or(1, &mRepaintEverything);
1401 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001402}
1403
Mathias Agopian4fec8732012-06-29 14:12:52 -07001404void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001405 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001406 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001407 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001408 bool frameMissed = !mHadClientComposition &&
1409 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001410 (mPreviousPresentFence->getSignalTime() ==
1411 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001412 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001413 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001414 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001415 mTimeStats.incrementMissedFrames();
1416 if (mPropagateBackpressure) {
1417 signalLayerUpdate();
1418 break;
1419 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001420 }
Dan Stoza50182882016-07-08 12:02:20 -07001421
Steven Thomas050b2c82017-03-06 11:45:16 -08001422 // Now that we're going to make it to the handleMessageTransaction()
1423 // call below it's safe to call updateVrFlinger(), which will
1424 // potentially trigger a display handoff.
1425 updateVrFlinger();
1426
Dan Stoza6b9454d2014-11-07 16:00:59 -08001427 bool refreshNeeded = handleMessageTransaction();
1428 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001429 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001430 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001431 // Signal a refresh if a transaction modified the window state,
1432 // a new buffer was latched, or if HWC has requested a full
1433 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001434 signalRefresh();
1435 }
1436 break;
1437 }
1438 case MessageQueue::REFRESH: {
1439 handleMessageRefresh();
1440 break;
1441 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001442 }
1443}
1444
Dan Stoza6b9454d2014-11-07 16:00:59 -08001445bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001446 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001447 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001448 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001449 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001450 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001451 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001452}
1453
Mathias Agopian4fec8732012-06-29 14:12:52 -07001454void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001455 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001456
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001457 mRefreshPending = false;
1458
David Sodmanfa9b2af2017-12-24 13:28:59 -08001459 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
David Sodman2b406362017-12-15 13:33:47 -08001460 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001461 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001462 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001463 for (const auto& [token, display] : mDisplays) {
1464 beginFrame(display);
1465 prepareFrame(display);
1466 doDebugFlashRegions(display, repaintEverything);
1467 doComposition(display, repaintEverything);
1468 }
1469
Adrian Roos1e1a1282017-11-01 19:05:31 +01001470 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001471 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001472
1473 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001474 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001475
Dan Stozabfbffeb2016-07-21 14:49:33 -07001476 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001477 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001478 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001479 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001480 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001481
Jorim Jaggi90535212018-05-23 23:44:06 +02001482 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001483
Dan Stoza9e56aa02015-11-02 13:00:03 -08001484 mLayersWithQueuedFrames.clear();
David Sodmanba340492018-08-05 21:51:33 -07001485 for (auto& compositionInfo : getBE().mCompositionInfo) {
1486 compositionInfo.hwc.hwcLayer = nullptr;
1487 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001488}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001489
David Sodmanfa9b2af2017-12-24 13:28:59 -08001490
1491bool SurfaceFlinger::handleMessageInvalidate() {
1492 ATRACE_CALL();
1493 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001494}
1495
David Sodman79bba0e2018-08-05 18:07:49 -07001496void SurfaceFlinger::calculateWorkingSet() {
1497 ATRACE_CALL();
1498 ALOGV(__FUNCTION__);
1499
David Sodman79bba0e2018-08-05 18:07:49 -07001500 // build the h/w work list
1501 if (CC_UNLIKELY(mGeometryInvalid)) {
1502 mGeometryInvalid = false;
1503 for (const auto& [token, display] : mDisplays) {
1504 const auto displayId = display->getId();
1505 if (displayId >= 0) {
1506 const Vector<sp<Layer>>& currentLayers(
1507 display->getVisibleLayersSortedByZ());
1508 for (size_t i = 0; i < currentLayers.size(); i++) {
1509 const auto& layer = currentLayers[i];
1510
1511 if (!layer->hasHwcLayer(displayId)) {
1512 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1513 layer->forceClientComposition(displayId);
1514 continue;
1515 }
1516 }
1517
1518 layer->setGeometry(display, i);
1519 if (mDebugDisableHWC || mDebugRegion) {
1520 layer->forceClientComposition(displayId);
1521 }
1522 }
1523 }
1524 }
1525 }
1526
1527 // Set the per-frame data
1528 for (const auto& [token, display] : mDisplays) {
1529 const auto displayId = display->getId();
1530 if (displayId < 0) {
1531 continue;
1532 }
1533
1534 if (mDrawingState.colorMatrixChanged) {
1535 display->setColorTransform(mDrawingState.colorMatrix);
1536 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1537 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1538 "display %d: %d", displayId, result);
1539 }
1540 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1541 if (layer->isHdrY410()) {
1542 layer->forceClientComposition(displayId);
1543 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1544 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1545 !display->hasHDR10Support()) {
1546 layer->forceClientComposition(displayId);
1547 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1548 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1549 !display->hasHLGSupport()) {
1550 layer->forceClientComposition(displayId);
1551 }
1552
1553 if (layer->getForceClientComposition(displayId)) {
1554 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1555 layer->setCompositionType(displayId, HWC2::Composition::Client);
1556 continue;
1557 }
1558
1559 layer->setPerFrameData(display);
1560 }
1561
Peiyong Lin13effd12018-07-24 17:01:47 -07001562 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001563 ColorMode colorMode;
1564 Dataspace dataSpace;
1565 RenderIntent renderIntent;
1566 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1567 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1568 }
1569 }
1570
1571 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001572 getBE().mCompositionInfo.clear();
1573
1574 for (const auto& [token, display] : mDisplays) {
1575 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1576 auto displayId = display->getId();
1577 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1578 if (!layer->setHwcLayer(displayId)) {
1579 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1580 }
1581 getBE().mCompositionInfo.push_back(layer->getBE().compositionInfo);
1582 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1583 }
1584 }
David Sodman79bba0e2018-08-05 18:07:49 -07001585}
1586
David Sodmanfa9b2af2017-12-24 13:28:59 -08001587void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001588{
1589 // is debugging enabled
1590 if (CC_LIKELY(!mDebugRegion))
1591 return;
1592
David Sodmanfa9b2af2017-12-24 13:28:59 -08001593 if (display->isPoweredOn()) {
1594 // transform the dirty region into this screen's coordinate space
1595 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1596 if (!dirtyRegion.isEmpty()) {
1597 // redraw the whole screen
1598 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001599
David Sodmanfa9b2af2017-12-24 13:28:59 -08001600 // and draw the dirty region
1601 const int32_t height = display->getHeight();
1602 auto& engine(getRenderEngine());
1603 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001604
David Sodmanfa9b2af2017-12-24 13:28:59 -08001605 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001606 }
1607 }
1608
David Sodmanfa9b2af2017-12-24 13:28:59 -08001609 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001610
1611 if (mDebugRegion > 1) {
1612 usleep(mDebugRegion * 1000);
1613 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001614
David Sodmanfa9b2af2017-12-24 13:28:59 -08001615 if (display->isPoweredOn()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001616 status_t result = display->prepareFrame(*getBE().mHwc);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001617 ALOGE_IF(result != NO_ERROR,
1618 "prepareFrame for display %d failed:"
1619 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001620 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001621 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001622}
1623
Adrian Roos1e1a1282017-11-01 19:05:31 +01001624void SurfaceFlinger::doTracing(const char* where) {
1625 ATRACE_CALL();
1626 ATRACE_NAME(where);
1627 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001628 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001629 }
1630}
1631
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001632void SurfaceFlinger::logLayerStats() {
1633 ATRACE_CALL();
1634 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001635 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001636 if (display->isPrimary()) {
1637 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001638 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001639 }
1640 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001641
1642 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001643 }
1644}
1645
David Sodman2b406362017-12-15 13:33:47 -08001646void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001647{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001648 ATRACE_CALL();
1649 ALOGV("preComposition");
1650
David Sodman2b406362017-12-15 13:33:47 -08001651 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1652
Mathias Agopiancd60f992012-08-16 16:28:27 -07001653 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001654 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001655 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001656 needExtraInvalidate = true;
1657 }
Robert Carr2047fae2016-11-28 14:09:09 -08001658 });
1659
Mathias Agopiancd60f992012-08-16 16:28:27 -07001660 if (needExtraInvalidate) {
1661 signalLayerUpdate();
1662 }
1663}
1664
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001665void SurfaceFlinger::updateCompositorTiming(
1666 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1667 std::shared_ptr<FenceTime>& presentFenceTime) {
1668 // Update queue of past composite+present times and determine the
1669 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001670 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001671 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001672 while (!getBE().mCompositePresentTimes.empty()) {
1673 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001674 // Cached values should have been updated before calling this method,
1675 // which helps avoid duplicate syscalls.
1676 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1677 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1678 break;
1679 }
1680 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001681 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001682 }
1683
1684 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001685 while (getBE().mCompositePresentTimes.size() > 16) {
1686 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001687 }
1688
Brian Andersond0010582017-03-07 13:20:31 -08001689 setCompositorTimingSnapped(
1690 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1691}
1692
1693void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1694 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001695 // Integer division and modulo round toward 0 not -inf, so we need to
1696 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001697 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001698 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1699 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1700
Brian Andersond0010582017-03-07 13:20:31 -08001701 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1702 if (idealLatency <= 0) {
1703 idealLatency = vsyncInterval;
1704 }
1705
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001706 // Snap the latency to a value that removes scheduling jitter from the
1707 // composition and present times, which often have >1ms of jitter.
1708 // Reducing jitter is important if an app attempts to extrapolate
1709 // something (such as user input) to an accurate diasplay time.
1710 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1711 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001712 nsecs_t bias = vsyncInterval / 2;
1713 int64_t extraVsyncs =
1714 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1715 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1716 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001717
David Sodman99974d22017-11-28 12:04:33 -08001718 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1719 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1720 getBE().mCompositorTiming.interval = vsyncInterval;
1721 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001722}
1723
David Sodman2b406362017-12-15 13:33:47 -08001724void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001725{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001726 ATRACE_CALL();
1727 ALOGV("postComposition");
1728
Brian Anderson3546a3f2016-07-14 11:51:14 -07001729 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001730 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001731 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001732 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001733 }
1734
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001735 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001736 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001737
David Sodman73beded2017-11-15 11:56:06 -08001738 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001739 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001740 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001741 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001742 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001743 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001744 } else {
1745 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1746 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001747
David Sodman73beded2017-11-15 11:56:06 -08001748 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001749 mPreviousPresentFence =
1750 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1751 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001752 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001753
Lloyd Pique41be5d22018-06-21 13:11:48 -07001754 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1755 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001756
David Sodman2b406362017-12-15 13:33:47 -08001757 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001758 // when we started doing work for this frame, but that should be okay
1759 // since updateCompositorTiming has snapping logic.
1760 updateCompositorTiming(
David Sodman2b406362017-12-15 13:33:47 -08001761 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001762 CompositorTiming compositorTiming;
1763 {
David Sodman99974d22017-11-28 12:04:33 -08001764 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1765 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001766 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001767
Robert Carr2047fae2016-11-28 14:09:09 -08001768 mDrawingState.traverseInZOrder([&](Layer* layer) {
1769 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001770 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001771 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001772 recordBufferingStats(layer->getName().string(),
1773 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001774 }
Robert Carr2047fae2016-11-28 14:09:09 -08001775 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001776
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001777 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001778 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001779 enableHardwareVsync();
1780 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001781 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001782 }
1783 }
1784
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001785 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001786 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001787 enableHardwareVsync();
1788 }
1789 }
1790
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001791 if (mAnimCompositionPending) {
1792 mAnimCompositionPending = false;
1793
Brian Anderson4e606e32017-03-16 15:34:57 -07001794 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001795 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001796 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001797 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001798 // The HWC doesn't support present fences, so use the refresh
1799 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001800 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001801 mAnimFrameTracker.setActualPresentTime(presentTime);
1802 }
1803 mAnimFrameTracker.advanceFrame();
1804 }
Dan Stozab90cf072015-03-05 11:05:59 -08001805
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001806 mTimeStats.incrementTotalFrames();
1807 if (mHadClientComposition) {
1808 mTimeStats.incrementClientCompositionFrames();
1809 }
1810
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001811 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001812 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001813 return;
1814 }
1815
1816 nsecs_t currentTime = systemTime();
1817 if (mHasPoweredOff) {
1818 mHasPoweredOff = false;
1819 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001820 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001821 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001822 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1823 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001824 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001825 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001826 }
David Sodman4a36e932017-11-07 14:29:47 -08001827 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001828 }
David Sodman4a36e932017-11-07 14:29:47 -08001829 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001830
1831 {
1832 std::lock_guard lock(mTexturePoolMutex);
1833 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1834 if (refillCount > 0) {
1835 const size_t offset = mTexturePool.size();
1836 mTexturePool.resize(mTexturePoolSize);
1837 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1838 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1839 }
1840 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001841}
1842
1843void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001844 ATRACE_CALL();
1845 ALOGV("rebuildLayerStacks");
1846
Mathias Agopiancd60f992012-08-16 16:28:27 -07001847 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001848 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001849 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001850 mVisibleRegionsDirty = false;
1851 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001852
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001853 for (const auto& pair : mDisplays) {
1854 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001855 Region opaqueRegion;
1856 Region dirtyRegion;
1857 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001858 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001859 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001860 const Rect bounds = display->getBounds();
1861 if (display->isPoweredOn()) {
1862 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001863
Jeff Sharkey76488112017-02-27 14:15:18 -07001864 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001865 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001866 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001867 Region drawRegion(tr.transform(
1868 layer->visibleNonTransparentRegion));
1869 drawRegion.andSelf(bounds);
1870 if (!drawRegion.isEmpty()) {
1871 layersSortedByZ.add(layer);
1872 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001873 // Clear out the HWC layer if this layer was
1874 // previously visible, but no longer is
1875 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001876 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001877 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001878 // WM changes display->layerStack upon sleep/awake.
1879 // Here we make sure we delete the HWC layers even if
1880 // WM changed their layer stack.
1881 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001882 }
1883
1884 // If a layer is not going to get a release fence because
1885 // it is invisible, but it is also going to release its
1886 // old buffer, add it to the list of layers needing
1887 // fences.
1888 if (hwcLayerDestroyed) {
1889 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1890 mLayersWithQueuedFrames.cend(), layer);
1891 if (found != mLayersWithQueuedFrames.cend()) {
1892 layersNeedingFences.add(layer);
1893 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001894 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001895 });
1896 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001897 display->setVisibleLayersSortedByZ(layersSortedByZ);
1898 display->setLayersNeedingFences(layersNeedingFences);
1899 display->undefinedRegion.set(bounds);
1900 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1901 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001902 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001903 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001904}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001905
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001906// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001907// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001908// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001909// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001910// The returned HDR data space is one of
1911// - Dataspace::UNKNOWN
1912// - Dataspace::BT2020_HLG
1913// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001914Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1915 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001916 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001917 *outHdrDataSpace = Dataspace::UNKNOWN;
1918
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001919 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001920 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001921 case Dataspace::V0_SCRGB:
1922 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001923 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001924 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001925 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001926 case Dataspace::BT2020_PQ:
1927 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001928 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001929 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001930 case Dataspace::BT2020_HLG:
1931 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001932 // When there's mixed PQ content and HLG content, we set the HDR
1933 // data space to be BT2020_PQ and convert HLG to PQ.
1934 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1935 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001936 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001937 break;
1938 default:
1939 break;
1940 }
Romain Guy54f154a2017-10-24 21:40:32 +01001941 }
1942
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001943 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001944}
1945
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001946// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001947void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1948 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001949 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1950 *outMode = ColorMode::NATIVE;
1951 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001952 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001953 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001954 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001955
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001956 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001957 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001958
Peiyong Lindfde5112018-06-05 10:58:41 -07001959 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001960 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001961 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001962 if (isHdr) {
1963 bestDataSpace = hdrDataSpace;
1964 }
1965
Chia-I Wu0d711262018-05-21 15:19:35 -07001966 RenderIntent intent;
1967 switch (mDisplayColorSetting) {
1968 case DisplayColorSetting::MANAGED:
1969 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001970 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001971 break;
1972 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001973 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001974 break;
1975 default: // vendor display color setting
1976 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1977 break;
1978 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001979
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001980 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001981}
1982
David Sodmanfa9b2af2017-12-24 13:28:59 -08001983void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08001984{
David Sodmanfa9b2af2017-12-24 13:28:59 -08001985 bool dirty = !display->getDirtyRegion(false).isEmpty();
1986 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
1987 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08001988
David Sodmanfa9b2af2017-12-24 13:28:59 -08001989 // If nothing has changed (!dirty), don't recompose.
1990 // If something changed, but we don't currently have any visible layers,
1991 // and didn't when we last did a composition, then skip it this time.
1992 // The second rule does two things:
1993 // - When all layers are removed from a display, we'll emit one black
1994 // frame, then nothing more until we get new layers.
1995 // - When a display is created with a private layer stack, we won't
1996 // emit any black frames until a layer is added to the layer stack.
1997 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08001998
David Sodmanfa9b2af2017-12-24 13:28:59 -08001999 ALOGV_IF(displayDevice->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2000 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
2001 mustRecompose ? "doing" : "skipping",
2002 dirty ? "+" : "-",
2003 empty ? "+" : "-",
2004 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002005
David Sodmanfa9b2af2017-12-24 13:28:59 -08002006 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002007
David Sodmanfa9b2af2017-12-24 13:28:59 -08002008 if (mustRecompose) {
2009 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002010 }
2011}
2012
David Sodmanfa9b2af2017-12-24 13:28:59 -08002013void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002014{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002015 if (!display->isPoweredOn()) {
2016 return;
David Sodman2b406362017-12-15 13:33:47 -08002017 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002018
2019 status_t result = display->prepareFrame(*getBE().mHwc);
2020 ALOGE_IF(result != NO_ERROR,
2021 "prepareFrame for display %d failed:"
2022 " %d (%s)",
2023 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002024}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002025
David Sodmanfa9b2af2017-12-24 13:28:59 -08002026void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002027 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002028 ALOGV("doComposition");
2029
David Sodmanfa9b2af2017-12-24 13:28:59 -08002030 if (display->isPoweredOn()) {
2031 // transform the dirty region into this screen's coordinate space
2032 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002033
David Sodmanfa9b2af2017-12-24 13:28:59 -08002034 // repaint the framebuffer (if needed)
2035 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002036
David Sodmanfa9b2af2017-12-24 13:28:59 -08002037 display->dirtyRegion.clear();
2038 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002039 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002040 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002041}
2042
David Sodmanfa9b2af2017-12-24 13:28:59 -08002043void SurfaceFlinger::postFrame()
2044{
2045 // |mStateLock| not needed as we are on the main thread
2046 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2047 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2048 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2049 logFrameStats();
2050 }
2051 }
2052}
2053
2054void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002055{
Mathias Agopian841cde52012-03-01 15:44:37 -08002056 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002057 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002058
David Sodmanfa9b2af2017-12-24 13:28:59 -08002059 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002060
David Sodmanfa9b2af2017-12-24 13:28:59 -08002061 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002062 const auto displayId = display->getId();
2063 if (displayId >= 0) {
2064 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002065 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002066 display->onSwapBuffersCompleted();
2067 display->makeCurrent();
2068 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002069 sp<Fence> releaseFence = Fence::NO_FENCE;
2070
Chia-I Wu7b549592017-11-15 09:14:57 -08002071 // The layer buffer from the previous frame (if any) is released
2072 // by HWC only when the release fence from this frame (if any) is
2073 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002074 auto hwcLayer = layer->getHwcLayer(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002075 if (displayId >= 0) {
2076 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
2077 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002078
2079 // If the layer was client composited in the previous frame, we
2080 // need to merge with the previous client target acquire fence.
2081 // Since we do not track that, always merge with the current
2082 // client target acquire fence when it is available, even though
2083 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002084 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002085 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002086 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002087 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002088
David Sodmanb8af7922017-12-21 15:17:55 -08002089 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002090 }
Chia-I Wu83806892017-11-16 10:50:20 -08002091
2092 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002093 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002094 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002095 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002096 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002097 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002098 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002099 }
2100 }
2101
Dominik Laskowski7e045462018-05-30 13:02:02 -07002102 if (displayId >= 0) {
2103 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002104 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002105 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002106}
2107
Mathias Agopian87baae12012-07-31 12:38:26 -07002108void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002109{
Mathias Agopian841cde52012-03-01 15:44:37 -08002110 ATRACE_CALL();
2111
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002112 // here we keep a copy of the drawing state (that is the state that's
2113 // going to be overwritten by handleTransactionLocked()) outside of
2114 // mStateLock so that the side-effects of the State assignment
2115 // don't happen with mStateLock held (which can cause deadlocks).
2116 State drawingState(mDrawingState);
2117
Mathias Agopianca4d3602011-05-19 15:38:14 -07002118 Mutex::Autolock _l(mStateLock);
2119 const nsecs_t now = systemTime();
2120 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002121
Mathias Agopianca4d3602011-05-19 15:38:14 -07002122 // Here we're guaranteed that some transaction flags are set
2123 // so we can call handleTransactionLocked() unconditionally.
2124 // We call getTransactionFlags(), which will also clear the flags,
2125 // with mStateLock held to guarantee that mCurrentState won't change
2126 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002127
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002128 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002129 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002130 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002131
Mathias Agopianca4d3602011-05-19 15:38:14 -07002132 mLastTransactionTime = systemTime() - now;
2133 mDebugInTransaction = 0;
2134 invalidateHwcGeometry();
2135 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002136}
2137
Dominik Laskowski7e045462018-05-30 13:02:02 -07002138DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002139 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002140 // Figure out whether the event is for the primary display or an
2141 // external display by matching the Hwc display id against one for a
2142 // connected display. If we did not find a match, we then check what
2143 // displays are not already connected to determine the type. If we don't
2144 // have a connected primary display, we assume the new display is meant to
2145 // be the primary display, and then if we don't have an external display,
2146 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002147 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2148 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002149 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002150 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002151 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002152 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002153 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002154 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002155 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002156 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002157 return DisplayDevice::DISPLAY_EXTERNAL;
2158 }
2159
2160 return DisplayDevice::DISPLAY_ID_INVALID;
2161}
2162
Lloyd Piqueba04e622017-12-14 17:11:26 -08002163void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2164 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002165 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002166 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002167 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002168 continue;
2169 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002170
2171 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2172 ALOGE("External displays are not supported by the vr hardware composer.");
2173 continue;
2174 }
2175
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002176 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002177 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002178 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002179 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002180 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002181
2182 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002183 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002184 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002185 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002186 DisplayDeviceState info;
2187 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002188 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2189 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002190 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002191 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002192 mInterceptor->saveDisplayCreation(info);
2193 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002194 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002195 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002196
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002197 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002198 if (idx >= 0) {
2199 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002200 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002201 mCurrentState.displays.removeItemsAt(idx);
2202 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002203 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002204 }
2205
2206 processDisplayChangesLocked();
2207 }
2208
2209 mPendingHotplugEvents.clear();
2210}
2211
Lloyd Pique99d3da52018-01-22 17:48:03 -08002212sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002213 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002214 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002215 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002216 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002217 HdrCapabilities hdrCapabilities;
2218 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002219
Peiyong Lin13effd12018-07-24 17:01:47 -07002220 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002221 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002222 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002223 if (isWideColorMode(colorMode)) {
2224 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002225 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002226
Dominik Laskowski7e045462018-05-30 13:02:02 -07002227 std::vector<RenderIntent> renderIntents =
2228 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002229 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002230 }
tangrobin6753a022018-08-10 10:58:54 +08002231 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002232
tangrobin6753a022018-08-10 10:58:54 +08002233 if (displayId >= 0) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002234 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2235 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2236 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002237
2238 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2239 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2240
2241 /*
2242 * Create our display's surface
2243 */
2244 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2245 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002246 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002247 renderSurface->setNativeWindow(nativeWindow.get());
2248 const int displayWidth = renderSurface->queryWidth();
2249 const int displayHeight = renderSurface->queryHeight();
2250
2251 // Make sure that composition can never be stalled by a virtual display
2252 // consumer that isn't processing buffers fast enough. We have to do this
2253 // in two places:
2254 // * Here, in case the display is composed entirely by HWC.
2255 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2256 // window's swap interval in eglMakeCurrent, so they'll override the
2257 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002258 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002259 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2260 }
2261
2262 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002263 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002264
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002265 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002266 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2267 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2268 displayHeight, hasWideColorGamut, hdrCapabilities,
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002269 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002270
2271 if (maxFrameBufferAcquiredBuffers >= 3) {
2272 nativeWindowSurface->preallocateBuffers();
2273 }
2274
2275 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002276 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2277 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002278 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002279 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002280 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002281 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002282 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002283 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002284 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002285 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002286 display->setLayerStack(state.layerStack);
2287 display->setProjection(state.orientation, state.viewport, state.frame);
2288 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002289
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002290 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002291}
2292
Lloyd Pique347200f2017-12-14 17:00:15 -08002293void SurfaceFlinger::processDisplayChangesLocked() {
2294 // here we take advantage of Vector's copy-on-write semantics to
2295 // improve performance by skipping the transaction entirely when
2296 // know that the lists are identical
2297 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2298 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2299 if (!curr.isIdenticalTo(draw)) {
2300 mVisibleRegionsDirty = true;
2301 const size_t cc = curr.size();
2302 size_t dc = draw.size();
2303
2304 // find the displays that were removed
2305 // (ie: in drawing state but not in current state)
2306 // also handle displays that changed
2307 // (ie: displays that are in both lists)
2308 for (size_t i = 0; i < dc;) {
2309 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2310 if (j < 0) {
2311 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002312 // Call makeCurrent() on the primary display so we can
2313 // be sure that nothing associated with this display
2314 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002315 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2316 defaultDisplay->makeCurrent();
2317 }
2318 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2319 display->disconnect(getHwComposer());
2320 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002321 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2322 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2323 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2324 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2325 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002326 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002327 } else {
2328 // this display is in both lists. see if something changed.
2329 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002330 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002331 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2332 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2333 if (state_binder != draw_binder) {
2334 // changing the surface is like destroying and
2335 // recreating the DisplayDevice, so we just remove it
2336 // from the drawing state, so that it get re-added
2337 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002338 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2339 display->disconnect(getHwComposer());
2340 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002341 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002342 mDrawingState.displays.removeItemsAt(i);
2343 dc--;
2344 // at this point we must loop to the next item
2345 continue;
2346 }
2347
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002348 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002349 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002350 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002351 }
2352 if ((state.orientation != draw[i].orientation) ||
2353 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002354 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002355 }
2356 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002357 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002358 }
2359 }
2360 }
2361 ++i;
2362 }
2363
2364 // find displays that were added
2365 // (ie: in current state but not in drawing state)
2366 for (size_t i = 0; i < cc; i++) {
2367 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2368 const DisplayDeviceState& state(curr[i]);
2369
2370 sp<DisplaySurface> dispSurface;
2371 sp<IGraphicBufferProducer> producer;
2372 sp<IGraphicBufferProducer> bqProducer;
2373 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002374 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002375
Dominik Laskowski7e045462018-05-30 13:02:02 -07002376 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002377 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002378 // Virtual displays without a surface are dormant:
2379 // they have external state (layer stack, projection,
2380 // etc.) but no internal state (i.e. a DisplayDevice).
2381 if (state.surface != nullptr) {
2382 // Allow VR composer to use virtual displays.
2383 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2384 int width = 0;
2385 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2386 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2387 int height = 0;
2388 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2389 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2390 int intFormat = 0;
2391 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2392 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002393 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002394
Dominik Laskowski7e045462018-05-30 13:02:02 -07002395 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2396 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002397 }
2398
2399 // TODO: Plumb requested format back up to consumer
2400
2401 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002402 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002403 bqProducer, bqConsumer,
2404 state.displayName);
2405
2406 dispSurface = vds;
2407 producer = vds;
2408 }
2409 } else {
2410 ALOGE_IF(state.surface != nullptr,
2411 "adding a supported display, but rendering "
2412 "surface is provided (%p), ignoring it",
2413 state.surface.get());
2414
Dominik Laskowski7e045462018-05-30 13:02:02 -07002415 displayId = state.type;
2416 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002417 producer = bqProducer;
2418 }
2419
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002420 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002421 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002422 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002423 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002424 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002425 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002426 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2427 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2428 true);
2429 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2430 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2431 true);
2432 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002433 }
2434 }
2435 }
2436 }
2437 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002438
2439 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002440}
2441
Mathias Agopian87baae12012-07-31 12:38:26 -07002442void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002443{
Dan Stoza7dde5992015-05-22 09:51:44 -07002444 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002445 mCurrentState.traverseInZOrder([](Layer* layer) {
2446 layer->notifyAvailableFrames();
2447 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002448
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002449 /*
2450 * Traversal of the children
2451 * (perform the transaction for each of them if needed)
2452 */
2453
Mathias Agopian3559b072012-08-15 13:46:03 -07002454 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002455 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002456 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002457 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002458
2459 const uint32_t flags = layer->doTransaction(0);
2460 if (flags & Layer::eVisibleRegion)
2461 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002462 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002463 }
2464
2465 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002466 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002467 */
2468
Mathias Agopiane57f2922012-08-09 16:29:12 -07002469 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002470 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002471 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002472 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002473
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002474 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002475 // The transform hint might have changed for some layers
2476 // (either because a display has changed, or because a layer
2477 // as changed).
2478 //
2479 // Walk through all the layers in currentLayers,
2480 // and update their transform hint.
2481 //
2482 // If a layer is visible only on a single display, then that
2483 // display is used to calculate the hint, otherwise we use the
2484 // default display.
2485 //
2486 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2487 // the hint is set before we acquire a buffer from the surface texture.
2488 //
2489 // NOTE: layer transactions have taken place already, so we use their
2490 // drawing state. However, SurfaceFlinger's own transaction has not
2491 // happened yet, so we must use the current state layer list
2492 // (soon to become the drawing state list).
2493 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002494 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002495 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002496 bool first = true;
2497 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002498 // NOTE: we rely on the fact that layers are sorted by
2499 // layerStack first (so we don't have to traverse the list
2500 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002501 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002502 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002503 currentlayerStack = layerStack;
2504 // figure out if this layerstack is mirrored
2505 // (more than one display) if so, pick the default display,
2506 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002507 hintDisplay = nullptr;
2508 for (const auto& [token, display] : mDisplays) {
2509 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2510 if (hintDisplay) {
2511 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002512 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002513 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002514 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002515 }
2516 }
2517 }
2518 }
Chet Haase91d25932013-04-11 15:24:55 -07002519
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002520 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002521 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2522 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002523
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002524 // could be null when this layer is using a layerStack
2525 // that is not visible on any display. Also can occur at
2526 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002527 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002528 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002529
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002530 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002531 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002532 if (hintDisplay) {
2533 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002534 }
Robert Carr2047fae2016-11-28 14:09:09 -08002535
2536 first = false;
2537 });
Mathias Agopian84300952012-11-21 16:02:13 -08002538 }
2539
2540
Mathias Agopian3559b072012-08-15 13:46:03 -07002541 /*
2542 * Perform our own transaction if needed
2543 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002544
2545 if (mLayersAdded) {
2546 mLayersAdded = false;
2547 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002548 mVisibleRegionsDirty = true;
2549 }
2550
2551 // some layers might have been removed, so
2552 // we need to update the regions they're exposing.
2553 if (mLayersRemoved) {
2554 mLayersRemoved = false;
2555 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002556 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002557 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002558 // this layer is not visible anymore
2559 // TODO: we could traverse the tree from front to back and
2560 // compute the actual visible region
2561 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002562 Region visibleReg;
2563 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002564 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002565 }
Robert Carr2047fae2016-11-28 14:09:09 -08002566 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002567 }
2568
2569 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002570
2571 updateCursorAsync();
2572}
2573
2574void SurfaceFlinger::updateCursorAsync()
2575{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002576 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002577 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002578 continue;
2579 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002580
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002581 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2582 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002583 }
2584 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002585}
2586
2587void SurfaceFlinger::commitTransaction()
2588{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002589 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002590 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002591 for (const auto& l : mLayersPendingRemoval) {
2592 recordBufferingStats(l->getName().string(),
2593 l->getOccupancyHistory(true));
2594 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002595 }
2596 mLayersPendingRemoval.clear();
2597 }
2598
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002599 // If this transaction is part of a window animation then the next frame
2600 // we composite should be considered an animation as well.
2601 mAnimCompositionPending = mAnimTransactionPending;
2602
Mathias Agopian4fec8732012-06-29 14:12:52 -07002603 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002604 // clear the "changed" flags in current state
2605 mCurrentState.colorMatrixChanged = false;
2606
Robert Carr1f0a16a2016-10-24 16:27:39 -07002607 mDrawingState.traverseInZOrder([](Layer* layer) {
2608 layer->commitChildList();
2609 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002610 mTransactionPending = false;
2611 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002612 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002613}
2614
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002615void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2616 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002617 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002618 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002619
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002620 Region aboveOpaqueLayers;
2621 Region aboveCoveredLayers;
2622 Region dirty;
2623
Mathias Agopian87baae12012-07-31 12:38:26 -07002624 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002625
Robert Carr2047fae2016-11-28 14:09:09 -08002626 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002627 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002628 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002629
Jesse Hall01e29052013-02-19 16:13:35 -08002630 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002631 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002632 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002633 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002634
Mathias Agopianab028732010-03-16 16:41:46 -07002635 /*
2636 * opaqueRegion: area of a surface that is fully opaque.
2637 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002638 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002639
2640 /*
2641 * visibleRegion: area of a surface that is visible on screen
2642 * and not fully transparent. This is essentially the layer's
2643 * footprint minus the opaque regions above it.
2644 * Areas covered by a translucent surface are considered visible.
2645 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002646 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002647
2648 /*
2649 * coveredRegion: area of a surface that is covered by all
2650 * visible regions above it (which includes the translucent areas).
2651 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002652 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002653
Jesse Halla8026d22012-09-25 13:25:04 -07002654 /*
2655 * transparentRegion: area of a surface that is hinted to be completely
2656 * transparent. This is only used to tell when the layer has no visible
2657 * non-transparent regions and can be removed from the layer list. It
2658 * does not affect the visibleRegion of this layer or any layers
2659 * beneath it. The hint may not be correct if apps don't respect the
2660 * SurfaceView restrictions (which, sadly, some don't).
2661 */
2662 Region transparentRegion;
2663
Mathias Agopianab028732010-03-16 16:41:46 -07002664
2665 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002666 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002667 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002668 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002669 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002670 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002671 if (!visibleRegion.isEmpty()) {
2672 // Remove the transparent area from the visible region
2673 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002674 if (tr.preserveRects()) {
2675 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002676 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002677 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002678 // transformation too complex, can't do the
2679 // transparent region optimization.
2680 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002681 }
Mathias Agopianab028732010-03-16 16:41:46 -07002682 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002683
Mathias Agopianab028732010-03-16 16:41:46 -07002684 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002685 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002686 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002687 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002688 // the opaque region is the layer's footprint
2689 opaqueRegion = visibleRegion;
2690 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002691 }
2692 }
2693
Robert Carre5f4f692018-01-12 13:12:28 -08002694 if (visibleRegion.isEmpty()) {
2695 layer->clearVisibilityRegions();
2696 return;
2697 }
2698
Mathias Agopianab028732010-03-16 16:41:46 -07002699 // Clip the covered region to the visible region
2700 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2701
2702 // Update aboveCoveredLayers for next (lower) layer
2703 aboveCoveredLayers.orSelf(visibleRegion);
2704
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002705 // subtract the opaque region covered by the layers above us
2706 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002707
2708 // compute this layer's dirty region
2709 if (layer->contentDirty) {
2710 // we need to invalidate the whole region
2711 dirty = visibleRegion;
2712 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002713 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002714 layer->contentDirty = false;
2715 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002716 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002717 * the exposed region consists of two components:
2718 * 1) what's VISIBLE now and was COVERED before
2719 * 2) what's EXPOSED now less what was EXPOSED before
2720 *
2721 * note that (1) is conservative, we start with the whole
2722 * visible region but only keep what used to be covered by
2723 * something -- which mean it may have been exposed.
2724 *
2725 * (2) handles areas that were not covered by anything but got
2726 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002727 */
Mathias Agopianab028732010-03-16 16:41:46 -07002728 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002729 const Region oldVisibleRegion = layer->visibleRegion;
2730 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002731 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2732 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002733 }
2734 dirty.subtractSelf(aboveOpaqueLayers);
2735
2736 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002737 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002738
Mathias Agopianab028732010-03-16 16:41:46 -07002739 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002740 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002741
Jesse Halla8026d22012-09-25 13:25:04 -07002742 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002743 layer->setVisibleRegion(visibleRegion);
2744 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002745 layer->setVisibleNonTransparentRegion(
2746 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002747 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002748
Mathias Agopian87baae12012-07-31 12:38:26 -07002749 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002750}
2751
Chia-I Wuab0c3192017-08-01 11:29:00 -07002752void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002753 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002754 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2755 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002756 }
2757 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002758}
2759
Dan Stoza6b9454d2014-11-07 16:00:59 -08002760bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002761{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002762 ALOGV("handlePageFlip");
2763
Brian Andersond6927fb2016-07-23 23:37:30 -07002764 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002765
Mathias Agopian4fec8732012-06-29 14:12:52 -07002766 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002767 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002768 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002769
2770 // Store the set of layers that need updates. This set must not change as
2771 // buffers are being latched, as this could result in a deadlock.
2772 // Example: Two producers share the same command stream and:
2773 // 1.) Layer 0 is latched
2774 // 2.) Layer 0 gets a new frame
2775 // 2.) Layer 1 gets a new frame
2776 // 3.) Layer 1 is latched.
2777 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2778 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002779 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002780 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002781 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07002782 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002783 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002784 } else {
2785 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002786 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002787 } else {
2788 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002789 }
Robert Carr2047fae2016-11-28 14:09:09 -08002790 });
2791
Dan Stoza9e56aa02015-11-02 13:00:03 -08002792 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002793 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002794 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002795 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002796 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002797 newDataLatched = true;
2798 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002799 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002800
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002801 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002802
2803 // If we will need to wake up at some time in the future to deal with a
2804 // queued frame that shouldn't be displayed during this vsync period, wake
2805 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002806 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002807 signalLayerUpdate();
2808 }
2809
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002810 // enter boot animation on first buffer latch
2811 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2812 ALOGI("Enter boot animation");
2813 mBootStage = BootStage::BOOTANIMATION;
2814 }
2815
Dan Stoza6b9454d2014-11-07 16:00:59 -08002816 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002817 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002818}
2819
Mathias Agopianad456f92011-01-13 17:53:01 -08002820void SurfaceFlinger::invalidateHwcGeometry()
2821{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002822 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002823}
2824
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002825void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2826 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002827 // We only need to actually compose the display if:
2828 // 1) It is being handled by hardware composer, which may need this to
2829 // keep its virtual display state machine in sync, or
2830 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002831 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002832 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002833 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002834 return;
2835 }
2836
Dan Stoza9e56aa02015-11-02 13:00:03 -08002837 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002838 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002839
2840 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002841 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002842}
2843
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002844bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002845 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002846
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002847 const Region bounds(display->bounds());
2848 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002849 const auto displayId = display->getId();
2850 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002851 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002852
Chia-I Wu8e50e692018-05-04 10:12:37 -07002853 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002854 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002855
Dan Stoza9e56aa02015-11-02 13:00:03 -08002856 if (hasClientComposition) {
2857 ALOGV("hasClientComposition");
2858
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002859 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002860 if (display->hasWideColorGamut()) {
2861 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002862 }
2863 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002864 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002865 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002866
Dominik Laskowski7e045462018-05-30 13:02:02 -07002867 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002868 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2869 HWC2::Capability::SkipClientColorTransform);
2870
Chia-I Wud49d6692018-06-27 07:17:41 +08002871 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002872 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2873 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08002874 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002875 }
2876
Chia-I Wud49d6692018-06-27 07:17:41 +08002877 // The current enhanced saturation matrix is designed to enhance Display P3,
2878 // thus we only apply this matrix when the render intent is not colorimetric
2879 // and the output color space is Display P3.
2880 needsEnhancedColorMatrix =
2881 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2882 outputDataspace == Dataspace::DISPLAY_P3);
2883 if (needsEnhancedColorMatrix) {
2884 colorMatrix *= mEnhancedSaturationMatrix;
2885 }
2886
2887 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002888
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002889 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002890 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002891 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002892 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002893
2894 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002895 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2896 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2897 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002898 }
2899 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002900 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002901
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002902 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002903 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002904 // when using overlays, we assume a fully transparent framebuffer
2905 // NOTE: we could reduce how much we need to clear, for instance
2906 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002907 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002908 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002909 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002910 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002911 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002912 // we're left with the letterbox region
2913 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002914 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07002915
2916 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002917 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07002918
Mathias Agopianb9494d52012-04-18 02:28:45 -07002919 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002920 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002921 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002922 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002923 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002924 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002925
Yiwei Zhange4e26c02018-08-22 13:59:12 -07002926 const Rect& bounds = display->getBounds();
2927 const Rect& scissor = display->getScissor();
2928 if (scissor != bounds) {
2929 // scissor doesn't match the screen's dimensions, so we
2930 // need to clear everything outside of it and enable
2931 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002932
Yiwei Zhange4e26c02018-08-22 13:59:12 -07002933 // enable scissor for this frame
2934 const uint32_t height = display->getHeight();
2935 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
2936 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002937 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002938 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002939
Mathias Agopian85d751c2012-08-29 16:59:24 -07002940 /*
2941 * and then, render the layers targeted at the framebuffer
2942 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002943
Dan Stoza9e56aa02015-11-02 13:00:03 -08002944 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07002945 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002946 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002947 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002948 const Region clip(bounds.intersect(
2949 displayTransform.transform(layer->visibleRegion)));
2950 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002951 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002952 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002953 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002954 case HWC2::Composition::Cursor:
2955 case HWC2::Composition::Device:
2956 case HWC2::Composition::Sideband:
2957 case HWC2::Composition::SolidColor: {
2958 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002959 if (layer->getClearClientTarget(displayId) && !firstLayer &&
Rajavenu Kyatham2eae6d32018-04-10 12:34:05 +05302960 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
2961 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002962 // never clear the very first layer since we're
2963 // guaranteed the FB is already cleared
2964 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002965 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002966 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002967 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002968 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002969 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002970 break;
2971 }
2972 default:
2973 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002974 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002975 } else {
2976 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002977 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002978 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002979 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002980
Chia-I Wud49d6692018-06-27 07:17:41 +08002981 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002982 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002983 }
2984
Mathias Agopianf45c5102012-10-24 16:29:17 -07002985 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002986 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002987 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002988}
2989
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002990void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
2991 const Region& region) const {
2992 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002993 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002994 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002995}
2996
Dan Stoza7d89d062015-04-30 13:29:25 -07002997status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002998 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002999 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003000 const sp<Layer>& lbc,
3001 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003002{
Dan Stoza7d89d062015-04-30 13:29:25 -07003003 // add this layer to the current state list
3004 {
3005 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003006 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003007 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3008 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003009 return NO_MEMORY;
3010 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003011 if (parent == nullptr) {
3012 mCurrentState.layersSortedByZ.add(lbc);
3013 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003014 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003015 ALOGE("addClientLayer called with a removed parent");
3016 return NAME_NOT_FOUND;
3017 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003018 parent->addChild(lbc);
3019 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003020
Yiwei Zhang243b3782018-05-15 17:40:04 -07003021 if (gbc != nullptr) {
3022 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3023 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3024 mMaxGraphicBufferProducerListSize,
3025 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3026 mGraphicBufferProducerList.size(),
3027 mMaxGraphicBufferProducerListSize, mNumLayers);
3028 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003029 mLayersAdded = true;
3030 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003031 }
3032
Mathias Agopian96f08192010-06-02 23:28:45 -07003033 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003034 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003035
Dan Stoza7d89d062015-04-30 13:29:25 -07003036 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003037}
3038
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003039status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003040 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003041 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3042}
Robert Carr7f9b8992017-03-10 11:08:39 -08003043
chaviwca27f252018-02-06 16:46:39 -08003044status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3045 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003046 if (layer->isPendingRemoval()) {
3047 return NO_ERROR;
3048 }
3049
Robert Carr1f0a16a2016-10-24 16:27:39 -07003050 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003051 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003052 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003053 if (topLevelOnly) {
3054 return NO_ERROR;
3055 }
3056
Chia-I Wu98f1c102017-05-30 14:54:08 -07003057 sp<Layer> ancestor = p;
3058 while (ancestor->getParent() != nullptr) {
3059 ancestor = ancestor->getParent();
3060 }
3061 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3062 ALOGE("removeLayer called with a layer whose parent has been removed");
3063 return NAME_NOT_FOUND;
3064 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003065
3066 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003067 } else {
3068 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003069 }
3070
Robert Carr136e2f62017-02-08 17:54:29 -08003071 // As a matter of normal operation, the LayerCleaner will produce a second
3072 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3073 // so we will succeed in promoting it, but it's already been removed
3074 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3075 // otherwise something has gone wrong and we are leaking the layer.
3076 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003077 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3078 layer->getName().string(),
3079 (p != nullptr) ? p->getName().string() : "no-parent");
3080 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003081 } else if (index < 0) {
3082 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003083 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003084
Chia-I Wuc6657022017-08-15 11:18:17 -07003085 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003086 mLayersPendingRemoval.add(layer);
3087 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003088 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003089 setTransactionFlags(eTransactionNeeded);
3090 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003091}
3092
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003093uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003094 return android_atomic_release_load(&mTransactionFlags);
3095}
3096
Mathias Agopian3f844832013-08-07 21:24:32 -07003097uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003098 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3099}
3100
Mathias Agopian3f844832013-08-07 21:24:32 -07003101uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003102 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3103}
3104
3105uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3106 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003107 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003108 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003109 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003110 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003111 }
3112 return old;
3113}
3114
chaviwca27f252018-02-06 16:46:39 -08003115bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3116 for (const ComposerState& state : states) {
3117 // Here we need to check that the interface we're given is indeed
3118 // one of our own. A malicious client could give us a nullptr
3119 // IInterface, or one of its own or even one of our own but a
3120 // different type. All these situations would cause us to crash.
3121 if (state.client == nullptr) {
3122 return true;
3123 }
3124
3125 sp<IBinder> binder = IInterface::asBinder(state.client);
3126 if (binder == nullptr) {
3127 return true;
3128 }
3129
3130 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3131 return true;
3132 }
3133 }
3134 return false;
3135}
3136
Mathias Agopian8b33f032012-07-24 20:43:54 -07003137void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003138 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003139 const Vector<DisplayState>& displays,
3140 uint32_t flags)
3141{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003142 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003143 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003144 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003145
chaviwca27f252018-02-06 16:46:39 -08003146 if (containsAnyInvalidClientState(states)) {
3147 return;
3148 }
3149
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003150 if (flags & eAnimation) {
3151 // For window updates that are part of an animation we must wait for
3152 // previous animation "frames" to be handled.
3153 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003154 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003155 if (CC_UNLIKELY(err != NO_ERROR)) {
3156 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003157 // caller after a few seconds.
3158 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3159 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003160 mAnimTransactionPending = false;
3161 break;
3162 }
3163 }
3164 }
3165
chaviwca27f252018-02-06 16:46:39 -08003166 for (const DisplayState& display : displays) {
3167 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003168 }
3169
chaviwca27f252018-02-06 16:46:39 -08003170 for (const ComposerState& state : states) {
3171 transactionFlags |= setClientStateLocked(state);
3172 }
3173
3174 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3175 // as destroyed should only occur after setting all other states. This is to allow for a
3176 // child re-parent to happen before marking its original parent as destroyed (which would
3177 // then mark the child as destroyed).
3178 for (const ComposerState& state : states) {
3179 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003180 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003181
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003182 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3183 // anyway. This can be used as a flush mechanism for previous async transactions.
3184 // Empty animation transaction can be used to simulate back-pressure, so also force a
3185 // transaction for empty animation transactions.
3186 if (transactionFlags == 0 &&
3187 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003188 transactionFlags = eTransactionNeeded;
3189 }
3190
Mathias Agopian386aa982011-11-07 21:58:03 -08003191 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003192 if (mInterceptor->isEnabled()) {
3193 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003194 }
Irvel468051e2016-06-13 16:44:44 -07003195
Mathias Agopian386aa982011-11-07 21:58:03 -08003196 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003197 const auto start = (flags & eEarlyWakeup)
3198 ? VSyncModulator::TransactionStart::EARLY
3199 : VSyncModulator::TransactionStart::NORMAL;
3200 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003201
3202 // if this is a synchronous transaction, wait for it to take effect
3203 // before returning.
3204 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003205 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003206 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003207 if (flags & eAnimation) {
3208 mAnimTransactionPending = true;
3209 }
3210 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003211 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3212 if (CC_UNLIKELY(err != NO_ERROR)) {
3213 // just in case something goes wrong in SF, return to the
3214 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003215 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3216 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003217 break;
3218 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003219 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003220 }
3221}
3222
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003223uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3224 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3225 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003226
Mathias Agopiane57f2922012-08-09 16:29:12 -07003227 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003228 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3229
3230 const uint32_t what = s.what;
3231 if (what & DisplayState::eSurfaceChanged) {
3232 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3233 state.surface = s.surface;
3234 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003235 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003236 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003237 if (what & DisplayState::eLayerStackChanged) {
3238 if (state.layerStack != s.layerStack) {
3239 state.layerStack = s.layerStack;
3240 flags |= eDisplayTransactionNeeded;
3241 }
3242 }
3243 if (what & DisplayState::eDisplayProjectionChanged) {
3244 if (state.orientation != s.orientation) {
3245 state.orientation = s.orientation;
3246 flags |= eDisplayTransactionNeeded;
3247 }
3248 if (state.frame != s.frame) {
3249 state.frame = s.frame;
3250 flags |= eDisplayTransactionNeeded;
3251 }
3252 if (state.viewport != s.viewport) {
3253 state.viewport = s.viewport;
3254 flags |= eDisplayTransactionNeeded;
3255 }
3256 }
3257 if (what & DisplayState::eDisplaySizeChanged) {
3258 if (state.width != s.width) {
3259 state.width = s.width;
3260 flags |= eDisplayTransactionNeeded;
3261 }
3262 if (state.height != s.height) {
3263 state.height = s.height;
3264 flags |= eDisplayTransactionNeeded;
3265 }
3266 }
3267
Mathias Agopiane57f2922012-08-09 16:29:12 -07003268 return flags;
3269}
3270
Robert Carrd4ae7f32018-06-07 16:10:57 -07003271bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3272 IPCThreadState* ipc = IPCThreadState::self();
3273 const int pid = ipc->getCallingPid();
3274 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003275 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003276 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003277 return false;
3278 }
3279 return true;
3280}
3281
chaviwca27f252018-02-06 16:46:39 -08003282uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3283 const layer_state_t& s = composerState.state;
3284 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3285
Mathias Agopian13127d82013-03-05 17:47:11 -08003286 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003287 if (layer == nullptr) {
3288 return 0;
3289 }
3290
3291 if (layer->isPendingRemoval()) {
3292 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3293 return 0;
3294 }
3295
3296 uint32_t flags = 0;
3297
3298 const uint32_t what = s.what;
3299 bool geometryAppliesWithResize =
3300 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003301
3302 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3303 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003304 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003305 layer->pushPendingState();
3306 }
3307
chaviw8b3871a2017-11-01 17:41:01 -07003308 if (what & layer_state_t::ePositionChanged) {
3309 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3310 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003311 }
chaviw8b3871a2017-11-01 17:41:01 -07003312 }
3313 if (what & layer_state_t::eLayerChanged) {
3314 // NOTE: index needs to be calculated before we update the state
3315 const auto& p = layer->getParent();
3316 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003317 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003318 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003319 mCurrentState.layersSortedByZ.removeAt(idx);
3320 mCurrentState.layersSortedByZ.add(layer);
3321 // we need traversal (state changed)
3322 // AND transaction (list changed)
3323 flags |= eTransactionNeeded|eTraversalNeeded;
3324 }
chaviw8b3871a2017-11-01 17:41:01 -07003325 } else {
3326 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003327 flags |= eTransactionNeeded|eTraversalNeeded;
3328 }
3329 }
chaviw8b3871a2017-11-01 17:41:01 -07003330 }
3331 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003332 // NOTE: index needs to be calculated before we update the state
3333 const auto& p = layer->getParent();
3334 if (p == nullptr) {
3335 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3336 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3337 mCurrentState.layersSortedByZ.removeAt(idx);
3338 mCurrentState.layersSortedByZ.add(layer);
3339 // we need traversal (state changed)
3340 // AND transaction (list changed)
3341 flags |= eTransactionNeeded|eTraversalNeeded;
3342 }
3343 } else {
3344 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3345 flags |= eTransactionNeeded|eTraversalNeeded;
3346 }
chaviw8b3871a2017-11-01 17:41:01 -07003347 }
3348 }
3349 if (what & layer_state_t::eSizeChanged) {
3350 if (layer->setSize(s.w, s.h)) {
3351 flags |= eTraversalNeeded;
3352 }
3353 }
3354 if (what & layer_state_t::eAlphaChanged) {
3355 if (layer->setAlpha(s.alpha))
3356 flags |= eTraversalNeeded;
3357 }
3358 if (what & layer_state_t::eColorChanged) {
3359 if (layer->setColor(s.color))
3360 flags |= eTraversalNeeded;
3361 }
3362 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003363 // TODO: b/109894387
3364 //
3365 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3366 // rotation. To see the problem observe that if we have a square parent, and a child
3367 // of the same size, then we rotate the child 45 degrees around it's center, the child
3368 // must now be cropped to a non rectangular 8 sided region.
3369 //
3370 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3371 // private API, and the WindowManager only uses rotation in one case, which is on a top
3372 // level layer in which cropping is not an issue.
3373 //
3374 // However given that abuse of rotation matrices could lead to surfaces extending outside
3375 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3376 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3377 // transformations.
3378 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003379 flags |= eTraversalNeeded;
3380 }
3381 if (what & layer_state_t::eTransparentRegionChanged) {
3382 if (layer->setTransparentRegionHint(s.transparentRegion))
3383 flags |= eTraversalNeeded;
3384 }
3385 if (what & layer_state_t::eFlagsChanged) {
3386 if (layer->setFlags(s.flags, s.mask))
3387 flags |= eTraversalNeeded;
3388 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003389 if (what & layer_state_t::eCropChanged_legacy) {
3390 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003391 flags |= eTraversalNeeded;
3392 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003393 if (what & layer_state_t::eFinalCropChanged_legacy) {
3394 if (layer->setFinalCrop_legacy(s.finalCrop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003395 flags |= eTraversalNeeded;
3396 }
3397 if (what & layer_state_t::eLayerStackChanged) {
3398 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3399 // We only allow setting layer stacks for top level layers,
3400 // everything else inherits layer stack from its parent.
3401 if (layer->hasParent()) {
3402 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3403 layer->getName().string());
3404 } else if (idx < 0) {
3405 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3406 "that also does not appear in the top level layer list. Something"
3407 " has gone wrong.", layer->getName().string());
3408 } else if (layer->setLayerStack(s.layerStack)) {
3409 mCurrentState.layersSortedByZ.removeAt(idx);
3410 mCurrentState.layersSortedByZ.add(layer);
3411 // we need traversal (state changed)
3412 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003413 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003414 }
3415 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003416 if (what & layer_state_t::eDeferTransaction_legacy) {
3417 if (s.barrierHandle_legacy != nullptr) {
3418 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3419 } else if (s.barrierGbp_legacy != nullptr) {
3420 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003421 if (authenticateSurfaceTextureLocked(gbp)) {
3422 const auto& otherLayer =
3423 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003424 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003425 } else {
3426 ALOGE("Attempt to defer transaction to to an"
3427 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003428 }
3429 }
chaviw8b3871a2017-11-01 17:41:01 -07003430 // We don't trigger a traversal here because if no other state is
3431 // changed, we don't want this to cause any more work
3432 }
3433 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003434 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003435 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003436 if (!hadParent) {
3437 mCurrentState.layersSortedByZ.remove(layer);
3438 }
chaviw8b3871a2017-11-01 17:41:01 -07003439 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003440 }
chaviw8b3871a2017-11-01 17:41:01 -07003441 }
3442 if (what & layer_state_t::eReparentChildren) {
3443 if (layer->reparentChildren(s.reparentHandle)) {
3444 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003445 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003446 }
chaviw8b3871a2017-11-01 17:41:01 -07003447 if (what & layer_state_t::eDetachChildren) {
3448 layer->detachChildren();
3449 }
3450 if (what & layer_state_t::eOverrideScalingModeChanged) {
3451 layer->setOverrideScalingMode(s.overrideScalingMode);
3452 // We don't trigger a traversal here because if no other state is
3453 // changed, we don't want this to cause any more work
3454 }
Marissa Wall61c58622018-07-18 10:12:20 -07003455 if (what & layer_state_t::eTransformChanged) {
3456 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3457 }
3458 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3459 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3460 flags |= eTraversalNeeded;
3461 }
3462 if (what & layer_state_t::eCropChanged) {
3463 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3464 }
3465 if (what & layer_state_t::eBufferChanged) {
3466 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3467 }
3468 if (what & layer_state_t::eAcquireFenceChanged) {
3469 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3470 }
3471 if (what & layer_state_t::eDataspaceChanged) {
3472 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3473 }
3474 if (what & layer_state_t::eHdrMetadataChanged) {
3475 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3476 }
3477 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3478 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3479 }
3480 if (what & layer_state_t::eApiChanged) {
3481 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3482 }
3483 if (what & layer_state_t::eSidebandStreamChanged) {
3484 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3485 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003486 return flags;
3487}
3488
chaviwca27f252018-02-06 16:46:39 -08003489void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3490 const layer_state_t& state = composerState.state;
3491 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3492
3493 sp<Layer> layer(client->getLayerUser(state.surface));
3494 if (layer == nullptr) {
3495 return;
3496 }
3497
3498 if (layer->isPendingRemoval()) {
3499 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3500 return;
3501 }
3502
3503 if (state.what & layer_state_t::eDestroySurface) {
3504 removeLayerLocked(mStateLock, layer);
3505 }
3506}
3507
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003508status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003509 const String8& name,
3510 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003511 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003512 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003513 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003514{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003515 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003516 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003517 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003518 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003519 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003520
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003521 status_t result = NO_ERROR;
3522
3523 sp<Layer> layer;
3524
Cody Northropbc755282017-03-31 12:00:08 -06003525 String8 uniqueName = getUniqueLayerName(name);
3526
Mathias Agopian3165cc22012-08-08 19:42:09 -07003527 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003528 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003529 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3530 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003531
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003532 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003533 case ISurfaceComposerClient::eFXSurfaceBufferState:
3534 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3535 break;
chaviw13fdc492017-06-27 12:40:18 -07003536 case ISurfaceComposerClient::eFXSurfaceColor:
3537 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003538 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003539 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003540 break;
3541 default:
3542 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003543 break;
3544 }
3545
Dan Stoza7d89d062015-04-30 13:29:25 -07003546 if (result != NO_ERROR) {
3547 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003548 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003549
Chia-I Wuab0c3192017-08-01 11:29:00 -07003550 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3551 // TODO b/64227542
3552 if (windowType == 441731) {
3553 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3554 layer->setPrimaryDisplayOnly();
3555 }
3556
Albert Chaulk479c60c2017-01-27 14:21:34 -05003557 layer->setInfo(windowType, ownerUid);
3558
Robert Carr1f0a16a2016-10-24 16:27:39 -07003559 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003560 if (result != NO_ERROR) {
3561 return result;
3562 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003563 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003564
3565 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003566 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003567}
3568
Cody Northropbc755282017-03-31 12:00:08 -06003569String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3570{
3571 bool matchFound = true;
3572 uint32_t dupeCounter = 0;
3573
3574 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3575 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3576
Dan Stoza436ccf32018-06-21 12:10:12 -07003577 // Grab the state lock since we're accessing mCurrentState
3578 Mutex::Autolock lock(mStateLock);
3579
Cody Northropbc755282017-03-31 12:00:08 -06003580 // Loop over layers until we're sure there is no matching name
3581 while (matchFound) {
3582 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003583 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003584 if (layer->getName() == uniqueName) {
3585 matchFound = true;
3586 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3587 }
3588 });
3589 }
3590
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003591 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3592 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003593
3594 return uniqueName;
3595}
3596
Marissa Wallfd668622018-05-10 10:21:13 -07003597status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3598 uint32_t w, uint32_t h, uint32_t flags,
3599 PixelFormat& format, sp<IBinder>* handle,
3600 sp<IGraphicBufferProducer>* gbp,
3601 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003602 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003603 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003604 case PIXEL_FORMAT_TRANSPARENT:
3605 case PIXEL_FORMAT_TRANSLUCENT:
3606 format = PIXEL_FORMAT_RGBA_8888;
3607 break;
3608 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003609 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003610 break;
3611 }
3612
Marissa Wallfd668622018-05-10 10:21:13 -07003613 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3614 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003615 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003616 *handle = layer->getHandle();
3617 *gbp = layer->getProducer();
3618 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003619 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003620
Marissa Wallfd668622018-05-10 10:21:13 -07003621 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003622 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003623}
3624
Marissa Wall61c58622018-07-18 10:12:20 -07003625status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3626 uint32_t w, uint32_t h, uint32_t flags,
3627 sp<IBinder>* handle, sp<Layer>* outLayer) {
3628 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3629 *handle = layer->getHandle();
3630 *outLayer = layer;
3631
3632 return NO_ERROR;
3633}
3634
chaviw13fdc492017-06-27 12:40:18 -07003635status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003636 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003637 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003638{
chaviw13fdc492017-06-27 12:40:18 -07003639 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003640 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003641 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003642}
3643
Mathias Agopianac9fa422013-02-11 16:40:36 -08003644status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003645{
Robert Carr9524cb32017-02-13 11:32:32 -08003646 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003647 status_t err = NO_ERROR;
3648 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003649 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003650 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003651 err = removeLayer(l);
3652 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3653 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003654 }
3655 return err;
3656}
3657
Mathias Agopian13127d82013-03-05 17:47:11 -08003658status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003659{
Mathias Agopian67106042013-03-14 19:18:13 -07003660 // called by ~LayerCleaner() when all references to the IBinder (handle)
3661 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003662 sp<Layer> l = layer.promote();
3663 if (l == nullptr) {
3664 // The layer has already been removed, carry on
3665 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003666 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003667 // If we have a parent, then we can continue to live as long as it does.
3668 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003669}
3670
Mathias Agopianb60314a2012-04-10 22:09:54 -07003671// ---------------------------------------------------------------------------
3672
Andy McFadden13a082e2012-08-24 10:16:42 -07003673void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003674 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3675 if (!displayToken) return;
3676
Jesse Hall01e29052013-02-19 16:13:35 -08003677 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003678 Vector<ComposerState> state;
3679 Vector<DisplayState> displays;
3680 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003681 d.what = DisplayState::eDisplayProjectionChanged |
3682 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003683 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003684 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003685 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003686 d.frame.makeInvalid();
3687 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003688 d.width = 0;
3689 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003690 displays.add(d);
3691 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003692
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003693 const auto display = getDisplayDevice(displayToken);
3694 if (!display) return;
3695
3696 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3697
3698 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003699 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003700 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003701
Brian Andersond0010582017-03-07 13:20:31 -08003702 // Use phase of 0 since phase is not known.
3703 // Use latency of 0, which will snap to the ideal latency.
3704 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003705}
3706
3707void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003708 // Async since we may be called from the main thread.
3709 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003710}
3711
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003712void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3713 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003714 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003715 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003716
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003717 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003718 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003719 return;
3720 }
3721
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003722 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003723 ALOGW("Trying to set power mode for virtual display");
3724 return;
3725 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003726
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003727 display->setPowerMode(mode);
3728
Lloyd Pique4dccc412018-01-22 17:21:36 -08003729 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003730 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003731 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003732 if (idx < 0) {
3733 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3734 return;
3735 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003736 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003737 }
3738
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003739 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003740 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003741 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003742 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003743 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003744 // FIXME: eventthread only knows about the main display right now
3745 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003746 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003747 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003748
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003749 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003750 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003751 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003752
3753 struct sched_param param = {0};
3754 param.sched_priority = 1;
3755 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3756 ALOGW("Couldn't set SCHED_FIFO on display on");
3757 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003758 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003759 // Turn off the display
3760 struct sched_param param = {0};
3761 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3762 ALOGW("Couldn't set SCHED_OTHER on display off");
3763 }
3764
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003765 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003766 disableHardwareVsync(true); // also cancels any in-progress resync
3767
Mathias Agopiancde87a32012-09-13 14:09:01 -07003768 // FIXME: eventthread only knows about the main display right now
3769 mEventThread->onScreenReleased();
3770 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003771
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003772 getHwComposer().setPowerMode(type, mode);
3773 mVisibleRegionsDirty = true;
3774 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003775 } else if (mode == HWC_POWER_MODE_DOZE ||
3776 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003777 // Update display while dozing
3778 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003779 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003780 // FIXME: eventthread only knows about the main display right now
3781 mEventThread->onScreenAcquired();
3782 resyncToHardwareVsync(true);
3783 }
3784 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3785 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003786 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003787 disableHardwareVsync(true); // also cancels any in-progress resync
3788 // FIXME: eventthread only knows about the main display right now
3789 mEventThread->onScreenReleased();
3790 }
3791 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003792 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003793 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003794 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003795 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003796
3797 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003798}
3799
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003800void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003801 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003802 const auto display = getDisplayDevice(displayToken);
3803 if (!display) {
3804 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3805 displayToken.get());
3806 } else if (display->isVirtual()) {
3807 ALOGW("Attempt to set power mode %d for virtual display", mode);
3808 } else {
3809 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003810 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003811 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003812}
3813
3814// ---------------------------------------------------------------------------
3815
Lloyd Pique755e3192018-01-31 16:46:15 -08003816status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3817 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003818 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003819
Mathias Agopianbd115332013-04-18 16:41:04 -07003820 IPCThreadState* ipc = IPCThreadState::self();
3821 const int pid = ipc->getCallingPid();
3822 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003823
Mathias Agopianbd115332013-04-18 16:41:04 -07003824 if ((uid != AID_SHELL) &&
3825 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003826 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003827 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003828 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003829 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003830 // (this would indicate SF is stuck, but we want to be able to
3831 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003832 status_t err = mStateLock.timedLock(s2ns(1));
3833 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003834 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003835 result.appendFormat(
3836 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3837 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003838 }
3839
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003840 bool dumpAll = true;
3841 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003842 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003843
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003844 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003845 if ((index < numArgs) &&
3846 (args[index] == String16("--list"))) {
3847 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003848 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003849 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003850 }
3851
3852 if ((index < numArgs) &&
3853 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003854 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003855 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003856 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003857 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003858
3859 if ((index < numArgs) &&
3860 (args[index] == String16("--latency-clear"))) {
3861 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003862 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003863 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003864 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003865
3866 if ((index < numArgs) &&
3867 (args[index] == String16("--dispsync"))) {
3868 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07003869 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07003870 dumpAll = false;
3871 }
Dan Stozab90cf072015-03-05 11:05:59 -08003872
3873 if ((index < numArgs) &&
3874 (args[index] == String16("--static-screen"))) {
3875 index++;
3876 dumpStaticScreenStats(result);
3877 dumpAll = false;
3878 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003879
3880 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003881 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003882 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003883 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003884 dumpAll = false;
3885 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003886
3887 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3888 index++;
3889 dumpWideColorInfo(result);
3890 dumpAll = false;
3891 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003892
3893 if ((index < numArgs) &&
3894 (args[index] == String16("--enable-layer-stats"))) {
3895 index++;
3896 mLayerStats.enable();
3897 dumpAll = false;
3898 }
3899
3900 if ((index < numArgs) &&
3901 (args[index] == String16("--disable-layer-stats"))) {
3902 index++;
3903 mLayerStats.disable();
3904 dumpAll = false;
3905 }
3906
3907 if ((index < numArgs) &&
3908 (args[index] == String16("--clear-layer-stats"))) {
3909 index++;
3910 mLayerStats.clear();
3911 dumpAll = false;
3912 }
3913
3914 if ((index < numArgs) &&
3915 (args[index] == String16("--dump-layer-stats"))) {
3916 index++;
3917 mLayerStats.dump(result);
3918 dumpAll = false;
3919 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003920
3921 if ((index < numArgs) &&
3922 (args[index] == String16("--display-identification"))) {
3923 index++;
3924 dumpDisplayIdentificationData(result);
3925 dumpAll = false;
3926 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003927
3928 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3929 index++;
3930 mTimeStats.parseArgs(asProto, args, index, result);
3931 dumpAll = false;
3932 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003933 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003934
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003935 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003936 if (asProto) {
3937 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3938 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3939 } else {
3940 dumpAllLocked(args, index, result);
3941 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003942 }
3943
Mathias Agopian9795c422009-08-26 16:36:26 -07003944 if (locked) {
3945 mStateLock.unlock();
3946 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003947 }
3948 write(fd, result.string(), result.size());
3949 return NO_ERROR;
3950}
3951
Dan Stozac7014012014-02-14 15:03:43 -08003952void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3953 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003954{
Robert Carr2047fae2016-11-28 14:09:09 -08003955 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003956 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003957 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003958}
3959
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003960void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003961 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003962{
3963 String8 name;
3964 if (index < args.size()) {
3965 name = String8(args[index]);
3966 index++;
3967 }
3968
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003969 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
3970 getHwComposer().isConnected(displayId)) {
3971 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
3972 const nsecs_t period = activeConfig->getVsyncPeriod();
3973 result.appendFormat("%" PRId64 "\n", period);
3974 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003975
3976 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003977 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003978 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003979 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003980 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003981 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003982 }
Robert Carr2047fae2016-11-28 14:09:09 -08003983 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003984 }
3985}
3986
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003987void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003988 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003989{
3990 String8 name;
3991 if (index < args.size()) {
3992 name = String8(args[index]);
3993 index++;
3994 }
3995
Robert Carr2047fae2016-11-28 14:09:09 -08003996 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003997 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003998 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003999 }
Robert Carr2047fae2016-11-28 14:09:09 -08004000 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004001
Svetoslavd85084b2014-03-20 10:28:31 -07004002 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004003}
4004
Jamie Gennis6547ff42013-07-16 20:12:42 -07004005// This should only be called from the main thread. Otherwise it would need
4006// the lock and should use mCurrentState rather than mDrawingState.
4007void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004008 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004009 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004010 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004011
4012 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4013}
4014
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004015void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004016{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004017 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004018
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004019 if (isLayerTripleBufferingDisabled())
4020 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004021
4022 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004023 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004024 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004025 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004026 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4027 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004028 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004029}
4030
Dan Stozab90cf072015-03-05 11:05:59 -08004031void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4032{
4033 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004034 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4035 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004036 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004037 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004038 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4039 b + 1, bucketTimeSec, percent);
4040 }
David Sodman4a36e932017-11-07 14:29:47 -08004041 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004042 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004043 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004044 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004045 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004046}
4047
Dan Stozae77c7662016-05-13 11:37:28 -07004048void SurfaceFlinger::recordBufferingStats(const char* layerName,
4049 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004050 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4051 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004052 for (const auto& segment : history) {
4053 if (!segment.usedThirdBuffer) {
4054 stats.twoBufferTime += segment.totalTime;
4055 }
4056 if (segment.occupancyAverage < 1.0f) {
4057 stats.doubleBufferedTime += segment.totalTime;
4058 } else if (segment.occupancyAverage < 2.0f) {
4059 stats.tripleBufferedTime += segment.totalTime;
4060 }
4061 ++stats.numSegments;
4062 stats.totalTime += segment.totalTime;
4063 }
4064}
4065
Brian Andersond6927fb2016-07-23 23:37:30 -07004066void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4067 result.appendFormat("Layer frame timestamps:\n");
4068
4069 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4070 const size_t count = currentLayers.size();
4071 for (size_t i=0 ; i<count ; i++) {
4072 currentLayers[i]->dumpFrameEvents(result);
4073 }
4074}
4075
Dan Stozae77c7662016-05-13 11:37:28 -07004076void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4077 result.append("Buffering stats:\n");
4078 result.append(" [Layer name] <Active time> <Two buffer> "
4079 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004080 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004081 typedef std::tuple<std::string, float, float, float> BufferTuple;
4082 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004083 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004084 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004085 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004086 if (stats.numSegments == 0) {
4087 continue;
4088 }
4089 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4090 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4091 stats.totalTime;
4092 float doubleBufferRatio = static_cast<float>(
4093 stats.doubleBufferedTime) / stats.totalTime;
4094 float tripleBufferRatio = static_cast<float>(
4095 stats.tripleBufferedTime) / stats.totalTime;
4096 sorted.insert({activeTime, {name, twoBufferRatio,
4097 doubleBufferRatio, tripleBufferRatio}});
4098 }
4099 for (const auto& sortedPair : sorted) {
4100 float activeTime = sortedPair.first;
4101 const BufferTuple& values = sortedPair.second;
4102 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4103 std::get<0>(values).c_str(), activeTime,
4104 std::get<1>(values), std::get<2>(values),
4105 std::get<3>(values));
4106 }
4107 result.append("\n");
4108}
4109
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004110void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004111 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004112 const int32_t displayId = display->getId();
4113 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4114 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004115 continue;
4116 }
4117
Dominik Laskowski7e045462018-05-30 13:02:02 -07004118 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004119 uint8_t port;
4120 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004121 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004122 result.append("no identification data\n");
4123 continue;
4124 }
4125
4126 if (!isEdid(data)) {
4127 result.append("unknown identification data: ");
4128 for (uint8_t byte : data) {
4129 result.appendFormat("%x ", byte);
4130 }
4131 result.append("\n");
4132 continue;
4133 }
4134
4135 const auto edid = parseEdid(data);
4136 if (!edid) {
4137 result.append("invalid EDID: ");
4138 for (uint8_t byte : data) {
4139 result.appendFormat("%x ", byte);
4140 }
4141 result.append("\n");
4142 continue;
4143 }
4144
4145 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4146 result.append(edid->displayName.data(), edid->displayName.length());
4147 result.append("\"\n");
4148 }
4149 result.append("\n");
4150}
4151
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004152void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004153 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4154 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004155 result.appendFormat("DisplayColorSetting: %s\n",
4156 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004157
4158 // TODO: print out if wide-color mode is active or not
4159
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004160 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004161 const int32_t displayId = display->getId();
4162 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004163 continue;
4164 }
4165
Dominik Laskowski7e045462018-05-30 13:02:02 -07004166 result.appendFormat("Display %d color modes:\n", displayId);
4167 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004168 for (auto&& mode : modes) {
4169 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4170 }
4171
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004172 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004173 result.appendFormat(" Current color mode: %s (%d)\n",
4174 decodeColorMode(currentMode).c_str(), currentMode);
4175 }
4176 result.append("\n");
4177}
4178
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004179LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004180 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004181 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4182 const State& state = useDrawing ? mDrawingState : mCurrentState;
4183 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004184 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004185 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004186 });
4187
4188 return layersProto;
4189}
4190
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004191LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004192 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004193
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004194 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004195 resolution->set_w(display.getWidth());
4196 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004197
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004198 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4199 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4200 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004201
Dominik Laskowski7e045462018-05-30 13:02:02 -07004202 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004203 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004204 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004205 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004206 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004207 }
4208 });
4209
4210 return layersProto;
4211}
4212
Mathias Agopian74d211a2013-04-22 16:55:35 +02004213void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4214 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004215{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004216 bool colorize = false;
4217 if (index < args.size()
4218 && (args[index] == String16("--color"))) {
4219 colorize = true;
4220 index++;
4221 }
4222
4223 Colorizer colorizer(colorize);
4224
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004225 // figure out if we're stuck somewhere
4226 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004227 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004228 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4229
4230 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004231 * Dump library configuration.
4232 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004233
4234 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004235 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004236 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004237 appendSfConfigString(result);
4238 appendUiConfigString(result);
4239 appendGuiConfigString(result);
4240 result.append("\n");
4241
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004242 result.append("\nDisplay identification data:\n");
4243 dumpDisplayIdentificationData(result);
4244
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004245 result.append("\nWide-Color information:\n");
4246 dumpWideColorInfo(result);
4247
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004248 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004249 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004250 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004251 result.append(SyncFeatures::getInstance().toString());
4252 result.append("\n");
4253
Andy McFadden41d67d72014-04-25 16:58:34 -07004254 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004255 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004256 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004257
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004258 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4259 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004260 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4261 getHwComposer().isConnected(displayId)) {
4262 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004263 result.appendFormat("Display %d: "
4264 "app phase %" PRId64 " ns, "
4265 "sf phase %" PRId64 " ns, "
4266 "early app phase %" PRId64 " ns, "
4267 "early sf phase %" PRId64 " ns, "
4268 "early app gl phase %" PRId64 " ns, "
4269 "early sf gl phase %" PRId64 " ns, "
4270 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4271 displayId,
4272 vsyncPhaseOffsetNs,
4273 sfVsyncPhaseOffsetNs,
4274 appEarlyOffset,
4275 sfEarlyOffset,
4276 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004277 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004278 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004279 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004280 result.append("\n");
4281
Dan Stozab90cf072015-03-05 11:05:59 -08004282 // Dump static screen stats
4283 result.append("\n");
4284 dumpStaticScreenStats(result);
4285 result.append("\n");
4286
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004287 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4288
Dan Stozae77c7662016-05-13 11:37:28 -07004289 dumpBufferingStats(result);
4290
Andy McFadden4803b742012-09-24 19:07:20 -07004291 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004292 * Dump the visible layer list
4293 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004294 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004295 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004296 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4297 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004298 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004299
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004300 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004301 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004302 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004303 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004304
4305 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004306 * Dump Display state
4307 */
4308
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004309 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004310 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004311 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004312 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004313 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004314 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004315 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004316
4317 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004318 * Dump SurfaceFlinger global state
4319 */
4320
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004321 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004322 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004323 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004324
Mathias Agopian888c8222012-08-04 21:10:38 -07004325 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004326 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004327
David Sodmanbc815282017-11-05 18:57:52 -08004328 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004329
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004330 if (display) {
4331 display->undefinedRegion.dump(result, "undefinedRegion");
4332 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4333 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004334 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004335 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004336 " gpu_to_cpu_unsupported : %d\n",
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004337 mTransactionFlags, !mGpuToCpuSupported);
4338
4339 if (display) {
4340 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4341 result.appendFormat(" refresh-rate : %f fps\n"
4342 " x-dpi : %f\n"
4343 " y-dpi : %f\n",
4344 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4345 activeConfig->getDpiY());
4346 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004347
Mathias Agopian74d211a2013-04-22 16:55:35 +02004348 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004349 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004350
4351 /*
4352 * VSYNC state
4353 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004354 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004355 result.append("\n");
4356
4357 /*
4358 * HWC layer minidump
4359 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004360 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004361 const int32_t displayId = display->getId();
4362 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004363 continue;
4364 }
4365
Dominik Laskowski7e045462018-05-30 13:02:02 -07004366 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004367 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004368 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004369 result.append("\n");
4370 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004371
4372 /*
4373 * Dump HWComposer state
4374 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004375 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004376 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004377 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004378 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004379 result.appendFormat(" h/w composer %s\n",
4380 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004381 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004382
4383 /*
4384 * Dump gralloc state
4385 */
4386 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4387 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004388
4389 /*
4390 * Dump VrFlinger state if in use.
4391 */
4392 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4393 result.append("VrFlinger state:\n");
4394 result.append(mVrFlinger->Dump().c_str());
4395 result.append("\n");
4396 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004397}
4398
Dominik Laskowski7e045462018-05-30 13:02:02 -07004399const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004400 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004401 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004402 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004403 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004404 }
4405 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004406
4407 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4408 static const Vector<sp<Layer>> empty;
4409 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004410}
4411
Keun young Park63f165f2012-08-31 10:53:36 -07004412bool SurfaceFlinger::startDdmConnection()
4413{
4414 void* libddmconnection_dso =
4415 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4416 if (!libddmconnection_dso) {
4417 return false;
4418 }
4419 void (*DdmConnection_start)(const char* name);
4420 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004421 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004422 if (!DdmConnection_start) {
4423 dlclose(libddmconnection_dso);
4424 return false;
4425 }
4426 (*DdmConnection_start)(getServiceName());
4427 return true;
4428}
4429
Chia-I Wu28f320b2018-05-03 11:02:56 -07004430void SurfaceFlinger::updateColorMatrixLocked() {
4431 mat4 colorMatrix;
4432 if (mGlobalSaturationFactor != 1.0f) {
4433 // Rec.709 luma coefficients
4434 float3 luminance{0.213f, 0.715f, 0.072f};
4435 luminance *= 1.0f - mGlobalSaturationFactor;
4436 mat4 saturationMatrix = mat4(
4437 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4438 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4439 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4440 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4441 );
4442 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4443 } else {
4444 colorMatrix = mClientColorMatrix * mDaltonizer();
4445 }
4446
4447 if (mCurrentState.colorMatrix != colorMatrix) {
4448 mCurrentState.colorMatrix = colorMatrix;
4449 mCurrentState.colorMatrixChanged = true;
4450 setTransactionFlags(eTransactionNeeded);
4451 }
4452}
4453
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004454status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004455#pragma clang diagnostic push
4456#pragma clang diagnostic error "-Wswitch-enum"
4457 switch (static_cast<ISurfaceComposerTag>(code)) {
4458 // These methods should at minimum make sure that the client requested
4459 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004460 case BOOT_FINISHED:
4461 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004462 case CREATE_CONNECTION:
4463 case CREATE_DISPLAY:
4464 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004465 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004466 case GET_ACTIVE_COLOR_MODE:
4467 case GET_ANIMATION_FRAME_STATS:
4468 case GET_HDR_CAPABILITIES:
4469 case SET_ACTIVE_CONFIG:
4470 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004471 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004472 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004473 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4474 IPCThreadState* ipc = IPCThreadState::self();
4475 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4476 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004477 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004478 }
Robert Carr1db73f62016-12-21 12:58:51 -08004479 return OK;
4480 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004481 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004482 IPCThreadState* ipc = IPCThreadState::self();
4483 const int pid = ipc->getCallingPid();
4484 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004485 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4486 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004487 return PERMISSION_DENIED;
4488 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004489 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004490 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004491 // Used by apps to hook Choreographer to SurfaceFlinger.
4492 case CREATE_DISPLAY_EVENT_CONNECTION:
4493 // The following calls are currently used by clients that do not
4494 // request necessary permissions. However, they do not expose any secret
4495 // information, so it is OK to pass them.
4496 case AUTHENTICATE_SURFACE:
4497 case GET_ACTIVE_CONFIG:
4498 case GET_BUILT_IN_DISPLAY:
4499 case GET_DISPLAY_COLOR_MODES:
4500 case GET_DISPLAY_CONFIGS:
4501 case GET_DISPLAY_STATS:
Yiwei Zhangcd3f9e92018-08-21 15:15:42 -07004502 case GET_DISPLAY_VIEWPORT:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004503 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4504 // Calling setTransactionState is safe, because you need to have been
4505 // granted a reference to Client* and Handle* to do anything with it.
4506 case SET_TRANSACTION_STATE:
4507 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4508 case CREATE_SCOPED_CONNECTION: {
4509 return OK;
4510 }
4511 case CAPTURE_LAYERS:
4512 case CAPTURE_SCREEN: {
4513 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004514 IPCThreadState* ipc = IPCThreadState::self();
4515 const int pid = ipc->getCallingPid();
4516 const int uid = ipc->getCallingUid();
4517 if ((uid != AID_GRAPHICS) &&
4518 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4519 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4520 return PERMISSION_DENIED;
4521 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004522 return OK;
4523 }
4524 // The following codes are deprecated and should never be allowed to access SF.
4525 case CONNECT_DISPLAY_UNUSED:
4526 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4527 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4528 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004529 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004530 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004531
4532 // These codes are used for the IBinder protocol to either interrogate the recipient
4533 // side of the transaction for its canonical interface descriptor or to dump its state.
4534 // We let them pass by default.
4535 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4536 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4537 code == IBinder::SYSPROPS_TRANSACTION) {
4538 return OK;
4539 }
4540 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4541 // in onTransact verifies that the user is root, and has access to use SF.
4542 if (code >= 1000 && code <= 1029) {
4543 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4544 return OK;
4545 }
4546 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4547 return PERMISSION_DENIED;
4548#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004549}
4550
Ana Krulec13be8ad2018-08-21 02:43:56 +00004551status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4552 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004553 status_t credentialCheck = CheckTransactCodeCredentials(code);
4554 if (credentialCheck != OK) {
4555 return credentialCheck;
4556 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004557
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004558 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4559 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004560 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004561 IPCThreadState* ipc = IPCThreadState::self();
4562 const int uid = ipc->getCallingUid();
4563 if (CC_UNLIKELY(uid != AID_SYSTEM
4564 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004565 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004566 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004567 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004568 return PERMISSION_DENIED;
4569 }
4570 int n;
4571 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004572 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004573 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004574 return NO_ERROR;
4575 case 1002: // SHOW_UPDATES
4576 n = data.readInt32();
4577 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004578 invalidateHwcGeometry();
4579 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004580 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004581 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004582 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004583 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004584 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004585 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004586 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004587 setTransactionFlags(
4588 eTransactionNeeded|
4589 eDisplayTransactionNeeded|
4590 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004591 return NO_ERROR;
4592 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004593 case 1006:{ // send empty update
4594 signalRefresh();
4595 return NO_ERROR;
4596 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004597 case 1008: // toggle use of hw composer
4598 n = data.readInt32();
4599 mDebugDisableHWC = n ? 1 : 0;
4600 invalidateHwcGeometry();
4601 repaintEverything();
4602 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004603 case 1009: // toggle use of transform hint
4604 n = data.readInt32();
4605 mDebugDisableTransformHint = n ? 1 : 0;
4606 invalidateHwcGeometry();
4607 repaintEverything();
4608 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004609 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004610 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004611 reply->writeInt32(0);
4612 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004613 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004614 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004615 return NO_ERROR;
4616 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004617 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004618 if (!display) {
4619 return NAME_NOT_FOUND;
4620 }
4621
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004622 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004623 return NO_ERROR;
4624 }
4625 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004626 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004627 // daltonize
4628 n = data.readInt32();
4629 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004630 case 1:
4631 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4632 break;
4633 case 2:
4634 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4635 break;
4636 case 3:
4637 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4638 break;
4639 default:
4640 mDaltonizer.setType(ColorBlindnessType::None);
4641 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004642 }
4643 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004644 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004645 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004646 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004647 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004648
4649 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004650 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004651 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004652 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004653 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004654 // apply a color matrix
4655 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004656 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004657 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004658 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004659 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004660 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004661 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004662 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004663 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004664 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004665 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004666
4667 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4668 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004669 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004670 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4671 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4672 }
4673
Chia-I Wu28f320b2018-05-03 11:02:56 -07004674 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004675 return NO_ERROR;
4676 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004677 // This is an experimental interface
4678 // Needs to be shifted to proper binder interface when we productize
4679 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004680 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07004681 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004682 return NO_ERROR;
4683 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004684 case 1017: {
4685 n = data.readInt32();
4686 mForceFullDamage = static_cast<bool>(n);
4687 return NO_ERROR;
4688 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004689 case 1018: { // Modify Choreographer's phase offset
4690 n = data.readInt32();
4691 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4692 return NO_ERROR;
4693 }
4694 case 1019: { // Modify SurfaceFlinger's phase offset
4695 n = data.readInt32();
4696 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4697 return NO_ERROR;
4698 }
Irvel468051e2016-06-13 16:44:44 -07004699 case 1020: { // Layer updates interceptor
4700 n = data.readInt32();
4701 if (n) {
4702 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004703 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004704 }
4705 else{
4706 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004707 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004708 }
4709 return NO_ERROR;
4710 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004711 case 1021: { // Disable HWC virtual displays
4712 n = data.readInt32();
4713 mUseHwcVirtualDisplays = !n;
4714 return NO_ERROR;
4715 }
Romain Guy0147a172017-06-01 13:53:56 -07004716 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004717 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004718 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004719
Chia-I Wu28f320b2018-05-03 11:02:56 -07004720 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004721 return NO_ERROR;
4722 }
Romain Guy54f154a2017-10-24 21:40:32 +01004723 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004724 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004725 invalidateHwcGeometry();
4726 repaintEverything();
4727 return NO_ERROR;
4728 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004729 // TODO(b/111505327): Find out whether the usage of 1024 can switch to 1030,
4730 // deprecate 1024 if they can.
4731 case 1024: { // Does device have wide color gamut display?
Romain Guy54f154a2017-10-24 21:40:32 +01004732 reply->writeBool(hasWideColorDisplay);
4733 return NO_ERROR;
4734 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004735 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004736 n = data.readInt32();
4737 if (n) {
4738 ALOGV("LayerTracing enabled");
4739 mTracing.enable();
4740 doTracing("tracing.enable");
4741 reply->writeInt32(NO_ERROR);
4742 } else {
4743 ALOGV("LayerTracing disabled");
4744 status_t err = mTracing.disable();
4745 reply->writeInt32(err);
4746 }
4747 return NO_ERROR;
4748 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004749 case 1026: { // Get layer tracing status
4750 reply->writeBool(mTracing.isEnabled());
4751 return NO_ERROR;
4752 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004753 // Is a DisplayColorSetting supported?
4754 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004755 const auto display = getDefaultDisplayDevice();
4756 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004757 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004758 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004759
4760 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4761 switch (setting) {
4762 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07004763 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004764 break;
4765 case DisplayColorSetting::UNMANAGED:
4766 reply->writeBool(true);
4767 break;
4768 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004769 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004770 break;
4771 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004772 reply->writeBool(
4773 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004774 break;
4775 }
4776 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004777 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004778 // Is VrFlinger active?
4779 case 1028: {
4780 Mutex::Autolock _l(mStateLock);
4781 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4782 return NO_ERROR;
4783 }
David Sodman6d46c1e2018-07-13 12:59:48 -07004784 case 1029: {
4785 // Code 1029 is an experimental feature that allows applications to
4786 // simulate a high frequency panel by setting a multiplier and divisor
4787 // on the VSYNC-sf clock. If either the multiplier or divisor are
4788 // 0, then the code will set both to 1 to return the VSYNC-sf clock
4789 // to it's normal frequency.
4790 int multiplier = data.readInt32();
4791 int divisor = data.readInt32();
4792
4793 if ((multiplier == 0) || (divisor == 0)) {
4794 multiplier = 1;
4795 divisor = 1;
4796 }
4797
4798 if ((multiplier == 1) && (divisor == 1)) {
4799 enableHardwareVsync();
4800 } else {
4801 disableHardwareVsync(true);
4802 }
4803 getBE().mHwc->getActiveConfig(DisplayDevice::DISPLAY_PRIMARY)
4804 ->scalePanelFrequency(multiplier, divisor);
4805 mPrimaryDispSync->scalePeriod(multiplier, divisor);
4806
4807 ATRACE_INT("PeriodMultiplier", multiplier);
4808 ATRACE_INT("PeriodDivisor", divisor);
4809 return NO_ERROR;
4810 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004811 // Is device color managed?
4812 case 1030: {
4813 reply->writeBool(useColorManagement);
4814 return NO_ERROR;
4815 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004816 }
4817 }
4818 return err;
4819}
4820
Steven Thomas6d8110b2017-08-31 18:24:21 -07004821void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004822 android_atomic_or(1, &mRepaintEverything);
4823 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004824}
4825
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004826// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4827class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004828public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004829 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4830 ~WindowDisconnector() {
4831 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004832 }
4833
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004834private:
4835 ANativeWindow* mWindow;
4836 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004837};
4838
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004839status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4840 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4841 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4842 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004843 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004844 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004845
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004846 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004847
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004848 const auto display = getDisplayDeviceLocked(displayToken);
4849 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004850
Yiwei Zhang06a58e22018-08-20 16:42:23 -07004851 const Rect& dispScissor = display->getScissor();
4852 if (!dispScissor.isEmpty()) {
4853 sourceCrop.set(dispScissor);
4854 // adb shell screencap will default reqWidth and reqHeight to zeros.
4855 if (reqWidth == 0 || reqHeight == 0) {
Yiwei Zhangec90e582018-08-21 22:11:37 -07004856 reqWidth = uint32_t(display->getViewport().width());
4857 reqHeight = uint32_t(display->getViewport().height());
Yiwei Zhang06a58e22018-08-20 16:42:23 -07004858 }
4859 }
4860
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004861 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004862
4863 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004864 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004865 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004866}
4867
4868status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004869 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004870 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004871 ATRACE_CALL();
4872
4873 class LayerRenderArea : public RenderArea {
4874 public:
Robert Carr578038f2018-03-09 12:25:24 -08004875 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4876 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004877 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004878 mLayer(layer),
4879 mCrop(crop),
4880 mFlinger(flinger),
4881 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07004882 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004883 Rect getBounds() const override {
4884 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07004885 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07004886 }
Marissa Wall61c58622018-07-18 10:12:20 -07004887 int getHeight() const override {
4888 return mLayer->getActiveHeight(mLayer->getDrawingState());
4889 }
4890 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07004891 bool isSecure() const override { return false; }
4892 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004893 Rect getSourceCrop() const override {
4894 if (mCrop.isEmpty()) {
4895 return getBounds();
4896 } else {
4897 return mCrop;
4898 }
4899 }
Robert Carr578038f2018-03-09 12:25:24 -08004900 class ReparentForDrawing {
4901 public:
4902 const sp<Layer>& oldParent;
4903 const sp<Layer>& newParent;
4904
4905 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4906 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004907 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004908 }
Robert Carr15eae092018-03-23 13:43:53 -07004909 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004910 };
4911
4912 void render(std::function<void()> drawLayers) override {
4913 if (!mChildrenOnly) {
4914 mTransform = mLayer->getTransform().inverse();
4915 drawLayers();
4916 } else {
4917 Rect bounds = getBounds();
4918 screenshotParentLayer =
4919 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4920 bounds.getWidth(), bounds.getHeight(), 0);
4921
4922 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4923 drawLayers();
4924 }
4925 }
chaviwa76b2712017-09-20 12:02:26 -07004926
chaviwa76b2712017-09-20 12:02:26 -07004927 private:
chaviw7206d492017-11-10 16:16:12 -08004928 const sp<Layer> mLayer;
4929 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004930
4931 // In the "childrenOnly" case we reparent the children to a screenshot
4932 // layer which has no properties set and which does not draw.
4933 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07004934 ui::Transform mTransform;
Robert Carr578038f2018-03-09 12:25:24 -08004935
4936 SurfaceFlinger* mFlinger;
4937 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004938 };
4939
4940 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4941 auto parent = layerHandle->owner.promote();
4942
chaviw7206d492017-11-10 16:16:12 -08004943 if (parent == nullptr || parent->isPendingRemoval()) {
4944 ALOGE("captureLayers called with a removed parent");
4945 return NAME_NOT_FOUND;
4946 }
4947
Robert Carr578038f2018-03-09 12:25:24 -08004948 const int uid = IPCThreadState::self()->getCallingUid();
4949 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4950 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4951 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4952 return PERMISSION_DENIED;
4953 }
4954
chaviw7206d492017-11-10 16:16:12 -08004955 Rect crop(sourceCrop);
4956 if (sourceCrop.width() <= 0) {
4957 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07004958 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08004959 }
4960
4961 if (sourceCrop.height() <= 0) {
4962 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07004963 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08004964 }
4965
4966 int32_t reqWidth = crop.width() * frameScale;
4967 int32_t reqHeight = crop.height() * frameScale;
4968
Robert Carr578038f2018-03-09 12:25:24 -08004969 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004970
Robert Carr578038f2018-03-09 12:25:24 -08004971 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004972 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4973 if (!layer->isVisible()) {
4974 return;
Robert Carr578038f2018-03-09 12:25:24 -08004975 } else if (childrenOnly && layer == parent.get()) {
4976 return;
chaviwa76b2712017-09-20 12:02:26 -07004977 }
4978 visitor(layer);
4979 });
4980 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004981 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004982}
4983
4984status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4985 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004986 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004987 bool useIdentityTransform) {
4988 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004989
Iris Chang7501ed62018-04-30 14:45:42 +08004990 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004991
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004992 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4993 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4994 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4995 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004996
4997 // This mutex protects syncFd and captureResult for communication of the return values from the
4998 // main thread back to this Binder thread
4999 std::mutex captureMutex;
5000 std::condition_variable captureCondition;
5001 std::unique_lock<std::mutex> captureLock(captureMutex);
5002 int syncFd = -1;
5003 std::optional<status_t> captureResult;
5004
Robert Carr03480e22018-01-04 16:02:06 -08005005 const int uid = IPCThreadState::self()->getCallingUid();
5006 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5007
Dominik Laskowski8c001672018-05-30 16:52:06 -07005008 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005009 // If there is a refresh pending, bug out early and tell the binder thread to try again
5010 // after the refresh.
5011 if (mRefreshPending) {
5012 ATRACE_NAME("Skipping screenshot for now");
5013 std::unique_lock<std::mutex> captureLock(captureMutex);
5014 captureResult = std::make_optional<status_t>(EAGAIN);
5015 captureCondition.notify_one();
5016 return;
5017 }
5018
5019 status_t result = NO_ERROR;
5020 int fd = -1;
5021 {
5022 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005023 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005024 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5025 useIdentityTransform, forSystem, &fd);
5026 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005027 }
5028
5029 {
5030 std::unique_lock<std::mutex> captureLock(captureMutex);
5031 syncFd = fd;
5032 captureResult = std::make_optional<status_t>(result);
5033 captureCondition.notify_one();
5034 }
5035 });
5036
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005037 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005038 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005039 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005040 while (*captureResult == EAGAIN) {
5041 captureResult.reset();
5042 result = postMessageAsync(message);
5043 if (result != NO_ERROR) {
5044 return result;
5045 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005046 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005047 }
5048 result = *captureResult;
5049 }
5050
5051 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005052 sync_wait(syncFd, -1);
5053 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005054 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005055
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005056 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005057}
5058
chaviwa76b2712017-09-20 12:02:26 -07005059void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5060 TraverseLayersFunction traverseLayers, bool yswap,
5061 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005062 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005063
Lloyd Pique144e1162017-12-20 16:44:52 -08005064 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005065
5066 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005067 const auto raWidth = renderArea.getWidth();
5068 const auto raHeight = renderArea.getHeight();
5069
5070 const auto reqWidth = renderArea.getReqWidth();
5071 const auto reqHeight = renderArea.getReqHeight();
5072 Rect sourceCrop = renderArea.getSourceCrop();
5073
Iris Chang7501ed62018-04-30 14:45:42 +08005074 bool filtering = false;
5075 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5076 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5077 static_cast<int32_t>(reqHeight) != raWidth;
5078 } else {
5079 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5080 static_cast<int32_t>(reqHeight) != raHeight;
5081 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005082
Dan Stozac1879002014-05-22 15:59:05 -07005083 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005084 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005085 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005086 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005087 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
Peiyong Linefefaac2018-08-17 12:27:51 -07005088 ui::Transform tr;
Iris Chang7501ed62018-04-30 14:45:42 +08005089 uint32_t flags = 0x00;
5090 switch (mPrimaryDisplayOrientation) {
5091 case DisplayState::eOrientation90:
Peiyong Linefefaac2018-08-17 12:27:51 -07005092 flags = ui::Transform::ROT_90;
Iris Chang7501ed62018-04-30 14:45:42 +08005093 break;
5094 case DisplayState::eOrientation180:
Peiyong Linefefaac2018-08-17 12:27:51 -07005095 flags = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005096 break;
5097 case DisplayState::eOrientation270:
Peiyong Linefefaac2018-08-17 12:27:51 -07005098 flags = ui::Transform::ROT_270;
Iris Chang7501ed62018-04-30 14:45:42 +08005099 break;
5100 }
5101 tr.set(flags, raWidth, raHeight);
5102 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005103 }
5104
5105 // ensure that sourceCrop is inside screen
5106 if (sourceCrop.left < 0) {
5107 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5108 }
chaviwa76b2712017-09-20 12:02:26 -07005109 if (sourceCrop.right > raWidth) {
5110 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005111 }
5112 if (sourceCrop.top < 0) {
5113 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5114 }
chaviwa76b2712017-09-20 12:02:26 -07005115 if (sourceCrop.bottom > raHeight) {
5116 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005117 }
5118
Chia-I Wu36574d92018-05-16 10:54:36 -07005119 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5120 engine.setOutputDataSpace(Dataspace::SRGB);
5121 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005122
Mathias Agopian180f10d2013-04-10 22:55:41 -07005123 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005124 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005125
Peiyong Linefefaac2018-08-17 12:27:51 -07005126 ui::Transform::orientation_flags rotation = renderArea.getRotationFlags();
Iris Chang7501ed62018-04-30 14:45:42 +08005127 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5128 // convert hw orientation into flag presentation
5129 // here inverse transform needed
5130 uint8_t hw_rot_90 = 0x00;
5131 uint8_t hw_flip_hv = 0x00;
5132 switch (mPrimaryDisplayOrientation) {
5133 case DisplayState::eOrientation90:
Peiyong Linefefaac2018-08-17 12:27:51 -07005134 hw_rot_90 = ui::Transform::ROT_90;
5135 hw_flip_hv = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005136 break;
5137 case DisplayState::eOrientation180:
Peiyong Linefefaac2018-08-17 12:27:51 -07005138 hw_flip_hv = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005139 break;
5140 case DisplayState::eOrientation270:
Peiyong Linefefaac2018-08-17 12:27:51 -07005141 hw_rot_90 = ui::Transform::ROT_90;
Iris Chang7501ed62018-04-30 14:45:42 +08005142 break;
5143 }
5144
5145 // transform flags operation
5146 // 1) flip H V if both have ROT_90 flag
5147 // 2) XOR these flags
Peiyong Linefefaac2018-08-17 12:27:51 -07005148 uint8_t rotation_rot_90 = rotation & ui::Transform::ROT_90;
5149 uint8_t rotation_flip_hv = rotation & ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005150 if (rotation_rot_90 & hw_rot_90) {
Peiyong Linefefaac2018-08-17 12:27:51 -07005151 rotation_flip_hv = (~rotation_flip_hv) & ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005152 }
Peiyong Linefefaac2018-08-17 12:27:51 -07005153 rotation = static_cast<ui::Transform::orientation_flags>
Iris Chang7501ed62018-04-30 14:45:42 +08005154 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5155 }
5156
Mathias Agopian180f10d2013-04-10 22:55:41 -07005157 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005158 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005159 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005160 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005161
chaviw50da5042018-04-09 13:49:37 -07005162 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005163 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005164 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005165
chaviwa76b2712017-09-20 12:02:26 -07005166 traverseLayers([&](Layer* layer) {
5167 if (filtering) layer->setFiltering(true);
David Sodmanca10ed22018-04-16 14:10:25 -07005168 layer->drawNow(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005169 if (filtering) layer->setFiltering(false);
5170 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005171}
5172
chaviwa76b2712017-09-20 12:02:26 -07005173status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5174 TraverseLayersFunction traverseLayers,
5175 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005176 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005177 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005178 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005179 ATRACE_CALL();
5180
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005181 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005182
5183 traverseLayers([&](Layer* layer) {
5184 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5185 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005186
Robert Carr03480e22018-01-04 16:02:06 -08005187 // We allow the system server to take screenshots of secure layers for
5188 // use in situations like the Screen-rotation animation and place
5189 // the impetus on WindowManager to not persist them.
5190 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005191 ALOGW("FB is protected: PERMISSION_DENIED");
5192 return PERMISSION_DENIED;
5193 }
5194
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005195 // this binds the given EGLImage as a framebuffer for the
5196 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005197 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005198 if (bufferBond.getStatus() != NO_ERROR) {
5199 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005200 return INVALID_OPERATION;
5201 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005202
Dan Stozaabcda352017-06-01 14:37:39 -07005203 // this will in fact render into our dequeued buffer
5204 // via an FBO, which means we didn't have to create
5205 // an EGLSurface and therefore we're not
5206 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005207 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005208
Dan Stozaabcda352017-06-01 14:37:39 -07005209 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005210 getRenderEngine().finish();
5211 *outSyncFd = -1;
5212
chaviwa76b2712017-09-20 12:02:26 -07005213 const auto reqWidth = renderArea.getReqWidth();
5214 const auto reqHeight = renderArea.getReqHeight();
5215
Dan Stozaabcda352017-06-01 14:37:39 -07005216 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5217 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005218 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005219 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005220 } else {
5221 base::unique_fd syncFd = getRenderEngine().flush();
5222 if (syncFd < 0) {
5223 getRenderEngine().finish();
5224 }
5225 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005226 }
5227
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005228 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005229}
5230
Mathias Agopiand5556842013-09-19 17:08:37 -07005231void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005232 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005233 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005234 for (size_t y = 0; y < h; y++) {
5235 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5236 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005237 if (p[x] != 0xFF000000) return;
5238 }
5239 }
chaviwa76b2712017-09-20 12:02:26 -07005240 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005241
Robert Carr2047fae2016-11-28 14:09:09 -08005242 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005243 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005244 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005245 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5246 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5247 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5248 static_cast<float>(state.color.a));
5249 i++;
5250 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005251 }
5252}
5253
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005254// ---------------------------------------------------------------------------
5255
Dan Stoza412903f2017-04-27 13:42:17 -07005256void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5257 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005258}
5259
Dan Stoza412903f2017-04-27 13:42:17 -07005260void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5261 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005262}
5263
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005264void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5265 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005266 const LayerVector::Visitor& visitor) {
5267 // We loop through the first level of layers without traversing,
5268 // as we need to interpret min/max layer Z in the top level Z space.
5269 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005270 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005271 continue;
5272 }
5273 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005274 // relative layers are traversed in Layer::traverseInZOrder
5275 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005276 continue;
5277 }
5278 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005279 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005280 return;
5281 }
chaviwa76b2712017-09-20 12:02:26 -07005282 if (!layer->isVisible()) {
5283 return;
5284 }
5285 visitor(layer);
5286 });
5287 }
5288}
5289
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005290}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005291
Lloyd Pique074e8122018-07-26 12:57:23 -07005292
Mathias Agopian3f844832013-08-07 21:24:32 -07005293#if defined(__gl_h_)
5294#error "don't include gl/gl.h in this file"
5295#endif
5296
5297#if defined(__gl2_h_)
5298#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005299#endif