blob: 7c3a8c1ae19a32485473ed26c8f936e9a9a57924 [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
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Dan Stoza9e56aa02015-11-02 13:00:03 -080021//#define LOG_NDEBUG 0
22#undef LOG_TAG
23#define LOG_TAG "Layer"
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080024#define ATRACE_TAG ATRACE_TAG_GRAPHICS
25
Alec Mourie60041e2019-06-14 18:59:51 -070026#include "Layer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080027
[1;3C2b9fc252021-02-04 16:16:50 -080028#include <android-base/properties.h>
Yiwei Zhang5434a782018-12-05 18:06:32 -080029#include <android-base/stringprintf.h>
Vishnu Nair0f085c62019-08-30 08:49:12 -070030#include <binder/IPCThreadState.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000031#include <compositionengine/CompositionEngine.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080032#include <compositionengine/Display.h>
Lloyd Piquea83776c2019-01-29 18:42:32 -080033#include <compositionengine/LayerFECompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080034#include <compositionengine/OutputLayer.h>
35#include <compositionengine/impl/OutputLayerCompositionState.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070036#include <cutils/compiler.h>
Mathias Agopian076b1cc2009-04-10 14:24:30 -070037#include <cutils/native_handle.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070038#include <cutils/properties.h>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070039#include <ftl/enum.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080040#include <ftl/fake_guard.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080041#include <gui/BufferItem.h>
42#include <gui/LayerDebugInfo.h>
43#include <gui/Surface.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000044#include <gui/TraceUtils.h>
Alec Mourie60041e2019-06-14 18:59:51 -070045#include <math.h>
chaviw250bcbb2020-08-05 11:17:54 -070046#include <private/android_filesystem_config.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080047#include <renderengine/RenderEngine.h>
Alec Mourie60041e2019-06-14 18:59:51 -070048#include <stdint.h>
49#include <stdlib.h>
50#include <sys/types.h>
Alec Mouridda07d92022-04-25 22:39:25 +000051#include <system/graphics-base-v1.0.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080052#include <ui/DebugUtils.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000053#include <ui/FloatRect.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080054#include <ui/GraphicBuffer.h>
Sally Qif6918d42023-08-07 15:28:30 -070055#include <ui/HdrRenderTypeUtils.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080056#include <ui/PixelFormat.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000057#include <ui/Rect.h>
58#include <ui/Transform.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059#include <utils/Errors.h>
60#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080061#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080063#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Alec Mourie60041e2019-06-14 18:59:51 -070065#include <algorithm>
66#include <mutex>
Vishnu Nair71fcf912022-10-18 09:14:20 -070067#include <optional>
Alec Mourie60041e2019-06-14 18:59:51 -070068#include <sstream>
69
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070070#include "DisplayDevice.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080071#include "DisplayHardware/HWComposer.h"
Ady Abraham22c7b5c2020-09-22 19:33:40 -070072#include "FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -070073#include "FrameTracer/FrameTracer.h"
Vishnu Naircb8be502022-10-12 19:03:23 +000074#include "FrontEnd/LayerCreationArgs.h"
Vishnu Nair07e2a482022-10-18 19:18:16 +000075#include "FrontEnd/LayerHandle.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080076#include "LayerProtoHelper.h"
Josh Gao194ff392022-09-08 16:19:29 -070077#include "MutexUtils.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include "SurfaceFlinger.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080079#include "TimeStats/TimeStats.h"
Robert Carr3e2a2992021-06-11 13:42:55 -070080#include "TunnelModeEnabledReporter.h"
Mathias Agopian1b031492012-06-20 17:51:20 -070081
David Sodman41fdfc92017-11-06 16:09:56 -080082#define DEBUG_RESIZE 0
Patrick Williamsbb25f802022-08-30 23:02:34 +000083#define EARLY_RELEASE_ENABLED false
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085namespace android {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +010086namespace {
87constexpr int kDumpTableRowLength = 159;
Patrick Williamsbb25f802022-08-30 23:02:34 +000088
Prabir Pradhanda0f62c2022-07-22 19:53:04 +000089const ui::Transform kIdentityTransform;
Patrick Williamsbb25f802022-08-30 23:02:34 +000090
Patrick Williamsbb25f802022-08-30 23:02:34 +000091bool assignTransform(ui::Transform* dst, ui::Transform& from) {
92 if (*dst == from) {
93 return false;
94 }
95 *dst = from;
96 return true;
97}
98
99TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
100 using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
101 using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
102 const auto frameRateCompatibility = [frameRate] {
Rachel Leece6e0042023-06-27 11:22:54 -0700103 switch (frameRate.vote.type) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000104 case Layer::FrameRateCompatibility::Default:
105 return FrameRateCompatibility::Default;
106 case Layer::FrameRateCompatibility::ExactOrMultiple:
107 return FrameRateCompatibility::ExactOrMultiple;
108 default:
109 return FrameRateCompatibility::Undefined;
110 }
111 }();
112
113 const auto seamlessness = [frameRate] {
Rachel Leece6e0042023-06-27 11:22:54 -0700114 switch (frameRate.vote.seamlessness) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000115 case scheduler::Seamlessness::OnlySeamless:
116 return Seamlessness::ShouldBeSeamless;
117 case scheduler::Seamlessness::SeamedAndSeamless:
118 return Seamlessness::NotRequired;
119 default:
120 return Seamlessness::Undefined;
121 }
122 }();
123
Rachel Leece6e0042023-06-27 11:22:54 -0700124 return TimeStats::SetFrameRateVote{.frameRate = frameRate.vote.rate.getValue(),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000125 .frameRateCompatibility = frameRateCompatibility,
126 .seamlessness = seamlessness};
127}
128
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100129} // namespace
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800130
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700131using namespace ftl::flag_operators;
132
Yiwei Zhang5434a782018-12-05 18:06:32 -0800133using base::StringAppendF;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000134using frontend::LayerSnapshot;
135using frontend::RoundedCornerState;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800136using gui::GameMode;
137using gui::LayerMetadata;
chaviw3277faf2021-05-19 16:45:23 -0500138using gui::WindowInfo;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800139
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700140using PresentState = frametimeline::SurfaceFrame::PresentState;
141
Kean Mariotti4ba343c2023-04-19 13:31:02 +0000142Layer::Layer(const surfaceflinger::LayerCreationArgs& args)
Vishnu Naircb8be502022-10-12 19:03:23 +0000143 : sequence(args.sequence),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700144 mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
Arthur Hung23e07502021-10-15 11:58:19 +0000145 mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
Ady Abraham8f1ee7f2019-04-05 10:32:50 -0700146 mClientRef(args.client),
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800147 mWindowType(static_cast<WindowInfo::Type>(
148 args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))),
Tianhao Yao67dd7122022-02-22 17:48:33 +0000149 mLayerCreationFlags(args.flags),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000150 mBorderEnabled(false),
Vishnu Nair3af0ec02023-02-10 04:13:48 +0000151 mLegacyLayerFE(args.flinger->getFactory().createLayerFE(mName)) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000152 ALOGV("Creating Layer %s", getDebugName());
153
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700154 uint32_t layerFlags = 0;
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700155 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
156 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
157 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
chaviwc5676c62020-09-18 15:01:04 -0700158 if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
159 layerFlags |= layer_state_t::eLayerSkipScreenshot;
Robert Carr6a160312021-05-17 12:08:20 -0700160 mDrawingState.flags = layerFlags;
Robert Carr6a160312021-05-17 12:08:20 -0700161 mDrawingState.crop.makeInvalid();
Robert Carr6a160312021-05-17 12:08:20 -0700162 mDrawingState.z = 0;
163 mDrawingState.color.a = 1.0f;
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700164 mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
Robert Carr6a160312021-05-17 12:08:20 -0700165 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700166 mDrawingState.transform.set(0, 0);
167 mDrawingState.frameNumber = 0;
Vishnu Nair63221212023-04-06 15:17:37 -0700168 mDrawingState.barrierFrameNumber = 0;
169 mDrawingState.producerId = 0;
170 mDrawingState.barrierProducerId = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700171 mDrawingState.bufferTransform = 0;
172 mDrawingState.transformToDisplayInverse = false;
Robert Carr6a160312021-05-17 12:08:20 -0700173 mDrawingState.acquireFence = sp<Fence>::make(-1);
174 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
Alec Mouri74c7ae12023-03-26 02:57:47 +0000175 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Robert Carr6a160312021-05-17 12:08:20 -0700176 mDrawingState.hdrMetadata.validTypes = 0;
177 mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
178 mDrawingState.cornerRadius = 0.0f;
179 mDrawingState.backgroundBlurRadius = 0;
180 mDrawingState.api = -1;
181 mDrawingState.hasColorTransform = false;
182 mDrawingState.colorSpaceAgnostic = false;
183 mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
184 mDrawingState.metadata = args.metadata;
185 mDrawingState.shadowRadius = 0.f;
186 mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
187 mDrawingState.frameTimelineInfo = {};
188 mDrawingState.postTime = -1;
189 mDrawingState.destinationFrame.makeInvalid();
Robin Leeedb375d2021-09-10 12:03:42 +0000190 mDrawingState.isTrustedOverlay = false;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -0700191 mDrawingState.dropInputMode = gui::DropInputMode::NONE;
Sally Qi81d95e62022-03-21 19:41:33 -0700192 mDrawingState.dimmingEnabled = true;
Andy Labrada096227e2022-06-15 16:58:11 +0000193 mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
Rachel Lee58cc90d2023-09-05 18:50:20 -0700194 mDrawingState.frameRateSelectionStrategy = FrameRateSelectionStrategy::Self;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700195
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700196 if (args.flags & ISurfaceComposerClient::eNoColorFill) {
197 // Set an invalid color so there is no color fill.
Robert Carr6a160312021-05-17 12:08:20 -0700198 mDrawingState.color.r = -1.0_hf;
199 mDrawingState.color.g = -1.0_hf;
200 mDrawingState.color.b = -1.0_hf;
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700201 }
Dominik Laskowski4376bd82022-07-07 11:50:20 -0700202
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500203 mFrameTracker.setDisplayRefreshPeriod(
204 args.flinger->mScheduler->getPacesetterVsyncPeriod().ns());
Robert Carr2e102c92018-10-23 12:11:15 -0700205
Vishnu Naircb8be502022-10-12 19:03:23 +0000206 mOwnerUid = args.ownerUid;
207 mOwnerPid = args.ownerPid;
Tony Huangf3621102023-09-04 17:14:22 +0800208 mOwnerAppId = mOwnerUid % PER_USER_RANGE;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000209
210 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
211 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
212 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000213
214 mSnapshot->sequence = sequence;
215 mSnapshot->name = getDebugName();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000216 mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000217 mSnapshot->parentTransform = {};
Dominik Laskowski75848362019-11-11 17:57:20 -0800218}
219
220void Layer::onFirstRef() {
221 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700222}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700223
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700224Layer::~Layer() {
Patrick Williams70093fd2022-12-12 16:51:52 +0000225 LOG_ALWAYS_FATAL_IF(std::this_thread::get_id() != mFlinger->mMainThreadId,
226 "Layer destructor called off the main thread.");
227
Patrick Williamsbb25f802022-08-30 23:02:34 +0000228 // The original layer and the clone layer share the same texture and buffer. Therefore, only
229 // one of the layers, in this case the original layer, needs to handle the deletion. The
230 // original layer and the clone should be removed at the same time so there shouldn't be any
231 // issue with the clone layer trying to use the texture.
232 if (mBufferInfo.mBuffer != nullptr) {
233 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
234 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
liulijuneb489f62022-10-17 22:02:14 +0800235 mBufferInfo.mFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000236 }
Patrick Williamsbb25f802022-08-30 23:02:34 +0000237 const int32_t layerId = getSequence();
238 mFlinger->mTimeStats->onDestroy(layerId);
239 mFlinger->mFrameTracer->onDestroy(layerId);
240
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000241 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700242 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700243
244 if (mDrawingState.sidebandStream != nullptr) {
245 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
246 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700247 if (mHadClonedChild) {
Vishnu Nair3be61902023-04-26 19:47:29 -0700248 auto& roots = mFlinger->mLayerMirrorRoots;
249 roots.erase(std::remove(roots.begin(), roots.end(), this), roots.end());
Robert Carr6a0382d2021-07-01 15:57:17 -0700250 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000251 if (hasTrustedPresentationListener()) {
252 mFlinger->mNumTrustedPresentationListeners--;
Vishnu Nair781d7252023-01-30 18:16:01 +0000253 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Chavi Weingarten076acac2023-01-19 17:20:43 +0000254 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700255}
256
Mathias Agopian13127d82013-03-05 17:47:11 -0800257// ---------------------------------------------------------------------------
258// callbacks
259// ---------------------------------------------------------------------------
260
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700261void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700262 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700263 return;
264 }
Robert Carr2e102c92018-10-23 12:11:15 -0700265
Robert Carr6a160312021-05-17 12:08:20 -0700266 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700267 if (strongRelative == nullptr) {
268 setZOrderRelativeOf(nullptr);
269 return;
270 }
271
272 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700273 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700274 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800275 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700276 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700277}
278
279void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700280 if (!mRemovedFromDrawingState) {
281 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700282 mFlinger->mScheduler->deregisterLayer(this);
283 }
Vishnu Nair781d7252023-01-30 18:16:01 +0000284 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Rob Carr4bba3702018-10-08 21:53:30 +0000285
Ady Abrahamd11bade2022-08-01 16:18:03 -0700286 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700287}
Chia-I Wu38512252017-05-17 14:36:16 -0700288
chaviw68d4dab2020-06-08 15:07:32 -0700289sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000290 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700291 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700292 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700293 }
294 return parent->getRootLayer();
295}
296
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700297void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700298 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
299 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700300 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700301
Josh Gao194ff392022-09-08 16:19:29 -0700302 REQUIRE_MUTEX(mFlinger->mStateLock);
303 traverse(LayerVector::StateSet::Current,
304 [&](Layer* layer) REQUIRES(layer->mFlinger->mStateLock) {
305 layer->removeFromCurrentState();
306 layer->removeRelativeZ(layersInTree);
307 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700308}
309
chaviw61626f22018-11-15 16:26:27 -0800310void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700311 if (mRemovedFromDrawingState) {
312 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700313 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700314 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700315 }
chaviw61626f22018-11-15 16:26:27 -0800316
317 for (const auto& child : mCurrentChildren) {
318 child->addToCurrentState();
319 }
320}
321
Mathias Agopian13127d82013-03-05 17:47:11 -0800322// ---------------------------------------------------------------------------
323// set-up
324// ---------------------------------------------------------------------------
325
chaviw13fdc492017-06-27 12:40:18 -0700326bool Layer::getPremultipledAlpha() const {
327 return mPremultipliedAlpha;
328}
329
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700330sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800331 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700332 if (mGetHandleCalled) {
333 ALOGE("Get handle called twice" );
334 return nullptr;
335 }
336 mGetHandleCalled = true;
Vishnu Nair787aa782023-03-17 13:46:46 -0700337 mHandleAlive = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000338 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800339}
340
341// ---------------------------------------------------------------------------
342// h/w composer set-up
343// ---------------------------------------------------------------------------
344
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700345static Rect reduce(const Rect& win, const Region& exclude) {
346 if (CC_LIKELY(exclude.isEmpty())) {
347 return win;
348 }
349 if (exclude.isRect()) {
350 return win.reduce(exclude.getBounds());
351 }
352 return Region(win).subtract(exclude).getBounds();
353}
354
Dan Stoza80d61162017-12-20 15:57:52 -0800355static FloatRect reduce(const FloatRect& win, const Region& exclude) {
356 if (CC_LIKELY(exclude.isEmpty())) {
357 return win;
358 }
359 // Convert through Rect (by rounding) for lack of FloatRegion
360 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
361}
362
Vishnu Nair4351ad52019-02-11 14:13:02 -0800363Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800364 if (!reduceTransparentRegion) {
365 return Rect{mScreenBounds};
366 }
367
368 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800369 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800370 // Transform to screen space.
371 bounds = t.transform(bounds);
372 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700373}
374
Vishnu Nair4351ad52019-02-11 14:13:02 -0800375FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000376 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800377 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700378}
379
Vishnu Nairf0c28512019-02-08 12:40:28 -0800380FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
381 // Subtract the transparent region and snap to the bounds.
382 return reduce(mBounds, activeTransparentRegion);
383}
384
Chavi Weingarten076acac2023-01-19 17:20:43 +0000385// No early returns.
Vishnu Nair781d7252023-01-30 18:16:01 +0000386void Layer::updateTrustedPresentationState(const DisplayDevice* display,
387 const frontend::LayerSnapshot* snapshot,
388 int64_t time_in_ms, bool leaveState) {
Chavi Weingarten076acac2023-01-19 17:20:43 +0000389 if (!hasTrustedPresentationListener()) {
390 return;
391 }
392 const bool lastState = mLastComputedTrustedPresentationState;
393 mLastComputedTrustedPresentationState = false;
394
395 if (!leaveState) {
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000396 const auto outputLayer = findOutputLayerForDisplay(display, snapshot->path);
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000397 if (outputLayer != nullptr) {
398 if (outputLayer->getState().coveredRegionExcludingDisplayOverlays) {
399 Region coveredRegion =
400 *outputLayer->getState().coveredRegionExcludingDisplayOverlays;
401 mLastComputedTrustedPresentationState =
402 computeTrustedPresentationState(snapshot->geomLayerBounds,
403 snapshot->sourceBounds(), coveredRegion,
404 snapshot->transformedBounds,
405 snapshot->alpha,
406 snapshot->geomLayerTransform,
407 mTrustedPresentationThresholds);
408 } else {
409 ALOGE("CoveredRegionExcludingDisplayOverlays was not set for %s. Don't compute "
410 "TrustedPresentationState",
411 getDebugName());
412 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000413 }
414 }
415 const bool newState = mLastComputedTrustedPresentationState;
416 if (lastState && !newState) {
417 // We were in the trusted presentation state, but now we left it,
418 // emit the callback if needed
419 if (mLastReportedTrustedPresentationState) {
420 mLastReportedTrustedPresentationState = false;
421 mTrustedPresentationListener.invoke(false);
422 }
423 // Reset the timer
424 mEnteredTrustedPresentationStateTime = -1;
425 } else if (!lastState && newState) {
426 // We were not in the trusted presentation state, but we entered it, begin the timer
427 // and make sure this gets called at least once more!
428 mEnteredTrustedPresentationStateTime = time_in_ms;
429 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
430 }
431
432 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
433 if (!mLastReportedTrustedPresentationState && newState &&
434 (time_in_ms - mEnteredTrustedPresentationStateTime >
435 mTrustedPresentationThresholds.stabilityRequirementMs)) {
436 mLastReportedTrustedPresentationState = true;
437 mTrustedPresentationListener.invoke(true);
438 }
439}
440
441/**
442 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
443 * of how the parameters and thresholds are interpreted. The general spirit is
444 * to produce an upper bound on the amount of the buffer which was presented.
445 */
446bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
447 const Region& coveredRegion,
448 const FloatRect& screenBounds, float alpha,
449 const ui::Transform& effectiveTransform,
450 const TrustedPresentationThresholds& thresholds) {
451 if (alpha < thresholds.minAlpha) {
452 return false;
453 }
454 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
455 return false;
456 }
457 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
458 return false;
459 }
460
461 const float sx = effectiveTransform.dsdx();
462 const float sy = effectiveTransform.dsdy();
463 float fractionRendered = std::min(sx * sy, 1.0f);
464
465 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
466 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
467 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
468
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000469 Region tJunctionFreeRegion = Region::createTJunctionFreeRegion(coveredRegion);
470 // Compute the size of all the rects since they may be disconnected.
471 float coveredSize = 0;
472 for (auto rect = tJunctionFreeRegion.begin(); rect < tJunctionFreeRegion.end(); rect++) {
473 float size = rect->width() * rect->height();
474 coveredSize += size;
475 }
476
477 fractionRendered *= (1 - (coveredSize / (screenBounds.getWidth() * screenBounds.getHeight())));
Chavi Weingarten076acac2023-01-19 17:20:43 +0000478
479 if (fractionRendered < thresholds.minFractionRendered) {
480 return false;
481 }
482
483 return true;
484}
485
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700486void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
487 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800488 const State& s(getDrawingState());
489
490 // Calculate effective layer transform
491 mEffectiveTransform = parentTransform * getActiveTransform(s);
492
Garfield Tan2c1782c2022-02-16 15:25:05 -0800493 if (CC_UNLIKELY(!isTransformValid())) {
494 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
495 getDebugName());
496 return;
497 }
498
Vishnu Nair4351ad52019-02-11 14:13:02 -0800499 // Transform parent bounds to layer space
500 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
501
Vishnu Nairc652ff82019-03-15 12:48:54 -0700502 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800503 mSourceBounds = computeSourceBounds(parentBounds);
504
505 // Calculate bounds by croping diplay frame with layer crop and parent bounds
506 FloatRect bounds = mSourceBounds;
507 const Rect layerCrop = getCrop(s);
508 if (!layerCrop.isEmpty()) {
509 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
510 }
511 bounds = bounds.intersect(parentBounds);
512
513 mBounds = bounds;
514 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700515
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700516 // Use the layer's own shadow radius if set. Otherwise get the radius from
517 // parent.
518 if (s.shadowRadius > 0.f) {
519 mEffectiveShadowRadius = s.shadowRadius;
520 } else {
521 mEffectiveShadowRadius = parentShadowRadius;
522 }
523
524 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
525 // don't pass it to its children.
526 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
527
Vishnu Nair4351ad52019-02-11 14:13:02 -0800528 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700529 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800530 }
Vishnu Nairba354102022-08-01 00:14:18 +0000531
532 if (mPotentialCursor) {
533 prepareCursorCompositionState();
534 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800535}
536
Vishnu Nair60356342018-11-13 13:00:45 -0800537Rect Layer::getCroppedBufferSize(const State& s) const {
538 Rect size = getBufferSize(s);
539 Rect crop = getCrop(s);
540 if (!crop.isEmpty() && size.isValid()) {
541 size.intersect(crop, &size);
542 } else if (!crop.isEmpty()) {
543 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700544 }
Vishnu Nair60356342018-11-13 13:00:45 -0800545 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800546}
547
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700548void Layer::setupRoundedCornersCropCoordinates(Rect win,
549 const FloatRect& roundedCornersCrop) const {
550 // Translate win by the rounded corners rect coordinates, to have all values in
551 // layer coordinate space.
552 win.left -= roundedCornersCrop.left;
553 win.right -= roundedCornersCrop.left;
554 win.top -= roundedCornersCrop.top;
555 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700556}
557
Lloyd Piquede196652020-01-22 17:29:58 -0800558void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800559 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800560 const auto alpha = static_cast<float>(getAlpha());
561 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700562 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800563
564 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
565 if (!opaque || alpha != 1.0f) {
566 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
567 : Hwc2::IComposerClient::BlendMode::COVERAGE;
568 }
569
Alec Mourif4af03e2023-02-11 00:25:24 +0000570 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000571 auto* snapshot = editLayerSnapshot();
572 snapshot->outputFilter = getOutputFilter();
573 snapshot->isVisible = isVisible();
574 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
Vishnu Naird9e4f462023-10-06 04:05:45 +0000575 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800576
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000577 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800578 contentDirty = false;
579
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000580 snapshot->geomLayerBounds = mBounds;
581 snapshot->geomLayerTransform = getTransform();
582 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
583 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000584 snapshot->localTransform = getActiveTransform(drawingState);
585 snapshot->localTransformInverse = snapshot->localTransform.inverse();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000586 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
587 snapshot->alpha = alpha;
Vishnu Nairc6384702023-07-31 12:22:20 -0700588 snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
589 snapshot->blurRegions = getBlurRegions();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000590 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800591}
592
Lloyd Piquede196652020-01-22 17:29:58 -0800593void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800594 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000595 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700596
Alec Mourif4af03e2023-02-11 00:25:24 +0000597 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000598 snapshot->geomBufferSize = getBufferSize(drawingState);
599 snapshot->geomContentCrop = getBufferCrop();
600 snapshot->geomCrop = getCrop(drawingState);
601 snapshot->geomBufferTransform = getBufferTransform();
602 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
603 snapshot->geomUsesSourceCrop = usesSourceCrop();
604 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800605
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000606 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800607 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
608 for (const auto& [key, mandatory] : supportedMetadata) {
609 const auto& genericLayerMetadataCompatibilityMap =
610 mFlinger->getGenericLayerMetadataKeyMap();
611 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
612 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
613 continue;
614 }
615 const uint32_t id = compatIter->second;
616
617 auto it = drawingState.metadata.mMap.find(id);
618 if (it == std::end(drawingState.metadata.mMap)) {
619 continue;
620 }
621
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000622 snapshot->metadata.emplace(key,
623 compositionengine::GenericLayerMetadataEntry{mandatory,
624 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800625 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800626}
David Sodmanba340492018-08-05 21:51:33 -0700627
Lloyd Piquede196652020-01-22 17:29:58 -0800628void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800629 const auto& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000630 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000631 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800632
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000633 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800634
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000635 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
636 snapshot->dataspace = getDataSpace();
637 snapshot->colorTransform = getColorTransform();
638 snapshot->colorTransformIsIdentity = !hasColorTransform();
639 snapshot->surfaceDamage = surfaceDamageRegion;
640 snapshot->hasProtectedContent = isProtected();
641 snapshot->dimmingEnabled = isDimmingEnabled();
Sally Qi963049b2023-03-23 14:06:21 -0700642 snapshot->currentHdrSdrRatio = getCurrentHdrSdrRatio();
643 snapshot->desiredHdrSdrRatio = getDesiredHdrSdrRatio();
Alec Mourif4af03e2023-02-11 00:25:24 +0000644 snapshot->cachingHint = getCachingHint();
Lloyd Pique688abd42019-02-15 15:42:24 -0800645
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700646 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700647
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000648 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800649
650 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400651 // Rounded corners no longer force client composition, since we may use a
652 // hole punch so that the layer will appear to have rounded corners.
Alec Mouri994761f2023-08-04 21:50:55 +0000653 if (drawShadows() || snapshot->stretchEffect.hasEffect()) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000654 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800655 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700656 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairc6384702023-07-31 12:22:20 -0700657 snapshot->blurRegions = getBlurRegions();
658 snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400659
660 // Layer framerate is used in caching decisions.
661 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
662 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000663 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000664
665 if (hasBufferOrSidebandStream()) {
666 preparePerFrameBufferCompositionState();
667 } else {
668 preparePerFrameEffectsCompositionState();
669 }
670}
671
672void Layer::preparePerFrameBufferCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000673 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000674 auto* snapshot = editLayerSnapshot();
Alec Mourif4af03e2023-02-11 00:25:24 +0000675 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000676 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
677 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000678 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
679 return;
680 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000681 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000682 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
ramindanib2158ee2023-02-13 20:29:59 -0800683 } else if ((mDrawingState.flags & layer_state_t::eLayerIsRefreshRateIndicator) != 0) {
684 snapshot->compositionType =
685 aidl::android::hardware::graphics::composer3::Composition::REFRESH_RATE_INDICATOR;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000686 } else {
687 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000688 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
689 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000690 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
691 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
692 }
693
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000694 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000695 snapshot->acquireFence = mBufferInfo.mFence;
696 snapshot->frameNumber = mBufferInfo.mFrameNumber;
697 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000698}
699
700void Layer::preparePerFrameEffectsCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000701 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000702 auto* snapshot = editLayerSnapshot();
703 snapshot->color = getColor();
704 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000705 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800706}
707
Lloyd Piquede196652020-01-22 17:29:58 -0800708void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800709 const State& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000710 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000711 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800712
713 // Apply the layer's transform, followed by the display's global transform
714 // Here we're guaranteed that the layer's transform preserves rects
715 Rect win = getCroppedBufferSize(drawingState);
716 // Subtract the transparent region and snap to the bounds
717 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
718 Rect frame(getTransform().transform(bounds));
719
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000720 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800721}
722
Lloyd Piquea83776c2019-01-29 18:42:32 -0800723const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700724 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800725}
726
Mathias Agopian13127d82013-03-05 17:47:11 -0800727// ---------------------------------------------------------------------------
728// drawing...
729// ---------------------------------------------------------------------------
730
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500731aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
732 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700733 const auto outputLayer = findOutputLayerForDisplay(&display);
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000734 return getCompositionType(outputLayer);
735}
736
737aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
738 const compositionengine::OutputLayer* outputLayer) const {
Alec Mouri6b9e9912020-01-21 10:50:24 -0800739 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500740 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800741 }
742 if (outputLayer->getState().hwc) {
743 return (*outputLayer->getState().hwc).hwcCompositionType;
744 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500745 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800746 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800747}
748
Mathias Agopian13127d82013-03-05 17:47:11 -0800749// ----------------------------------------------------------------------------
750// local state
751// ----------------------------------------------------------------------------
752
David Sodman41fdfc92017-11-06 16:09:56 -0800753bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800754 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700755 if (s.flags & layer_state_t::eLayerSecure) {
756 return true;
757 }
758
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000759 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700760 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700761}
762
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100763void Layer::transferAvailableJankData(const std::deque<sp<CallbackHandle>>& handles,
764 std::vector<JankData>& jankData) {
765 if (mPendingJankClassifications.empty() ||
766 !mPendingJankClassifications.front()->getJankType()) {
767 return;
768 }
769
770 bool includeJankData = false;
771 for (const auto& handle : handles) {
772 for (const auto& cb : handle->callbackIds) {
773 if (cb.includeJankData) {
774 includeJankData = true;
775 break;
776 }
777 }
778
779 if (includeJankData) {
780 jankData.reserve(mPendingJankClassifications.size());
781 break;
782 }
783 }
784
785 while (!mPendingJankClassifications.empty() &&
786 mPendingJankClassifications.front()->getJankType()) {
787 if (includeJankData) {
788 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
789 mPendingJankClassifications.front();
Pascal Muetschardac7bcd92023-10-03 15:05:36 +0200790 jankData.emplace_back(JankData(surfaceFrame->getToken(),
791 surfaceFrame->getJankType().value(),
792 surfaceFrame->getRenderRate().getPeriodNsecs()));
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100793 }
794 mPendingJankClassifications.pop_front();
795 }
796}
797
Mathias Agopian13127d82013-03-05 17:47:11 -0800798// ----------------------------------------------------------------------------
799// transaction
800// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800801
Vishnu Naira156f482023-02-22 00:23:38 +0000802uint32_t Layer::doTransaction(uint32_t flags) {
Marissa Wall61c58622018-07-18 10:12:20 -0700803 ATRACE_CALL();
804
Robert Carr0758e5d2021-03-11 22:15:04 -0800805 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700806 mDrawingStateModified = mDrawingState.modified;
807 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700808
Alec Mourib416efd2018-09-06 21:01:59 +0000809 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700810
Robert Carr6a160312021-05-17 12:08:20 -0700811 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800812 // invalidate and recompute the visible regions if needed
813 flags |= Layer::eVisibleRegion;
814 }
815
Robert Carr6a160312021-05-17 12:08:20 -0700816 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800817 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000818 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800819 flags |= eVisibleRegion;
820 this->contentDirty = true;
821
822 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700823 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800824 }
825
Arthur Hung9ed43392022-05-27 06:31:57 +0000826 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
827 mFlinger->mUpdateInputInfo = true;
828 }
829
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700830 commitTransaction();
Robert Carra1257842020-01-31 13:48:28 -0800831
Mathias Agopian13127d82013-03-05 17:47:11 -0800832 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800833}
834
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700835void Layer::commitTransaction() {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000836 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
837 // bufferSurfaceFrameTX will be presented in latchBuffer.
838 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
839 if (surfaceFrame->getPresentState() != PresentState::Presented) {
840 // With applyPendingStates, we could end up having presented surfaceframes from previous
841 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800842 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000843 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
844 }
845 }
Robert Carr6a160312021-05-17 12:08:20 -0700846 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700847}
848
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700849uint32_t Layer::clearTransactionFlags(uint32_t mask) {
850 const auto flags = mTransactionFlags & mask;
851 mTransactionFlags &= ~mask;
852 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800853}
854
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700855void Layer::setTransactionFlags(uint32_t mask) {
856 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800857}
858
Robert Carr1f0a16a2016-10-24 16:27:39 -0700859bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
860 ssize_t idx = mCurrentChildren.indexOf(childLayer);
861 if (idx < 0) {
862 return false;
863 }
864 if (childLayer->setLayer(z)) {
865 mCurrentChildren.removeAt(idx);
866 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800867 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700868 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800869 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700870}
871
Robert Carr503c7042017-09-27 15:06:08 -0700872bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
873 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
874 ssize_t idx = mCurrentChildren.indexOf(childLayer);
875 if (idx < 0) {
876 return false;
877 }
878 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
879 mCurrentChildren.removeAt(idx);
880 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800881 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700882 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800883 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700884}
885
Robert Carrae060832016-11-28 10:51:00 -0800886bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700887 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
888 mDrawingState.sequence++;
889 mDrawingState.z = z;
890 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700891
Robert Carra70e91c2021-06-11 13:59:52 -0700892 mFlinger->mSomeChildrenChanged = true;
893
Robert Carrdb66e622017-04-10 16:55:57 -0700894 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700895 if (mDrawingState.zOrderRelativeOf != nullptr) {
896 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700897 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700898 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700899 }
chaviw606e5cf2019-03-01 10:12:10 -0800900 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700901 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800902 setTransactionFlags(eTransactionNeeded);
903 return true;
904}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700905
Robert Carrdb66e622017-04-10 16:55:57 -0700906void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700907 mDrawingState.zOrderRelatives.remove(relative);
908 mDrawingState.sequence++;
909 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700910 setTransactionFlags(eTransactionNeeded);
911}
912
913void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700914 mDrawingState.zOrderRelatives.add(relative);
915 mDrawingState.modified = true;
916 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700917 setTransactionFlags(eTransactionNeeded);
918}
919
chaviw606e5cf2019-03-01 10:12:10 -0800920void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700921 mDrawingState.zOrderRelativeOf = relativeOf;
922 mDrawingState.sequence++;
923 mDrawingState.modified = true;
924 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700925
chaviw606e5cf2019-03-01 10:12:10 -0800926 setTransactionFlags(eTransactionNeeded);
927}
928
Robert Carr503d2bd2017-12-04 15:49:47 -0800929bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000930 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700931 if (relative == nullptr) {
932 return false;
933 }
934
Robert Carr6a160312021-05-17 12:08:20 -0700935 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
936 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800937 return false;
938 }
939
Robert Carr88b85e12022-03-21 15:47:35 -0700940 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
941 (relative->mDrawingState.zOrderRelativeOf == this)) {
942 ALOGE("Detected relative layer loop between %s and %s",
943 mName.c_str(), relative->mName.c_str());
944 ALOGE("Ignoring new call to set relative layer");
945 return false;
946 }
947
Robert Carra70e91c2021-06-11 13:59:52 -0700948 mFlinger->mSomeChildrenChanged = true;
949
Robert Carr6a160312021-05-17 12:08:20 -0700950 mDrawingState.sequence++;
951 mDrawingState.modified = true;
952 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700953
Robert Carr6a160312021-05-17 12:08:20 -0700954 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700955 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700956 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700957 }
chaviw606e5cf2019-03-01 10:12:10 -0800958 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700959 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700960
961 setTransactionFlags(eTransactionNeeded);
962
963 return true;
964}
965
Winson Chunga30f7c92021-06-29 15:42:56 -0700966bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
967 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
968 mDrawingState.isTrustedOverlay = isTrustedOverlay;
969 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000970 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700971 setTransactionFlags(eTransactionNeeded);
972 return true;
973}
974
975bool Layer::isTrustedOverlay() const {
976 if (getDrawingState().isTrustedOverlay) {
977 return true;
978 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000979 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700980 return (p != nullptr) && p->isTrustedOverlay();
981}
982
Dan Stoza9e56aa02015-11-02 13:00:03 -0800983bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700984 if (mDrawingState.color.a == alpha) return false;
985 mDrawingState.sequence++;
986 mDrawingState.color.a = alpha;
987 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800988 setTransactionFlags(eTransactionNeeded);
989 return true;
990}
chaviw13fdc492017-06-27 12:40:18 -0700991
Valerie Haudd0b7572019-01-29 14:59:27 -0800992bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700993 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700994 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800995 }
Robert Carr6a160312021-05-17 12:08:20 -0700996 mDrawingState.sequence++;
997 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -0800998 setTransactionFlags(eTransactionNeeded);
999
Robert Carr6a160312021-05-17 12:08:20 -07001000 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -08001001 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -08001002 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001003 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -07001004 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Kean Mariotti4ba343c2023-04-19 13:31:02 +00001005 surfaceflinger::LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
1006 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -07001007
Valerie Haudd0b7572019-01-29 14:59:27 -08001008 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -07001009 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -08001010 mFlinger->mLayersAdded = true;
1011 // set up SF to handle added color layer
1012 if (isRemovedFromCurrentState()) {
Josh Gao194ff392022-09-08 16:19:29 -07001013 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001014 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001015 }
1016 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001017 } else if (mDrawingState.bgColorLayer && alpha == 0) {
Josh Gao194ff392022-09-08 16:19:29 -07001018 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001019 mDrawingState.bgColorLayer->reparent(nullptr);
1020 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001021 return true;
1022 }
1023
Robert Carr6a160312021-05-17 12:08:20 -07001024 mDrawingState.bgColorLayer->setColor(color);
1025 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1026 mDrawingState.bgColorLayer->setAlpha(alpha);
1027 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001028
chaviw13fdc492017-06-27 12:40:18 -07001029 return true;
1030}
1031
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001032bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001033 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001034
Robert Carr6a160312021-05-17 12:08:20 -07001035 mDrawingState.sequence++;
1036 mDrawingState.cornerRadius = cornerRadius;
1037 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001038 setTransactionFlags(eTransactionNeeded);
1039 return true;
1040}
1041
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001042bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001043 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001044 // If we start or stop drawing blur then the layer's visibility state may change so increment
1045 // the magic sequence number.
1046 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1047 mDrawingState.sequence++;
1048 }
Robert Carr6a160312021-05-17 12:08:20 -07001049 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1050 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001051 setTransactionFlags(eTransactionNeeded);
1052 return true;
1053}
Marissa Wall61c58622018-07-18 10:12:20 -07001054
Mathias Agopian13127d82013-03-05 17:47:11 -08001055bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001056 mDrawingState.sequence++;
1057 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001058 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001059 setTransactionFlags(eTransactionNeeded);
1060 return true;
1061}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001062
Lucas Dupinc3800b82020-10-02 16:24:48 -07001063bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001064 // If we start or stop drawing blur then the layer's visibility state may change so increment
1065 // the magic sequence number.
1066 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1067 mDrawingState.sequence++;
1068 }
Robert Carr6a160312021-05-17 12:08:20 -07001069 mDrawingState.blurRegions = blurRegions;
1070 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001071 setTransactionFlags(eTransactionNeeded);
1072 return true;
1073}
1074
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001075bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001076 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1077 if (mDrawingState.flags == newFlags) return false;
1078 mDrawingState.sequence++;
1079 mDrawingState.flags = newFlags;
1080 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001081 setTransactionFlags(eTransactionNeeded);
1082 return true;
1083}
Robert Carr99e27f02016-06-16 15:18:02 -07001084
chaviw25714502021-02-11 10:01:08 -08001085bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001086 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001087 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001088 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001089
Robert Carr6a160312021-05-17 12:08:20 -07001090 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001091 setTransactionFlags(eTransactionNeeded);
1092 return true;
1093}
Robert Carr8d5227b2017-03-16 15:41:03 -07001094
Evan Roskyef876c92019-01-25 17:46:06 -08001095bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001096 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1097 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001098 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001099 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001100}
1101
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001102bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001103 if (mDrawingState.layerStack == layerStack) return false;
1104 mDrawingState.sequence++;
1105 mDrawingState.layerStack = layerStack;
1106 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001107 setTransactionFlags(eTransactionNeeded);
1108 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001109}
1110
Peiyong Linc502cb72019-03-01 15:00:23 -08001111bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001112 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001113 return false;
1114 }
Robert Carr6a160312021-05-17 12:08:20 -07001115 mDrawingState.sequence++;
1116 mDrawingState.colorSpaceAgnostic = agnostic;
1117 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001118 setTransactionFlags(eTransactionNeeded);
1119 return true;
1120}
1121
Sally Qi81d95e62022-03-21 19:41:33 -07001122bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1123 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1124
1125 mDrawingState.sequence++;
1126 mDrawingState.dimmingEnabled = dimmingEnabled;
1127 mDrawingState.modified = true;
1128 setTransactionFlags(eTransactionNeeded);
1129 return true;
1130}
1131
Ana Krulecc84d09b2019-11-02 23:10:29 +01001132bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001133 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1134 mDrawingState.frameRateSelectionPriority = priority;
1135 mDrawingState.sequence++;
1136 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001137 setTransactionFlags(eTransactionNeeded);
1138 return true;
1139}
1140
1141int32_t Layer::getFrameRateSelectionPriority() const {
1142 // Check if layer has priority set.
1143 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1144 return mDrawingState.frameRateSelectionPriority;
1145 }
1146 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001147 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001148 if (parent != nullptr) {
1149 return parent->getFrameRateSelectionPriority();
1150 }
1151
1152 return Layer::PRIORITY_UNSET;
1153}
1154
Andy Labrada096227e2022-06-15 16:58:11 +00001155bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1156 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1157 mDrawingState.defaultFrameRateCompatibility = compatibility;
1158 mDrawingState.modified = true;
Vishnu Nair80e8cfe2023-09-29 17:03:45 -07001159 mFlinger->mScheduler->setDefaultFrameRateCompatibility(sequence, compatibility);
Andy Labrada096227e2022-06-15 16:58:11 +00001160 setTransactionFlags(eTransactionNeeded);
1161 return true;
1162}
1163
Vishnu Nair3fbe3262023-09-29 17:07:00 -07001164scheduler::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
Andy Labrada096227e2022-06-15 16:58:11 +00001165 return mDrawingState.defaultFrameRateCompatibility;
1166}
1167
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001168bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1169 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1170};
1171
Vishnu Nair73908d12022-10-24 21:46:42 -07001172ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1173 bool useDrawing = state == LayerVector::StateSet::Drawing;
1174 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1175 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001176 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001177 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001178 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001179}
1180
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001181bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001182 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001183 return false;
1184 }
1185
Robert Carr6a160312021-05-17 12:08:20 -07001186 mDrawingState.sequence++;
1187 mDrawingState.shadowRadius = shadowRadius;
1188 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001189 setTransactionFlags(eTransactionNeeded);
1190 return true;
1191}
1192
Vishnu Nair6213bd92020-05-08 17:42:25 -07001193bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001194 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001195 return false;
1196 }
1197
Robert Carr6a160312021-05-17 12:08:20 -07001198 mDrawingState.sequence++;
1199 mDrawingState.fixedTransformHint = fixedTransformHint;
1200 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001201 setTransactionFlags(eTransactionNeeded);
1202 return true;
1203}
1204
John Reckcdb4ed72021-02-04 13:39:33 -05001205bool Layer::setStretchEffect(const StretchEffect& effect) {
1206 StretchEffect temp = effect;
1207 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001208 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001209 return false;
1210 }
Robert Carr6a160312021-05-17 12:08:20 -07001211 mDrawingState.sequence++;
1212 mDrawingState.stretchEffect = temp;
1213 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001214 setTransactionFlags(eTransactionNeeded);
1215 return true;
1216}
1217
John Reckc00c6692021-02-16 11:37:33 -05001218StretchEffect Layer::getStretchEffect() const {
1219 if (mDrawingState.stretchEffect.hasEffect()) {
1220 return mDrawingState.stretchEffect;
1221 }
1222
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001223 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001224 if (parent != nullptr) {
1225 auto effect = parent->getStretchEffect();
1226 if (effect.hasEffect()) {
1227 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1228 return effect;
1229 }
1230 }
1231 return StretchEffect{};
1232}
1233
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001234bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1235 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001236 return false;
1237 }
1238 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001239 mBorderWidth = width;
1240 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001241 return true;
1242}
1243
1244bool Layer::isBorderEnabled() {
1245 return mBorderEnabled;
1246}
1247
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001248float Layer::getBorderWidth() {
1249 return mBorderWidth;
1250}
1251
1252const half4& Layer::getBorderColor() {
1253 return mBorderColor;
1254}
1255
Rachel Lee0faad6c2023-09-08 13:34:34 -07001256bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool overrideChildren,
1257 bool* transactionNeeded) {
1258 // Gets the frame rate to propagate to children.
Ady Abrahama850c182021-08-04 13:04:37 -07001259 const auto frameRate = [&] {
Rachel Lee0faad6c2023-09-08 13:34:34 -07001260 if (overrideChildren && parentFrameRate.isValid()) {
1261 return parentFrameRate;
1262 }
1263
Rachel Leece6e0042023-06-27 11:22:54 -07001264 if (mDrawingState.frameRate.isValid()) {
Ady Abrahama850c182021-08-04 13:04:37 -07001265 return mDrawingState.frameRate;
1266 }
1267
1268 return parentFrameRate;
1269 }();
1270
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001271 auto now = systemTime();
1272 *transactionNeeded |= setFrameRateForLayerTreeLegacy(frameRate, now);
Ady Abrahama850c182021-08-04 13:04:37 -07001273
1274 // The frame rate is propagated to the children
1275 bool childrenHaveFrameRate = false;
1276 for (const sp<Layer>& child : mCurrentChildren) {
1277 childrenHaveFrameRate |=
Rachel Lee0faad6c2023-09-08 13:34:34 -07001278 child->propagateFrameRateForLayerTree(frameRate,
1279 overrideChildren ||
1280 shouldOverrideChildrenFrameRate(),
1281 transactionNeeded);
Ady Abrahama850c182021-08-04 13:04:37 -07001282 }
1283
Rachel Leece6e0042023-06-27 11:22:54 -07001284 // If we don't have a valid frame rate specification, but the children do, we set this
Ady Abrahama850c182021-08-04 13:04:37 -07001285 // layer as NoVote to allow the children to control the refresh rate
Rachel Leece6e0042023-06-27 11:22:54 -07001286 if (!frameRate.isValid() && childrenHaveFrameRate) {
Ady Abrahama850c182021-08-04 13:04:37 -07001287 *transactionNeeded |=
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001288 setFrameRateForLayerTreeLegacy(FrameRate(Fps(), FrameRateCompatibility::NoVote),
1289 now);
Ady Abrahama850c182021-08-04 13:04:37 -07001290 }
1291
Rachel Leece6e0042023-06-27 11:22:54 -07001292 // We return whether this layer or its children has a vote. We ignore ExactOrMultiple votes for
Ady Abrahama850c182021-08-04 13:04:37 -07001293 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001294 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001295 const auto layerVotedWithDefaultCompatibility =
Rachel Leece6e0042023-06-27 11:22:54 -07001296 frameRate.vote.rate.isValid() && frameRate.vote.type == FrameRateCompatibility::Default;
1297 const auto layerVotedWithNoVote = frameRate.vote.type == FrameRateCompatibility::NoVote;
1298 const auto layerVotedWithCategory = frameRate.category != FrameRateCategory::Default;
Ady Abrahama850c182021-08-04 13:04:37 -07001299 const auto layerVotedWithExactCompatibility =
Rachel Leece6e0042023-06-27 11:22:54 -07001300 frameRate.vote.rate.isValid() && frameRate.vote.type == FrameRateCompatibility::Exact;
1301 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote || layerVotedWithCategory ||
Ady Abrahama850c182021-08-04 13:04:37 -07001302 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1303}
1304
Ady Abraham60e42ea2020-03-09 19:17:31 -07001305void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001306 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001307 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001308 while (auto parent = layer->getParent()) {
1309 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001310 }
Ady Abrahama850c182021-08-04 13:04:37 -07001311 return layer;
1312 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001313
Ady Abraham60e42ea2020-03-09 19:17:31 -07001314 bool transactionNeeded = false;
Rachel Lee0faad6c2023-09-08 13:34:34 -07001315 root->propagateFrameRateForLayerTree({}, false, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001316
Ady Abrahama850c182021-08-04 13:04:37 -07001317 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001318 if (transactionNeeded) {
1319 mFlinger->setTransactionFlags(eTraversalNeeded);
1320 }
1321}
1322
Rachel Leece6e0042023-06-27 11:22:54 -07001323bool Layer::setFrameRate(FrameRate::FrameRateVote frameRateVote) {
1324 if (mDrawingState.frameRate.vote == frameRateVote) {
Steven Thomas3172e202020-01-06 19:25:30 -08001325 return false;
1326 }
1327
Robert Carr6a160312021-05-17 12:08:20 -07001328 mDrawingState.sequence++;
Rachel Leece6e0042023-06-27 11:22:54 -07001329 mDrawingState.frameRate.vote = frameRateVote;
1330 mDrawingState.modified = true;
1331
1332 updateTreeHasFrameRateVote();
1333
1334 setTransactionFlags(eTransactionNeeded);
1335 return true;
1336}
1337
Rachel Lee67afbea2023-09-28 15:35:07 -07001338bool Layer::setFrameRateCategory(FrameRateCategory category, bool smoothSwitchOnly) {
1339 if (mDrawingState.frameRate.category == category &&
1340 mDrawingState.frameRate.categorySmoothSwitchOnly == smoothSwitchOnly) {
Rachel Leece6e0042023-06-27 11:22:54 -07001341 return false;
1342 }
1343
1344 mDrawingState.sequence++;
1345 mDrawingState.frameRate.category = category;
Rachel Lee67afbea2023-09-28 15:35:07 -07001346 mDrawingState.frameRate.categorySmoothSwitchOnly = smoothSwitchOnly;
Robert Carr6a160312021-05-17 12:08:20 -07001347 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001348
1349 updateTreeHasFrameRateVote();
1350
Steven Thomas3172e202020-01-06 19:25:30 -08001351 setTransactionFlags(eTransactionNeeded);
1352 return true;
1353}
1354
Rachel Lee58cc90d2023-09-05 18:50:20 -07001355bool Layer::setFrameRateSelectionStrategy(FrameRateSelectionStrategy strategy) {
1356 if (mDrawingState.frameRateSelectionStrategy == strategy) return false;
1357 mDrawingState.frameRateSelectionStrategy = strategy;
1358 mDrawingState.sequence++;
1359 mDrawingState.modified = true;
Rachel Leed7479502023-09-25 17:02:35 -07001360
1361 updateTreeHasFrameRateVote();
Rachel Lee58cc90d2023-09-05 18:50:20 -07001362 setTransactionFlags(eTransactionNeeded);
1363 return true;
1364}
1365
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001366void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1367 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001368 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001369
1370 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1371 // there are two transactions with the same token, the first one without a buffer and the
1372 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1373 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001374 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1375 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001376 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001377 mDrawingState.bufferSurfaceFrameTX = it->second;
1378 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1379 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1380 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001381 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001382 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001383 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1384 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001385
1386 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001387}
1388
1389void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1390 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001391 mDrawingState.frameTimelineInfo = info;
1392 mDrawingState.postTime = postTime;
1393 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001394 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001395
Robert Carr6a160312021-05-17 12:08:20 -07001396 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001397 bufferSurfaceFrameTX != nullptr) {
1398 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1399 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1400 // being used for BufferSurfaceFrame, don't create a new one.
1401 return;
1402 }
1403 }
1404 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1405 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1406 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001407 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1408 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001409 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001410 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001411 } else {
1412 if (it->second->getPresentState() == PresentState::Presented) {
1413 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1414 // have been from previous vsync.
1415 it->second = createSurfaceFrameForTransaction(info, postTime);
1416 }
1417 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001418
1419 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001420}
1421
1422void Layer::addSurfaceFrameDroppedForBuffer(
Ady Abraham5a3e3562023-06-07 10:32:08 -07001423 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t dropTime) {
1424 surfaceFrame->setDropTime(dropTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001425 surfaceFrame->setPresentState(PresentState::Dropped);
1426 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1427}
1428
1429void Layer::addSurfaceFramePresentedForBuffer(
1430 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1431 nsecs_t currentLatchTime) {
1432 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1433 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1434 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +00001435 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001436}
1437
1438std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1439 const FrameTimelineInfo& info, nsecs_t postTime) {
1440 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001441 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1442 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001443 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001444 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001445 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001446 // For Transactions, the post time is considered to be both queue and acquire fence time.
1447 surfaceFrame->setActualQueueTime(postTime);
1448 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001449 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1450 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001451 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001452 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001453 onSurfaceFrameCreated(surfaceFrame);
1454 return surfaceFrame;
1455}
1456
1457std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1458 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1459 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001460 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001461 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001462 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001463 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001464 // For buffers, acquire fence time will set during latch.
1465 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001466 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1467 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001468 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001469 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001470 onSurfaceFrameCreated(surfaceFrame);
1471 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001472}
1473
Ady Abraham5a3e3562023-06-07 10:32:08 -07001474void Layer::setFrameTimelineVsyncForSkippedFrames(const FrameTimelineInfo& info, nsecs_t postTime,
1475 std::string debugName) {
1476 if (info.skippedFrameVsyncId == FrameTimelineInfo::INVALID_VSYNC_ID) {
1477 return;
1478 }
1479
1480 FrameTimelineInfo skippedFrameTimelineInfo = info;
1481 skippedFrameTimelineInfo.vsyncId = info.skippedFrameVsyncId;
1482
1483 auto surfaceFrame =
1484 mFlinger->mFrameTimeline->createSurfaceFrameForToken(skippedFrameTimelineInfo,
1485 mOwnerPid, mOwnerUid,
1486 getSequence(), mName, debugName,
1487 /*isBuffer*/ false, getGameMode());
1488 surfaceFrame->setActualStartTime(skippedFrameTimelineInfo.skippedFrameStartTimeNanos);
1489 // For Transactions, the post time is considered to be both queue and acquire fence time.
1490 surfaceFrame->setActualQueueTime(postTime);
1491 surfaceFrame->setAcquireFenceTime(postTime);
1492 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1493 if (fps) {
1494 surfaceFrame->setRenderRate(*fps);
1495 }
1496 onSurfaceFrameCreated(surfaceFrame);
1497 addSurfaceFrameDroppedForBuffer(surfaceFrame, postTime);
1498}
1499
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001500bool Layer::setFrameRateForLayerTreeLegacy(FrameRate frameRate, nsecs_t now) {
Ady Abrahama850c182021-08-04 13:04:37 -07001501 if (mDrawingState.frameRateForLayerTree == frameRate) {
1502 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001503 }
1504
Ady Abrahama850c182021-08-04 13:04:37 -07001505 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001506
Ady Abrahama850c182021-08-04 13:04:37 -07001507 // TODO(b/195668952): we probably don't need to dirty visible regions here
1508 // or even store frameRateForLayerTree in mDrawingState
1509 mDrawingState.sequence++;
1510 mDrawingState.modified = true;
1511 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001512
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001513 mFlinger->mScheduler
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001514 ->recordLayerHistory(sequence, getLayerProps(), now, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001515 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
1516 return true;
1517}
Ady Abrahama850c182021-08-04 13:04:37 -07001518
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001519bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps,
1520 nsecs_t now) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001521 if (mDrawingState.frameRateForLayerTree == frameRate) {
1522 return false;
1523 }
1524
1525 mDrawingState.frameRateForLayerTree = frameRate;
1526 mFlinger->mScheduler
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001527 ->recordLayerHistory(sequence, layerProps, now, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001528 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001529 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001530}
1531
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001532Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1533 return getDrawingState().frameRateForLayerTree;
1534}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001535
Robert Carr1f0a16a2016-10-24 16:27:39 -07001536bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001537 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001538 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001539 if (parent != nullptr && parent->isHiddenByPolicy()) {
1540 return true;
1541 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001542 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1543 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1544 if (zOrderRelativeOf != nullptr) {
1545 if (zOrderRelativeOf->isHiddenByPolicy()) {
1546 return true;
1547 }
1548 }
1549 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001550 if (CC_UNLIKELY(!isTransformValid())) {
1551 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1552 return true;
1553 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001554 return s.flags & layer_state_t::eLayerHidden;
1555}
1556
David Sodman41fdfc92017-11-06 16:09:56 -08001557uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001558 // TODO: should we do something special if mSecure is set?
1559 if (mProtectedByApp) {
1560 // need a hardware-protected path to external video sink
1561 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001562 }
Riley Andrews03414a12014-07-01 14:22:59 -07001563 if (mPotentialCursor) {
1564 usage |= GraphicBuffer::USAGE_CURSOR;
1565 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001566 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001567 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001568}
1569
Vishnu Nair71fcf912022-10-18 09:14:20 -07001570void Layer::skipReportingTransformHint() {
1571 mSkipReportingTransformHint = true;
1572}
1573
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001574void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1575 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1576 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001577 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001578
Vishnu Nairb76d99a2023-03-19 18:22:31 -07001579 setTransformHintLegacy(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001580}
1581
Mathias Agopian13127d82013-03-05 17:47:11 -08001582// ----------------------------------------------------------------------------
1583// debugging
1584// ----------------------------------------------------------------------------
1585
Marissa Wall61c58622018-07-18 10:12:20 -07001586// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001587gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001588 using namespace std::string_literals;
1589
Huihong Luo05539a12022-02-23 10:29:40 -08001590 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001591 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001592 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001593 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001594 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001595 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001596
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001597 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001598 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001599 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001600 info.mX = ds.transform.tx();
1601 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001602 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001603 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001604 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001605 info.mFlags = ds.flags;
1606 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001607 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001608 info.mMatrix[0][0] = ds.transform[0][0];
1609 info.mMatrix[0][1] = ds.transform[0][1];
1610 info.mMatrix[1][0] = ds.transform[1][0];
1611 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001612 {
chaviwd62d3062019-09-04 14:48:02 -07001613 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001614 if (buffer != 0) {
1615 info.mActiveBufferWidth = buffer->getWidth();
1616 info.mActiveBufferHeight = buffer->getHeight();
1617 info.mActiveBufferStride = buffer->getStride();
1618 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001619 } else {
1620 info.mActiveBufferWidth = 0;
1621 info.mActiveBufferHeight = 0;
1622 info.mActiveBufferStride = 0;
1623 info.mActiveBufferFormat = 0;
1624 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001625 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001626 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001627 info.mIsOpaque = isOpaque(ds);
1628 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001629 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001630 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001631}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001632
Yiwei Zhang5434a782018-12-05 18:06:32 -08001633void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001634 result.append(kDumpTableRowLength, '-');
1635 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001636 result.append(" Layer name\n");
1637 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001638 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001639 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001640 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001641 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001642 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001643 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1644 result.append(kDumpTableRowLength, '-');
1645 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001646}
1647
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001648void Layer::miniDumpLegacy(std::string& result, const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001649 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001650 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001651 return;
1652 }
1653
Yiwei Zhang5434a782018-12-05 18:06:32 -08001654 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001655 if (mName.length() > 77) {
1656 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001657 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001658 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001659 shortened.append(mName, mName.length() - 36);
1660 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001661 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001662 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001663 }
1664
Yiwei Zhang5434a782018-12-05 18:06:32 -08001665 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001666
Alec Mourib416efd2018-09-06 21:01:59 +00001667 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001668 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001669
Chia-I Wu1e043612018-03-01 09:45:09 -08001670 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001671 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001672 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001673 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001674 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001675 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001676 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001677 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1678 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001679 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001680 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001681 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001682 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001683 const auto frameRate = getFrameRateForLayerTree();
Rachel Leece6e0042023-06-27 11:22:54 -07001684 if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
1685 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.vote.rate).c_str(),
1686 ftl::enum_string(frameRate.vote.type).c_str(),
1687 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001688 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001689 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001690 }
Dan Stozae22aec72016-08-01 13:20:59 -07001691
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001692 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1693 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1694
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001695 result.append(kDumpTableRowLength, '-');
1696 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001697}
Dan Stozae22aec72016-08-01 13:20:59 -07001698
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001699void Layer::miniDump(std::string& result, const frontend::LayerSnapshot& snapshot,
1700 const DisplayDevice& display) const {
1701 const auto outputLayer = findOutputLayerForDisplay(&display, snapshot.path);
1702 if (!outputLayer) {
1703 return;
1704 }
1705
1706 StringAppendF(&result, " %s\n", snapshot.debugName.c_str());
1707 StringAppendF(&result, " %10zu | ", snapshot.globalZ);
1708 StringAppendF(&result, " %10d | ",
1709 snapshot.layerMetadata.getInt32(gui::METADATA_WINDOW_TYPE, 0));
1710 StringAppendF(&result, "%10s | ", toString(getCompositionType(outputLayer)).c_str());
1711 const auto& outputLayerState = outputLayer->getState();
1712 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1713 const Rect& frame = outputLayerState.displayFrame;
1714 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
1715 const FloatRect& crop = outputLayerState.sourceCrop;
1716 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
1717 crop.bottom);
1718 const auto frameRate = snapshot.frameRate;
Rachel Leece6e0042023-06-27 11:22:54 -07001719 if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
1720 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.vote.rate).c_str(),
1721 ftl::enum_string(frameRate.vote.type).c_str(),
1722 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001723 } else {
1724 result.append(41, ' ');
1725 }
1726
1727 const auto focused = isLayerFocusedBasedOnPriority(snapshot.frameRateSelectionPriority);
1728 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1729
1730 result.append(kDumpTableRowLength, '-');
1731 result.append("\n");
1732}
1733
Yiwei Zhang5434a782018-12-05 18:06:32 -08001734void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001735 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001736}
1737
Svetoslavd85084b2014-03-20 10:28:31 -07001738void Layer::clearFrameStats() {
1739 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001740}
1741
Jamie Gennis6547ff42013-07-16 20:12:42 -07001742void Layer::logFrameStats() {
1743 mFrameTracker.logAndResetStats(mName);
1744}
1745
Svetoslavd85084b2014-03-20 10:28:31 -07001746void Layer::getFrameStats(FrameStats* outStats) const {
1747 mFrameTracker.getStats(outStats);
1748}
1749
Vishnu Nair76554eb2022-12-09 03:38:36 +00001750void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1751 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
Vishnu Nair3be61902023-04-26 19:47:29 -07001752 StringAppendF(&result, "Layer %s%s pid:%d uid:%d%s\n", getName().c_str(), hasBuffer.c_str(),
1753 mOwnerPid, mOwnerUid, isHandleAlive() ? " handleAlive" : "");
Vishnu Nair0f085c62019-08-30 08:49:12 -07001754}
1755
Brian Anderson5ea5e592016-12-01 16:54:33 -08001756void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001757 const int32_t layerId = getSequence();
1758 mFlinger->mTimeStats->onDestroy(layerId);
1759 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001760}
1761
Vishnu Nair787aa782023-03-17 13:46:46 -07001762size_t Layer::getDescendantCount() const {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001763 size_t count = 0;
Vishnu Nair787aa782023-03-17 13:46:46 -07001764 for (const sp<Layer>& child : mDrawingChildren) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001765 count += 1 + child->getChildrenCount();
1766 }
1767 return count;
1768}
1769
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001770void Layer::setGameModeForTree(GameMode gameMode) {
1771 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001772 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1773 gameMode =
1774 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001775 }
1776 setGameMode(gameMode);
1777 for (const sp<Layer>& child : mCurrentChildren) {
1778 child->setGameModeForTree(gameMode);
1779 }
1780}
1781
Robert Carr1f0a16a2016-10-24 16:27:39 -07001782void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001783 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001784 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001785
Robert Carr1f0a16a2016-10-24 16:27:39 -07001786 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001787 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001788 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001789 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001790}
1791
1792ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001793 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001794 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001795
Robert Carr1323c952019-01-28 18:13:27 -08001796 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001797 const auto removeResult = mCurrentChildren.remove(layer);
1798
1799 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001800 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001801 layer->updateTreeHasFrameRateVote();
1802
1803 return removeResult;
1804}
1805
Robert Carr15eae092018-03-23 13:43:53 -07001806void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001807 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001808 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001809 const float parentShadowRadius =
1810 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001811 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001812 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001813 }
1814}
1815
chaviwf1961f72017-09-18 16:41:07 -07001816bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001817 sp<Layer> newParent;
1818 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001819 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001820 if (newParent == nullptr) {
1821 ALOGE("Unable to promote Layer handle");
1822 return false;
1823 }
1824 if (newParent == this) {
1825 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1826 return false;
1827 }
1828 }
1829
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001830 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001831 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001832 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001833 }
1834
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001835 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001836 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001837 if (!newParent->isRemovedFromCurrentState()) {
1838 addToCurrentState();
1839 } else {
1840 onRemovedFromCurrentState();
1841 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001842 } else {
1843 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001844 }
1845
chaviw06178942017-07-27 10:25:59 -07001846 return true;
1847}
1848
Peiyong Lind3788632018-09-18 16:01:31 -07001849bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001850 static const mat4 identityMatrix = mat4();
1851
Robert Carr6a160312021-05-17 12:08:20 -07001852 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001853 return false;
1854 }
Robert Carr6a160312021-05-17 12:08:20 -07001855 ++mDrawingState.sequence;
1856 mDrawingState.colorTransform = matrix;
1857 mDrawingState.hasColorTransform = matrix != identityMatrix;
1858 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001859 setTransactionFlags(eTransactionNeeded);
1860 return true;
1861}
1862
chaviwf66724d2018-11-28 16:35:21 -08001863mat4 Layer::getColorTransform() const {
1864 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001865 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001866 colorTransform = parent->getColorTransform() * colorTransform;
1867 }
1868 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001869}
1870
1871bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001872 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001873 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001874 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1875 }
1876 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001877}
1878
Chia-I Wu11481472018-05-04 10:43:19 -07001879bool Layer::isLegacyDataSpace() const {
1880 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001881 return !(getDataSpace() &
1882 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1883 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001884}
1885
Robert Carr1f0a16a2016-10-24 16:27:39 -07001886void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001887 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001888}
1889
Robert Carr6a160312021-05-17 12:08:20 -07001890int32_t Layer::getZ(LayerVector::StateSet) const {
1891 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001892}
1893
Robert Carr1c5481e2019-07-01 14:42:27 -07001894bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001895 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001896 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001897 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001898}
1899
David Sodman41fdfc92017-11-06 16:09:56 -08001900__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001901 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001902 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1903 "makeTraversalList received invalid stateSet");
1904 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1905 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001906 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001907
Robert Carr29abff82017-12-04 13:51:20 -08001908 if (state.zOrderRelatives.size() == 0) {
1909 *outSkipRelativeZUsers = true;
1910 return children;
1911 }
1912
chaviwfd462612018-05-31 16:11:27 -07001913 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001914 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001915 sp<Layer> strongRelative = weakRelative.promote();
1916 if (strongRelative != nullptr) {
1917 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001918 }
1919 }
1920
Dan Stoza412903f2017-04-27 13:42:17 -07001921 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001922 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001923 continue;
1924 }
Robert Carrdb66e622017-04-10 16:55:57 -07001925 traverse.add(child);
1926 }
1927
1928 return traverse;
1929}
1930
Robert Carr1f0a16a2016-10-24 16:27:39 -07001931/**
Robert Carrdb66e622017-04-10 16:55:57 -07001932 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001933 */
Dan Stoza412903f2017-04-27 13:42:17 -07001934void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001935 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1936 // produce a new list for traversing, including our relatives, and not including our children
1937 // who are relatives of another surface. In the case that there are no relative Z,
1938 // makeTraversalList returns our children directly to avoid significant overhead.
1939 // However in this case we need to take the responsibility for filtering children which
1940 // are relatives of another surface here.
1941 bool skipRelativeZUsers = false;
1942 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001943
Robert Carr1f0a16a2016-10-24 16:27:39 -07001944 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001945 for (; i < list.size(); i++) {
1946 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001947 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1948 continue;
1949 }
1950
chaviw301b1d82019-11-06 13:15:09 -08001951 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001952 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001953 }
Dan Stoza412903f2017-04-27 13:42:17 -07001954 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001955 }
Robert Carr29abff82017-12-04 13:51:20 -08001956
Dan Stoza412903f2017-04-27 13:42:17 -07001957 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001958 for (; i < list.size(); i++) {
1959 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001960
Robert Carr29abff82017-12-04 13:51:20 -08001961 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1962 continue;
1963 }
Dan Stoza412903f2017-04-27 13:42:17 -07001964 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001965 }
1966}
1967
1968/**
Robert Carrdb66e622017-04-10 16:55:57 -07001969 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001970 */
Dan Stoza412903f2017-04-27 13:42:17 -07001971void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1972 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001973 // See traverseInZOrder for documentation.
1974 bool skipRelativeZUsers = false;
1975 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001976
Robert Carr1f0a16a2016-10-24 16:27:39 -07001977 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001978 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001979 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001980
1981 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1982 continue;
1983 }
1984
chaviw301b1d82019-11-06 13:15:09 -08001985 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001986 break;
1987 }
Dan Stoza412903f2017-04-27 13:42:17 -07001988 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001989 }
Dan Stoza412903f2017-04-27 13:42:17 -07001990 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001991 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001992 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001993
1994 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1995 continue;
1996 }
1997
Dan Stoza412903f2017-04-27 13:42:17 -07001998 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001999 }
2000}
2001
Edgar Arriaga844fa672020-01-16 14:21:42 -08002002void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
2003 visitor(this);
2004 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07002005 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002006 for (const sp<Layer>& child : children) {
2007 child->traverse(state, visitor);
2008 }
2009}
2010
Vishnu Nair787aa782023-03-17 13:46:46 -07002011void Layer::traverseChildren(const LayerVector::Visitor& visitor) {
2012 for (const sp<Layer>& child : mDrawingChildren) {
2013 visitor(child.get());
2014 }
2015}
2016
chaviw4b129c22018-04-09 16:19:43 -07002017LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
2018 const std::vector<Layer*>& layersInTree) {
2019 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2020 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07002021 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2022 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002023 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07002024
chaviwfd462612018-05-31 16:11:27 -07002025 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07002026 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2027 sp<Layer> strongRelative = weakRelative.promote();
2028 // Only add relative layers that are also descendents of the top most parent of the tree.
2029 // If a relative layer is not a descendent, then it should be ignored.
2030 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
2031 traverse.add(strongRelative);
2032 }
2033 }
2034
2035 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07002036 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07002037 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
2038 // descendent of the top most parent of the tree. If it's not a descendent, then just add
2039 // the child here since it won't be added later as a relative.
2040 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
2041 childState.zOrderRelativeOf.promote().get())) {
2042 continue;
2043 }
2044 traverse.add(child);
2045 }
2046
2047 return traverse;
2048}
2049
2050void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
2051 LayerVector::StateSet stateSet,
2052 const LayerVector::Visitor& visitor) {
2053 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07002054
2055 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07002056 for (; i < list.size(); i++) {
2057 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08002058 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07002059 break;
2060 }
chaviw4b129c22018-04-09 16:19:43 -07002061 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002062 }
chaviw4b129c22018-04-09 16:19:43 -07002063
chaviwa76b2712017-09-20 12:02:26 -07002064 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07002065 for (; i < list.size(); i++) {
2066 const auto& relative = list[i];
2067 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002068 }
2069}
2070
chaviw4b129c22018-04-09 16:19:43 -07002071std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
2072 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2073 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2074
2075 std::vector<Layer*> layersInTree = {this};
2076 for (size_t i = 0; i < children.size(); i++) {
2077 const auto& child = children[i];
2078 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
2079 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
2080 }
2081
2082 return layersInTree;
2083}
2084
2085void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
2086 const LayerVector::Visitor& visitor) {
2087 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
2088 std::sort(layersInTree.begin(), layersInTree.end());
2089 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
2090}
2091
Peiyong Linefefaac2018-08-17 12:27:51 -07002092ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08002093 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002094}
2095
Garfield Tan2c1782c2022-02-16 15:25:05 -08002096bool Layer::isTransformValid() const {
2097 float transformDet = getTransform().det();
2098 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
2099}
2100
chaviw13fdc492017-06-27 12:40:18 -07002101half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002102 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002103
chaviw13fdc492017-06-27 12:40:18 -07002104 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2105 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002106}
Robert Carr6452f122017-03-21 10:41:29 -07002107
Vishnu Nair6213bd92020-05-08 17:42:25 -07002108ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07002109 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07002110 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2111 return fixedTransformHint;
2112 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002113 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07002114 if (!p) return fixedTransformHint;
2115 return p->getFixedTransformHint();
2116}
2117
chaviw13fdc492017-06-27 12:40:18 -07002118half4 Layer::getColor() const {
2119 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002120 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002121}
Robert Carr6452f122017-03-21 10:41:29 -07002122
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002123int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002124 if (getDrawingState().backgroundBlurRadius == 0) {
2125 return 0;
2126 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002127
Vishnu Nair29810f72022-07-01 16:38:41 +00002128 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002129 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2130 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002131}
2132
Galia Peychevae0acf382021-04-12 21:22:34 +02002133const std::vector<BlurRegion> Layer::getBlurRegions() const {
2134 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002135 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002136 for (auto& region : regionsCopy) {
2137 region.alpha = region.alpha * layerAlpha;
2138 }
2139 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002140}
2141
Vishnu Naire14c6b32022-08-06 04:20:15 +00002142RoundedCornerState Layer::getRoundedCornerState() const {
Leon Scroggins IIIc1dbfcb2022-03-21 16:48:10 -04002143 // Today's DPUs cannot do rounded corners. If RenderEngine cannot render
2144 // protected content, remove rounded corners from protected content so it
2145 // can be rendered by the DPU.
2146 if (isProtected() && !mFlinger->getRenderEngine().supportsProtectedContent()) {
2147 return {};
2148 }
2149
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002150 // Get parent settings
2151 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002152 const auto& parent = mDrawingParent.promote();
2153 if (parent != nullptr) {
2154 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002155 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002156 ui::Transform t = getActiveTransform(getDrawingState());
2157 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002158 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002159 parentSettings.radius.x *= t.getScaleX();
2160 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002161 }
2162 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002163
2164 // Get layer settings
2165 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002166 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002167 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002168 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002169
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002170 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002171 // If the parent and the layer have rounded corner settings, use the parent settings if the
2172 // parent crop is entirely inside the layer crop.
2173 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2174 if (parentSettings.cropRect.left > layerCropRect.left &&
2175 parentSettings.cropRect.top > layerCropRect.top &&
2176 parentSettings.cropRect.right < layerCropRect.right &&
2177 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2178 return parentSettings;
2179 } else {
2180 return layerSettings;
2181 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002182 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002183 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002184 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002185 return parentSettings;
2186 }
2187 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002188}
2189
Robert Carr88b85e12022-03-21 15:47:35 -07002190bool Layer::findInHierarchy(const sp<Layer>& l) {
2191 if (l == this) {
2192 return true;
2193 }
2194 for (auto& child : mDrawingChildren) {
2195 if (child->findInHierarchy(l)) {
2196 return true;
2197 }
2198 }
2199 return false;
2200}
2201
Robert Carr1f0a16a2016-10-24 16:27:39 -07002202void Layer::commitChildList() {
2203 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2204 const auto& child = mCurrentChildren[i];
2205 child->commitChildList();
2206 }
2207 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002208 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002209 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2210 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2211 if (zOrderRelativeOf == nullptr) return;
2212 if (findInHierarchy(zOrderRelativeOf)) {
2213 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2214 zOrderRelativeOf->mName.c_str());
2215 ALOGE("Severing rel Z loop, potentially dangerous");
2216 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002217 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002218 }
2219 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002220}
2221
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002222
chaviw3277faf2021-05-19 16:45:23 -05002223void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002224 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002225 mDrawingState.touchableRegionCrop =
2226 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002227 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002228 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002229 setTransactionFlags(eTransactionNeeded);
2230}
2231
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002232perfetto::protos::LayerProto* Layer::writeToProto(perfetto::protos::LayersProto& layersProto,
2233 uint32_t traceFlags) {
2234 perfetto::protos::LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002235 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002236 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2237
Vishnu Nair00b90132021-11-05 14:03:40 -07002238 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Vishnu Nair2f65e972023-04-04 16:36:28 +00002239 ui::LayerStack layerStack =
2240 (mSnapshot) ? mSnapshot->outputFilter.layerStack : ui::INVALID_LAYER_STACK;
2241 writeCompositionStateToProto(layerProto, layerStack);
Alec Mouri6b9e9912020-01-21 10:50:24 -08002242 }
2243
chaviw08f3cb22020-01-13 13:17:21 -08002244 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002245 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002246 }
chaviw6d89e2d2020-01-14 14:42:01 -08002247
2248 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002249}
2250
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002251void Layer::writeCompositionStateToProto(perfetto::protos::LayerProto* layerProto,
2252 ui::LayerStack layerStack) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002253 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002254 ftl::FakeGuard mainThreadGuard(kMainThreadContext);
Vishnu Nairea6ff812023-02-27 17:41:39 +00002255
2256 // Only populate for the primary display.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002257 if (const auto display = mFlinger->getDisplayFromLayerStack(layerStack)) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002258 const auto compositionType = getCompositionType(*display);
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002259 layerProto->set_hwc_composition_type(
2260 static_cast<perfetto::protos::HwcCompositionType>(compositionType));
Vishnu Nair2f65e972023-04-04 16:36:28 +00002261 LayerProtoHelper::writeToProto(getVisibleRegion(display),
Vishnu Nairea6ff812023-02-27 17:41:39 +00002262 [&]() { return layerProto->mutable_visible_region(); });
2263 }
2264}
2265
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002266void Layer::writeToProtoDrawingState(perfetto::protos::LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002267 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002268 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002269 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002270 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002271 [&]() { return layerInfo->mutable_active_buffer(); });
2272 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2273 layerInfo->mutable_buffer_transform());
2274 }
2275 layerInfo->set_invalidate(contentDirty);
2276 layerInfo->set_is_protected(isProtected());
2277 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2278 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002279 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002280 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002281 layerInfo->set_corner_radius(
2282 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002283 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2284 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2285 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2286 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2287 [&]() { return layerInfo->mutable_position(); });
2288 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002289 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2290 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002291
Vishnu Nair00b90132021-11-05 14:03:40 -07002292 if (hasColorTransform()) {
2293 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002294 }
2295
Vishnu Nair60db8c02020-04-02 11:55:16 -07002296 LayerProtoHelper::writeToProto(mSourceBounds,
2297 [&]() { return layerInfo->mutable_source_bounds(); });
2298 LayerProtoHelper::writeToProto(mScreenBounds,
2299 [&]() { return layerInfo->mutable_screen_bounds(); });
2300 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2301 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2302 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002303}
2304
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002305void Layer::writeToProtoCommonState(perfetto::protos::LayerProto* layerInfo,
2306 LayerVector::StateSet stateSet, uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002307 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2308 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002309 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002310
chaviw766c9c52021-02-10 17:36:47 -08002311 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002312
Vishnu Nair00b90132021-11-05 14:03:40 -07002313 layerInfo->set_id(sequence);
2314 layerInfo->set_name(getName().c_str());
2315 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002316
Vishnu Nair00b90132021-11-05 14:03:40 -07002317 for (const auto& child : children) {
2318 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002319 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002320
Vishnu Nair00b90132021-11-05 14:03:40 -07002321 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2322 sp<Layer> strongRelative = weakRelative.promote();
2323 if (strongRelative != nullptr) {
2324 layerInfo->add_relatives(strongRelative->sequence);
2325 }
2326 }
2327
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002328 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002329 [&]() { return layerInfo->mutable_transparent_region(); });
2330
2331 layerInfo->set_layer_stack(getLayerStack().id);
2332 layerInfo->set_z(state.z);
2333
2334 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2335 return layerInfo->mutable_requested_position();
2336 });
2337
Vishnu Nair00b90132021-11-05 14:03:40 -07002338 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2339
2340 layerInfo->set_is_opaque(isOpaque(state));
2341
2342 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2343 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2344 LayerProtoHelper::writeToProto(state.color,
2345 [&]() { return layerInfo->mutable_requested_color(); });
2346 layerInfo->set_flags(state.flags);
2347
2348 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2349 layerInfo->mutable_requested_transform());
2350
2351 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2352 if (parent != nullptr) {
2353 layerInfo->set_parent(parent->sequence);
Vishnu Nair00b90132021-11-05 14:03:40 -07002354 }
2355
2356 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2357 if (zOrderRelativeOf != nullptr) {
2358 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
Vishnu Nair00b90132021-11-05 14:03:40 -07002359 }
2360
2361 layerInfo->set_is_relative_of(state.isRelativeOf);
2362
2363 layerInfo->set_owner_uid(mOwnerUid);
2364
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002365 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002366 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002367 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002368 info = fillInputInfo(
2369 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002370 } else {
2371 info = state.inputInfo;
2372 }
2373
2374 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002375 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002376 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002377
Vishnu Nair00b90132021-11-05 14:03:40 -07002378 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002379 auto protoMap = layerInfo->mutable_metadata();
2380 for (const auto& entry : state.metadata.mMap) {
2381 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2382 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002383 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002384
2385 LayerProtoHelper::writeToProto(state.destinationFrame,
2386 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002387}
2388
Robert Carr2e102c92018-10-23 12:11:15 -07002389bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002390 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002391}
2392
Prabir Pradhan33da9462022-06-14 14:55:57 +00002393// Applies the given transform to the region, while protecting against overflows caused by any
2394// offsets. If applying the offset in the transform to any of the Rects in the region would result
2395// in an overflow, they are not added to the output Region.
2396static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2397 const std::string& debugWindowName) {
2398 // Round the translation using the same rounding strategy used by ui::Transform.
2399 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2400 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2401
2402 ui::Transform transformWithoutOffset = t;
2403 transformWithoutOffset.set(0.f, 0.f);
2404
2405 const Region transformed = transformWithoutOffset.transform(r);
2406
2407 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2408 Region ret;
2409 for (const auto& rect : transformed) {
2410 Rect newRect;
2411 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2412 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2413 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2414 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2415 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2416 debugWindowName.c_str());
2417 continue;
2418 }
2419 ret.orSelf(newRect);
2420 }
2421 return ret;
2422}
2423
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002424void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002425 auto [inputBounds, inputBoundsValid] = getInputBounds(/*fillParentBounds=*/false);
2426 if (!inputBoundsValid) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002427 info.touchableRegion.clear();
chaviw7e72caf2020-12-02 16:50:43 -08002428 }
2429
Chavi Weingarten7f019192023-08-08 20:39:01 +00002430 info.frame = getInputBoundsInDisplaySpace(inputBounds, screenToDisplay);
chaviw1ff3d1e2020-07-01 15:53:47 -07002431
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002432 ui::Transform inputToLayer;
Vishnu Nairfed7c122023-03-18 01:54:43 +00002433 inputToLayer.set(inputBounds.left, inputBounds.top);
2434 const ui::Transform layerToScreen = getInputTransform();
2435 const ui::Transform inputToDisplay = screenToDisplay * layerToScreen * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002436
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002437 // InputDispatcher expects a display-to-input transform.
2438 info.transform = inputToDisplay.inverse();
2439
2440 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002441 info.touchableRegion =
2442 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002443}
2444
chaviw3277faf2021-05-19 16:45:23 -05002445void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002446 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002447 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002448 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002449 }
2450 if (p != nullptr) {
2451 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2452 }
2453}
2454
Vishnu Naira066d902021-09-13 18:40:17 -07002455gui::DropInputMode Layer::getDropInputMode() const {
2456 gui::DropInputMode mode = mDrawingState.dropInputMode;
2457 if (mode == gui::DropInputMode::ALL) {
2458 return mode;
2459 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002460 sp<Layer> parent = mDrawingParent.promote();
2461 if (parent) {
2462 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002463 if (parentMode != gui::DropInputMode::NONE) {
2464 return parentMode;
2465 }
2466 }
2467 return mode;
2468}
2469
2470void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002471 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002472 return;
2473 }
2474
2475 // Check if we need to drop input unconditionally
2476 gui::DropInputMode dropInputMode = getDropInputMode();
2477 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002478 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002479 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2480 return;
2481 }
2482
2483 // Check if we need to check if the window is obscured by parent
2484 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2485 return;
2486 }
2487
2488 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002489 sp<Layer> parent = mDrawingParent.promote();
2490 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002491 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002492 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2493 static_cast<float>(getAlpha()));
2494 }
2495
2496 // Check if the parent has cropped the buffer
2497 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2498 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002499 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002500 return;
2501 }
2502
2503 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2504 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2505 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2506 // match then the layer has not been cropped by its parents.
2507 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2508 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2509
2510 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002511 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002512 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2513 getDebugName());
2514 } else {
2515 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2516 // input if the window is obscured. This check should be done in surfaceflinger but the
2517 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2518 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002519 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002520 }
2521}
2522
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002523WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002524 if (!hasInputInfo()) {
2525 mDrawingState.inputInfo.name = getName();
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002526 mDrawingState.inputInfo.ownerUid = gui::Uid{mOwnerUid};
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00002527 mDrawingState.inputInfo.ownerPid = gui::Pid{mOwnerPid};
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002528 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002529 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002530 }
2531
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002532 const ui::Transform& displayTransform =
2533 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2534
chaviw3277faf2021-05-19 16:45:23 -05002535 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002536 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002537 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002538
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002539 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002540
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002541 if (displayArgs.transform == nullptr) {
2542 // Do not let the window receive touches if it is not associated with a valid display
2543 // transform. We still allow the window to receive keys and prevent ANRs.
2544 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2545 }
2546
Patrick Williams1caf3b72023-03-31 10:59:10 -05002547 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !isVisibleForInput());
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002548
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002549 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002550 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002551 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002552
Vishnu Nair16a938f2021-09-24 07:14:54 -07002553 // If the window will be blacked out on a display because the display does not have the secure
2554 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002555 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002556 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002557 }
2558
Vishnu Nairfed7c122023-03-18 01:54:43 +00002559 sp<Layer> cropLayer = mDrawingState.touchableRegionCrop.promote();
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002560 if (info.replaceTouchableRegionWithCrop) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002561 Rect inputBoundsInDisplaySpace;
2562 if (!cropLayer) {
2563 FloatRect inputBounds = getInputBounds(/*fillParentBounds=*/true).first;
2564 inputBoundsInDisplaySpace = getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2565 } else {
2566 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2567 inputBoundsInDisplaySpace =
2568 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2569 }
2570 info.touchableRegion = Region(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002571 } else if (cropLayer != nullptr) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002572 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2573 Rect inputBoundsInDisplaySpace =
2574 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2575 info.touchableRegion = info.touchableRegion.intersect(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002576 }
2577
Winson Chunga30f7c92021-06-29 15:42:56 -07002578 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2579 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002580 if (isTrustedOverlay()) {
2581 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2582 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002583
chaviwaf87b3e2019-10-01 16:59:28 -07002584 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2585 // touches from going outside the cloned area.
2586 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002587 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002588 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2589 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002590 info.touchableRegion = info.touchableRegion.intersect(rect);
2591 }
2592 }
2593
Robert Carr720e5062018-07-30 17:45:14 -07002594 return info;
2595}
2596
Vishnu Nairfed7c122023-03-18 01:54:43 +00002597Rect Layer::getInputBoundsInDisplaySpace(const FloatRect& inputBounds,
2598 const ui::Transform& screenToDisplay) {
2599 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2600 // frame and transform used for the layer, which determines the bounds and the coordinate space
2601 // within which the layer will receive input.
2602
2603 // Coordinate space definitions:
2604 // - display: The display device's coordinate space. Correlates to pixels on the display.
2605 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2606 // - layer: The coordinate space of this layer.
2607 // - input: The coordinate space in which this layer will receive input events. This could be
2608 // different than layer space if a surfaceInset is used, which changes the origin
2609 // of the input space.
2610
2611 // Crop the input bounds to ensure it is within the parent's bounds.
2612 const FloatRect croppedInputBounds = mBounds.intersect(inputBounds);
2613 const ui::Transform layerToScreen = getInputTransform();
2614 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
2615 return Rect{layerToDisplay.transform(croppedInputBounds)};
2616}
2617
chaviwaf87b3e2019-10-01 16:59:28 -07002618sp<Layer> Layer::getClonedRoot() {
2619 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002620 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002621 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002622 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002623 return nullptr;
2624 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002625 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002626}
2627
Robert Carredd13602020-04-13 17:24:34 -07002628bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002629 return mDrawingState.inputInfo.token != nullptr ||
2630 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002631}
2632
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002633compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002634 const DisplayDevice* display) const {
2635 if (!display) return nullptr;
Lloyd Pique30db6402023-06-26 18:56:51 +00002636 if (!mFlinger->mLayerLifecycleManagerEnabled) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00002637 return display->getCompositionDisplay()->getOutputLayerForLayer(
2638 getCompositionEngineLayerFE());
2639 }
2640 sp<LayerFE> layerFE;
2641 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
2642 for (auto& [p, layer] : mLayerFEs) {
2643 if (p == path) {
2644 layerFE = layer;
2645 }
2646 }
2647
2648 if (!layerFE) return nullptr;
2649 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002650}
2651
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002652compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
2653 const DisplayDevice* display, const frontend::LayerHierarchy::TraversalPath& path) const {
2654 if (!display) return nullptr;
Vishnu Naire9ee0002023-07-01 03:14:51 +00002655 if (!mFlinger->mLayerLifecycleManagerEnabled) {
2656 return display->getCompositionDisplay()->getOutputLayerForLayer(
2657 getCompositionEngineLayerFE());
2658 }
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002659 sp<LayerFE> layerFE;
2660 for (auto& [p, layer] : mLayerFEs) {
2661 if (p == path) {
2662 layerFE = layer;
2663 }
2664 }
2665
2666 if (!layerFE) return nullptr;
2667 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
2668}
2669
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002670Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2671 const auto outputLayer = findOutputLayerForDisplay(display);
2672 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002673}
2674
Vishnu Nairde177252023-04-21 12:44:10 -07002675void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom, uint32_t mirrorRootId) {
2676 mSnapshot->path.id = clonedFrom->getSequence();
Vishnu Nair6f878312023-09-08 11:05:01 -07002677 mSnapshot->path.mirrorRootIds.emplace_back(mirrorRootId);
Vishnu Nairde177252023-04-21 12:44:10 -07002678
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002679 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002680 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002681 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2682 mPotentialCursor = clonedFrom->mPotentialCursor;
2683 mProtectedByApp = clonedFrom->mProtectedByApp;
2684 updateCloneBufferInfo();
2685}
2686
2687void Layer::updateCloneBufferInfo() {
2688 if (!isClone() || !isClonedFromAlive()) {
2689 return;
2690 }
2691
2692 sp<Layer> clonedFrom = getClonedFrom();
2693 mBufferInfo = clonedFrom->mBufferInfo;
2694 mSidebandStream = clonedFrom->mSidebandStream;
2695 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2696 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2697 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2698
2699 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2700 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2701 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2702 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2703 // the cloned drawingState again.
2704 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2705 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2706 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2707 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2708
2709 cloneDrawingState(clonedFrom.get());
2710
2711 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2712 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2713 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2714 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002715}
chaviw74b03172019-08-19 11:09:03 -07002716
Vishnu Nair3be61902023-04-26 19:47:29 -07002717bool Layer::updateMirrorInfo(const std::deque<Layer*>& cloneRootsPendingUpdates) {
chaviw74b03172019-08-19 11:09:03 -07002718 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2719 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2720 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2721 // that case, we want to delete the reference to the clone since we want it to get
2722 // destroyed. The root, this layer, will still be around since the client can continue
2723 // to hold a reference, but no cloned layers will be displayed.
2724 mClonedChild = nullptr;
Vishnu Nair3be61902023-04-26 19:47:29 -07002725 return true;
chaviw74b03172019-08-19 11:09:03 -07002726 }
2727
2728 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2729 // If the real layer exists and is in current state, add the clone as a child of the root.
2730 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2731 // copied to drawingState for the root layer. So the clonedChild is always removed from
2732 // drawingState and then needs to be added back each traversal.
2733 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2734 addChildToDrawing(mClonedChild);
2735 }
2736
2737 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002738 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002739 mClonedChild->updateClonedRelatives(clonedLayersMap);
Vishnu Nair3be61902023-04-26 19:47:29 -07002740
2741 for (Layer* root : cloneRootsPendingUpdates) {
2742 if (clonedLayersMap.find(sp<Layer>::fromExisting(root)) != clonedLayersMap.end()) {
2743 return false;
2744 }
2745 }
2746 return true;
chaviw74b03172019-08-19 11:09:03 -07002747}
2748
2749void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2750 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2751 // to the clone. If the real layer is no longer alive, continue traversing the children
2752 // since we may be able to pull out other children that are still alive.
2753 if (isClonedFromAlive()) {
2754 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002755 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002756 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002757 }
2758
2759 // The clone layer may have children in drawingState since they may have been created and
2760 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2761 // that already exist, since we can just re-use them.
2762 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2763 // not updated in the regular traversal. They are skipped since the root will lose the
2764 // reference to them when it copies its currentChildren to drawing.
2765 for (sp<Layer>& child : mDrawingChildren) {
2766 child->updateClonedDrawingState(clonedLayersMap);
2767 }
2768}
2769
2770void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2771 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2772 mDrawingChildren.clear();
2773
2774 if (!isClonedFromAlive()) {
2775 return;
2776 }
2777
2778 sp<Layer> clonedFrom = getClonedFrom();
2779 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2780 if (child == mirrorRoot) {
2781 // This is to avoid cyclical mirroring.
2782 continue;
2783 }
2784 sp<Layer> clonedChild = clonedLayersMap[child];
2785 if (clonedChild == nullptr) {
Vishnu Nairde177252023-04-21 12:44:10 -07002786 clonedChild = child->createClone(mirrorRoot->getSequence());
chaviw74b03172019-08-19 11:09:03 -07002787 clonedLayersMap[child] = clonedChild;
2788 }
2789 addChildToDrawing(clonedChild);
2790 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2791 }
2792}
2793
chaviwaf87b3e2019-10-01 16:59:28 -07002794void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2795 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2796 if (cropLayer != nullptr) {
2797 if (clonedLayersMap.count(cropLayer) == 0) {
2798 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2799 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002800 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002801 } else {
2802 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2803 mDrawingState.touchableRegionCrop = clonedCropLayer;
2804 }
2805 }
2806 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2807 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002808 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002809}
2810
2811void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002812 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002813 mDrawingState.zOrderRelatives.clear();
2814
2815 if (!isClonedFromAlive()) {
2816 return;
2817 }
2818
chaviwaf87b3e2019-10-01 16:59:28 -07002819 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002820 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002821 const sp<Layer>& relative = relativeWeak.promote();
2822 if (clonedLayersMap.count(relative) > 0) {
2823 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002824 mDrawingState.zOrderRelatives.add(clonedRelative);
2825 }
2826 }
2827
2828 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2829 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2830 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2831 // still traverse the children, but the layer with the missing relativeOf will not be shown
2832 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002833 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2834 if (clonedLayersMap.count(relativeOf) > 0) {
2835 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002836 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2837 }
2838
chaviwaf87b3e2019-10-01 16:59:28 -07002839 updateClonedInputInfo(clonedLayersMap);
2840
chaviw74b03172019-08-19 11:09:03 -07002841 for (sp<Layer>& child : mDrawingChildren) {
2842 child->updateClonedRelatives(clonedLayersMap);
2843 }
2844}
2845
2846void Layer::addChildToDrawing(const sp<Layer>& layer) {
2847 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002848 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002849}
2850
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002851bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002852 const State& s(mDrawingState);
2853 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2854 return true;
2855 }
2856
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002857 sp<Layer> parent = mDrawingParent.promote();
2858 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002859}
2860
Robert Carr6a0382d2021-07-01 15:57:17 -07002861void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2862 mClonedChild = clonedChild;
2863 mHadClonedChild = true;
Vishnu Nair3be61902023-04-26 19:47:29 -07002864 mFlinger->mLayerMirrorRoots.push_back(this);
Robert Carr6a0382d2021-07-01 15:57:17 -07002865}
2866
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002867bool Layer::setDropInputMode(gui::DropInputMode mode) {
2868 if (mDrawingState.dropInputMode == mode) {
2869 return false;
2870 }
2871 mDrawingState.dropInputMode = mode;
2872 return true;
2873}
2874
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002875void Layer::cloneDrawingState(const Layer* from) {
2876 mDrawingState = from->mDrawingState;
2877 // Skip callback info since they are not applicable for cloned layers.
2878 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002879 // TODO (b/238781169) currently broken for mirror layers because we do not
2880 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002881 mDrawingState.callbackHandles = {};
2882}
2883
Patrick Williamsbb25f802022-08-30 23:02:34 +00002884void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2885 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08002886 const sp<Fence>& releaseFence) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002887 if (!listener) {
2888 return;
2889 }
2890 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
liulijuneb489f62022-10-17 22:02:14 +08002891 uint32_t currentMaxAcquiredBufferCount =
2892 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002893 listener->onReleaseBuffer({buffer->getId(), framenumber},
2894 releaseFence ? releaseFence : Fence::NO_FENCE,
2895 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002896}
2897
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002898void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult,
2899 ui::LayerStack layerStack) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002900 // If we are displayed on multiple displays in a single composition cycle then we would
2901 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2902 // For example we can only use it if all the displays are client comp, and we need
2903 // to merge all the client comp fences. We could do this, but for now we just
2904 // disable the optimization when a layer is composed on multiple displays.
2905 if (mClearClientCompositionFenceOnLayerDisplayed) {
2906 mLastClientCompositionFence = nullptr;
2907 } else {
2908 mClearClientCompositionFenceOnLayerDisplayed = true;
2909 }
2910
2911 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2912 // buffer that was presented on this layer. The first transaction that came in this frame that
2913 // replaced the previous buffer on this layer needs this release fence, because the fence will
2914 // let the client know when that previous buffer is removed from the screen.
2915 //
2916 // Every other transaction on this layer does not need a release fence because no other
2917 // Transactions that were set on this layer this frame are going to have their preceding buffer
2918 // removed from the display this frame.
2919 //
2920 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2921 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2922 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2923 // the previous buffer will be released this frame. The third transaction also contains a
2924 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2925 // transaction will now no longer be presented so it is released immediately and the third
2926 // transaction doesn't need a previous release fence.
2927 sp<CallbackHandle> ch;
2928 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002929 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002930 ch = handle;
2931 break;
2932 }
2933 }
2934
Patrick Williamsbb25f802022-08-30 23:02:34 +00002935 if (ch != nullptr) {
2936 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2937 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2938 ch->name = mName;
2939 }
Vishnu Nair316b7f42023-10-13 23:44:46 +00002940 if (mBufferInfo.mBuffer) {
2941 mPreviouslyPresentedLayerStacks.push_back(layerStack);
2942 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002943}
2944
2945void Layer::onSurfaceFrameCreated(
2946 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2947 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2948 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2949 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2950 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01002951 if (hasBufferOrSidebandStreamInDrawing()) {
2952 // Only log for layers with a buffer, since we expect the jank data to be drained for
2953 // these, while there may be no jank listeners for bufferless layers.
2954 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2955 mName.c_str());
2956 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2957 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2958 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002959 mPendingJankClassifications.pop_front();
2960 }
2961 mPendingJankClassifications.emplace_back(surfaceFrame);
2962}
2963
2964void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2965 for (const auto& handle : mDrawingState.callbackHandles) {
Lloyd Pique30db6402023-06-26 18:56:51 +00002966 if (mFlinger->mLayerLifecycleManagerEnabled) {
Vishnu Nairb76d99a2023-03-19 18:22:31 -07002967 handle->transformHint = mTransformHint;
2968 } else {
2969 handle->transformHint = mSkipReportingTransformHint
2970 ? std::nullopt
2971 : std::make_optional<uint32_t>(mTransformHintLegacy);
2972 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002973 handle->dequeueReadyTime = dequeueReadyTime;
2974 handle->currentMaxAcquiredBufferCount =
2975 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2976 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2977 handle->previousReleaseCallbackId.framenumber);
2978 }
2979
2980 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002981 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002982 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2983 break;
2984 }
2985 }
2986
2987 std::vector<JankData> jankData;
Pascal Muetschardf54181b2022-12-13 14:53:25 +01002988 transferAvailableJankData(mDrawingState.callbackHandles, jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002989 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2990 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002991 mDrawingState.callbackHandles = {};
2992}
2993
2994bool Layer::willPresentCurrentTransaction() const {
2995 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2996 return (getSidebandStreamChanged() || getAutoRefresh() ||
2997 (mDrawingState.modified &&
2998 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2999}
3000
3001bool Layer::setTransform(uint32_t transform) {
3002 if (mDrawingState.bufferTransform == transform) return false;
3003 mDrawingState.bufferTransform = transform;
3004 mDrawingState.modified = true;
3005 setTransactionFlags(eTransactionNeeded);
3006 return true;
3007}
3008
3009bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
3010 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
3011 mDrawingState.sequence++;
3012 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
3013 mDrawingState.modified = true;
3014 setTransactionFlags(eTransactionNeeded);
3015 return true;
3016}
3017
3018bool Layer::setBufferCrop(const Rect& bufferCrop) {
3019 if (mDrawingState.bufferCrop == bufferCrop) return false;
3020
3021 mDrawingState.sequence++;
3022 mDrawingState.bufferCrop = bufferCrop;
3023
3024 mDrawingState.modified = true;
3025 setTransactionFlags(eTransactionNeeded);
3026 return true;
3027}
3028
3029bool Layer::setDestinationFrame(const Rect& destinationFrame) {
3030 if (mDrawingState.destinationFrame == destinationFrame) return false;
3031
3032 mDrawingState.sequence++;
3033 mDrawingState.destinationFrame = destinationFrame;
3034
3035 mDrawingState.modified = true;
3036 setTransactionFlags(eTransactionNeeded);
3037 return true;
3038}
3039
3040// Translate destination frame into scale and position. If a destination frame is not set, use the
3041// provided scale and position
3042bool Layer::updateGeometry() {
3043 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
3044 mDrawingState.destinationFrame.isEmpty()) {
3045 // If destination frame is not set, use the requested transform set via
3046 // Layer::setPosition and Layer::setMatrix.
3047 return assignTransform(&mDrawingState.transform, mRequestedTransform);
3048 }
3049
3050 Rect destRect = mDrawingState.destinationFrame;
3051 int32_t destW = destRect.width();
3052 int32_t destH = destRect.height();
3053 if (destRect.left < 0) {
3054 destRect.left = 0;
3055 destRect.right = destW;
3056 }
3057 if (destRect.top < 0) {
3058 destRect.top = 0;
3059 destRect.bottom = destH;
3060 }
3061
3062 if (!mDrawingState.buffer) {
3063 ui::Transform t;
3064 t.set(destRect.left, destRect.top);
3065 return assignTransform(&mDrawingState.transform, t);
3066 }
3067
3068 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
3069 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
3070 // Undo any transformations on the buffer.
3071 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
3072 std::swap(bufferWidth, bufferHeight);
3073 }
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003074 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003075 if (mDrawingState.transformToDisplayInverse) {
3076 if (invTransform & ui::Transform::ROT_90) {
3077 std::swap(bufferWidth, bufferHeight);
3078 }
3079 }
3080
3081 float sx = destW / static_cast<float>(bufferWidth);
3082 float sy = destH / static_cast<float>(bufferHeight);
3083 ui::Transform t;
3084 t.set(sx, 0, 0, sy);
3085 t.set(destRect.left, destRect.top);
3086 return assignTransform(&mDrawingState.transform, t);
3087}
3088
3089bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
3090 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
3091 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
3092 return false;
3093 }
3094
3095 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
3096
3097 mDrawingState.sequence++;
3098 mDrawingState.modified = true;
3099 setTransactionFlags(eTransactionNeeded);
3100
3101 return true;
3102}
3103
3104bool Layer::setPosition(float x, float y) {
3105 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3106 return false;
3107 }
3108
3109 mRequestedTransform.set(x, y);
3110
3111 mDrawingState.sequence++;
3112 mDrawingState.modified = true;
3113 setTransactionFlags(eTransactionNeeded);
3114
3115 return true;
3116}
3117
Dorin Drimuse5374e52023-08-02 17:52:43 +00003118void Layer::releasePreviousBuffer() {
3119 mReleasePreviousBuffer = true;
3120 if (!mBufferInfo.mBuffer ||
3121 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3122 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3123 // If mDrawingState has a buffer, and we are about to update again
3124 // before swapping to drawing state, then the first buffer will be
3125 // dropped and we should decrement the pending buffer count and
3126 // call any release buffer callbacks if set.
3127 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3128 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3129 mDrawingState.acquireFence);
3130 decrementPendingBufferCount();
3131 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3132 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3133 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX, systemTime());
3134 mDrawingState.bufferSurfaceFrameTX.reset();
3135 }
3136 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3137 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3138 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3139 mLastClientCompositionFence);
3140 mLastClientCompositionFence = nullptr;
3141 }
3142}
3143
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003144void Layer::resetDrawingStateBufferInfo() {
3145 mDrawingState.producerId = 0;
3146 mDrawingState.frameNumber = 0;
3147 mDrawingState.releaseBufferListener = nullptr;
3148 mDrawingState.buffer = nullptr;
3149 mDrawingState.acquireFence = sp<Fence>::make(-1);
3150 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3151 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3152 mDrawingState.releaseBufferEndpoint = nullptr;
3153}
3154
Patrick Williamsbb25f802022-08-30 23:02:34 +00003155bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3156 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3157 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07003158 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003159 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003160
3161 const bool frameNumberChanged =
3162 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3163 const uint64_t frameNumber =
3164 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003165 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003166
3167 if (mDrawingState.buffer) {
Dorin Drimuse5374e52023-08-02 17:52:43 +00003168 releasePreviousBuffer();
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003169 } else if (buffer) {
Vishnu Nairc09c0232023-03-02 03:22:35 +00003170 // if we are latching a buffer for the first time then clear the mLastLatchTime since
3171 // we don't want to incorrectly classify a frame if we miss the desired present time.
3172 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003173 }
3174
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003175 mDrawingState.desiredPresentTime = desiredPresentTime;
3176 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3177 mDrawingState.latchedVsyncId = info.vsyncId;
Ady Abraham55269162023-05-09 11:26:06 -07003178 mDrawingState.useVsyncIdForRefreshRateSelection = info.useForRefreshRateSelection;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003179 mDrawingState.modified = true;
3180 if (!buffer) {
3181 resetDrawingStateBufferInfo();
3182 setTransactionFlags(eTransactionNeeded);
3183 mDrawingState.bufferSurfaceFrameTX = nullptr;
3184 setFrameTimelineVsyncForBufferlessTransaction(info, postTime);
3185 return true;
Dorin Drimuse5374e52023-08-02 17:52:43 +00003186 } else {
3187 // release sideband stream if it exists and a non null buffer is being set
3188 if (mDrawingState.sidebandStream != nullptr) {
Dorin Drimus66ed1c42023-09-27 13:10:16 +00003189 setSidebandStream(nullptr, info, postTime);
Dorin Drimuse5374e52023-08-02 17:52:43 +00003190 }
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003191 }
3192
Vishnu Naird1f74982023-06-15 20:16:51 -07003193 if ((mDrawingState.producerId > bufferData.producerId) ||
3194 ((mDrawingState.producerId == bufferData.producerId) &&
3195 (mDrawingState.frameNumber > frameNumber))) {
3196 ALOGE("Out of order buffers detected for %s producedId=%d frameNumber=%" PRIu64
3197 " -> producedId=%d frameNumber=%" PRIu64,
3198 getDebugName(), mDrawingState.producerId, mDrawingState.frameNumber,
3199 bufferData.producerId, frameNumber);
3200 TransactionTraceWriter::getInstance().invoke("out_of_order_buffers_", /*overwrite=*/false);
3201 }
3202
liulijuneb489f62022-10-17 22:02:14 +08003203 mDrawingState.producerId = bufferData.producerId;
Vishnu Nair63221212023-04-06 15:17:37 -07003204 mDrawingState.barrierProducerId =
3205 std::max(mDrawingState.producerId, mDrawingState.barrierProducerId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003206 mDrawingState.frameNumber = frameNumber;
Vishnu Nair63221212023-04-06 15:17:37 -07003207 mDrawingState.barrierFrameNumber =
3208 std::max(mDrawingState.frameNumber, mDrawingState.barrierFrameNumber);
3209
Patrick Williamsbb25f802022-08-30 23:02:34 +00003210 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3211 mDrawingState.buffer = std::move(buffer);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003212 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3213 ? bufferData.acquireFence
3214 : Fence::NO_FENCE;
3215 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3216 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3217 // We latched this buffer unsiganled, so we need to pass the acquire fence
3218 // on the callback instead of just the acquire time, since it's unknown at
3219 // this point.
3220 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3221 } else {
3222 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3223 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003224 setTransactionFlags(eTransactionNeeded);
3225
3226 const int32_t layerId = getSequence();
3227 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3228 mOwnerUid, postTime, getGameMode());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003229
Lloyd Pique30db6402023-06-26 18:56:51 +00003230 if (mFlinger->mLegacyFrontEndEnabled) {
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003231 recordLayerHistoryBufferUpdate(getLayerProps(), systemTime());
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003232 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003233
3234 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3235
3236 if (dequeueTime && *dequeueTime != 0) {
3237 const uint64_t bufferId = mDrawingState.buffer->getId();
3238 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3239 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3240 FrameTracer::FrameEvent::DEQUEUE);
3241 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3242 FrameTracer::FrameEvent::QUEUE);
3243 }
3244
3245 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
Arthur Hungc70bee22023-06-02 01:35:52 +00003246
3247 // If the layer had been updated a TextureView, this would make sure the present time could be
3248 // same to TextureView update when it's a small dirty, and get the correct heuristic rate.
3249 if (mFlinger->mScheduler->supportSmallDirtyDetection()) {
3250 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
3251 mUsedVsyncIdForRefreshRateSelection = true;
3252 }
3253 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003254 return true;
3255}
3256
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003257void Layer::setDesiredPresentTime(nsecs_t desiredPresentTime, bool isAutoTimestamp) {
3258 mDrawingState.desiredPresentTime = desiredPresentTime;
3259 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3260}
3261
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003262void Layer::recordLayerHistoryBufferUpdate(const scheduler::LayerProps& layerProps, nsecs_t now) {
Ady Abraham55269162023-05-09 11:26:06 -07003263 ATRACE_CALL();
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003264 const nsecs_t presentTime = [&] {
Ady Abraham55269162023-05-09 11:26:06 -07003265 if (!mDrawingState.isAutoTimestamp) {
3266 ATRACE_FORMAT_INSTANT("desiredPresentTime");
3267 return mDrawingState.desiredPresentTime;
3268 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003269
Ady Abraham55269162023-05-09 11:26:06 -07003270 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
3271 const auto prediction =
3272 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3273 mDrawingState.latchedVsyncId);
3274 if (prediction.has_value()) {
3275 ATRACE_FORMAT_INSTANT("predictedPresentTime");
Arthur Hungc70bee22023-06-02 01:35:52 +00003276 mMaxTimeForUseVsyncId = prediction->presentTime +
3277 scheduler::LayerHistory::kMaxPeriodForHistory.count();
Ady Abraham55269162023-05-09 11:26:06 -07003278 return prediction->presentTime;
3279 }
3280 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003281
Arthur Hungc70bee22023-06-02 01:35:52 +00003282 if (!mFlinger->mScheduler->supportSmallDirtyDetection()) {
3283 return static_cast<nsecs_t>(0);
3284 }
3285
3286 // If the layer is not an application and didn't set an explicit rate or desiredPresentTime,
3287 // return "0" to tell the layer history that it will use the max refresh rate without
3288 // calculating the adaptive rate.
3289 if (mWindowType != WindowInfo::Type::APPLICATION &&
3290 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
3291 return static_cast<nsecs_t>(0);
3292 }
3293
3294 // Return the valid present time only when the layer potentially updated a TextureView so
3295 // LayerHistory could heuristically calculate the rate if the UI is continually updating.
3296 if (mUsedVsyncIdForRefreshRateSelection) {
3297 const auto prediction =
3298 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3299 mDrawingState.latchedVsyncId);
3300 if (prediction.has_value()) {
3301 if (mMaxTimeForUseVsyncId >= prediction->presentTime) {
3302 return prediction->presentTime;
3303 }
3304 mUsedVsyncIdForRefreshRateSelection = false;
3305 }
3306 }
3307
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003308 return static_cast<nsecs_t>(0);
3309 }();
Ady Abraham55269162023-05-09 11:26:06 -07003310
3311 if (ATRACE_ENABLED() && presentTime > 0) {
3312 const auto presentIn = TimePoint::fromNs(presentTime) - TimePoint::now();
3313 ATRACE_FORMAT_INSTANT("presentIn %s", to_string(presentIn).c_str());
3314 }
3315
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003316 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003317 scheduler::LayerHistory::LayerUpdateType::Buffer);
3318}
3319
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003320void Layer::recordLayerHistoryAnimationTx(const scheduler::LayerProps& layerProps, nsecs_t now) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003321 const nsecs_t presentTime =
3322 mDrawingState.isAutoTimestamp ? 0 : mDrawingState.desiredPresentTime;
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003323 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003324 scheduler::LayerHistory::LayerUpdateType::AnimationTX);
3325}
3326
Patrick Williamsbb25f802022-08-30 23:02:34 +00003327bool Layer::setDataspace(ui::Dataspace dataspace) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003328 if (mDrawingState.dataspace == dataspace) return false;
3329 mDrawingState.dataspace = dataspace;
3330 mDrawingState.modified = true;
3331 setTransactionFlags(eTransactionNeeded);
3332 return true;
3333}
3334
John Reck68796592023-01-25 13:47:12 -05003335bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
Sally Qi963049b2023-03-23 14:06:21 -07003336 if (mDrawingState.currentHdrSdrRatio == currentBufferRatio &&
3337 mDrawingState.desiredHdrSdrRatio == desiredRatio)
John Reck68796592023-01-25 13:47:12 -05003338 return false;
Sally Qi963049b2023-03-23 14:06:21 -07003339 mDrawingState.currentHdrSdrRatio = currentBufferRatio;
3340 mDrawingState.desiredHdrSdrRatio = desiredRatio;
John Reck68796592023-01-25 13:47:12 -05003341 mDrawingState.modified = true;
3342 setTransactionFlags(eTransactionNeeded);
3343 return true;
3344}
3345
Alec Mourif4af03e2023-02-11 00:25:24 +00003346bool Layer::setCachingHint(gui::CachingHint cachingHint) {
3347 if (mDrawingState.cachingHint == cachingHint) return false;
3348 mDrawingState.cachingHint = cachingHint;
3349 mDrawingState.modified = true;
3350 setTransactionFlags(eTransactionNeeded);
3351 return true;
3352}
3353
Patrick Williamsbb25f802022-08-30 23:02:34 +00003354bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3355 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3356 mDrawingState.hdrMetadata = hdrMetadata;
3357 mDrawingState.modified = true;
3358 setTransactionFlags(eTransactionNeeded);
3359 return true;
3360}
3361
3362bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Sally Qi2b1b4292023-03-14 16:47:39 +00003363 if (mDrawingState.surfaceDamageRegion.hasSameRects(surfaceDamage)) return false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003364 mDrawingState.surfaceDamageRegion = surfaceDamage;
3365 mDrawingState.modified = true;
3366 setTransactionFlags(eTransactionNeeded);
Arthur Hung69f95222023-10-04 07:39:02 +00003367 setIsSmallDirty(surfaceDamage, getTransform());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003368 return true;
3369}
3370
3371bool Layer::setApi(int32_t api) {
3372 if (mDrawingState.api == api) return false;
3373 mDrawingState.api = api;
3374 mDrawingState.modified = true;
3375 setTransactionFlags(eTransactionNeeded);
3376 return true;
3377}
3378
Dorin Drimuse5374e52023-08-02 17:52:43 +00003379bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream, const FrameTimelineInfo& info,
3380 nsecs_t postTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003381 if (mDrawingState.sidebandStream == sidebandStream) return false;
3382
3383 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3384 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3385 } else if (sidebandStream != nullptr) {
3386 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3387 }
3388
3389 mDrawingState.sidebandStream = sidebandStream;
3390 mDrawingState.modified = true;
Dorin Drimuse5374e52023-08-02 17:52:43 +00003391 if (sidebandStream != nullptr && mDrawingState.buffer != nullptr) {
3392 releasePreviousBuffer();
3393 resetDrawingStateBufferInfo();
3394 mDrawingState.bufferSurfaceFrameTX = nullptr;
3395 setFrameTimelineVsyncForBufferlessTransaction(info, postTime);
3396 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003397 setTransactionFlags(eTransactionNeeded);
3398 if (!mSidebandStreamChanged.exchange(true)) {
3399 // mSidebandStreamChanged was false
3400 mFlinger->onLayerUpdate();
3401 }
3402 return true;
3403}
3404
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003405bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3406 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003407 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3408 if (handles.empty()) {
3409 mReleasePreviousBuffer = false;
3410 return false;
3411 }
3412
Pascal Muetschard81cef292023-02-06 12:18:52 +01003413 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003414 for (const auto& handle : handles) {
3415 // If this transaction set a buffer on this layer, release its previous buffer
3416 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3417
3418 // If this layer will be presented in this frame
3419 if (willPresent) {
3420 // If this transaction set an acquire fence on this layer, set its acquire time
3421 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3422 handle->frameNumber = mDrawingState.frameNumber;
3423
3424 // Store so latched time and release fence can be set
3425 mDrawingState.callbackHandles.push_back(handle);
3426
3427 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01003428 // Queue this handle to be notified below.
3429 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003430 }
3431 }
3432
Pascal Muetschard81cef292023-02-06 12:18:52 +01003433 if (!remainingHandles.empty()) {
3434 // Notify the transaction completed threads these handles are done. These are only the
3435 // handles that were not added to the mDrawingState, which will be notified later.
3436 std::vector<JankData> jankData;
3437 transferAvailableJankData(remainingHandles, jankData);
3438 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles, jankData);
3439 }
3440
Patrick Williamsbb25f802022-08-30 23:02:34 +00003441 mReleasePreviousBuffer = false;
3442 mCallbackHandleAcquireTimeOrFence = -1;
3443
3444 return willPresent;
3445}
3446
3447Rect Layer::getBufferSize(const State& /*s*/) const {
3448 // for buffer state layers we use the display frame size as the buffer size.
3449
3450 if (mBufferInfo.mBuffer == nullptr) {
3451 return Rect::INVALID_RECT;
3452 }
3453
3454 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3455 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3456
3457 // Undo any transformations on the buffer and return the result.
3458 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3459 std::swap(bufWidth, bufHeight);
3460 }
3461
3462 if (getTransformToDisplayInverse()) {
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003463 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003464 if (invTransform & ui::Transform::ROT_90) {
3465 std::swap(bufWidth, bufHeight);
3466 }
3467 }
3468
3469 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3470}
3471
3472FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3473 if (mBufferInfo.mBuffer == nullptr) {
3474 return parentBounds;
3475 }
3476
3477 return getBufferSize(getDrawingState()).toFloatRect();
3478}
3479
3480bool Layer::fenceHasSignaled() const {
3481 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3482 return true;
3483 }
3484
3485 const bool fenceSignaled =
3486 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3487 if (!fenceSignaled) {
3488 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3489 TimeStats::LatchSkipReason::LateAcquire);
3490 }
3491
3492 return fenceSignaled;
3493}
3494
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003495void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003496 for (const auto& handle : mDrawingState.callbackHandles) {
3497 handle->refreshStartTime = refreshStartTime;
3498 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003499}
3500
3501void Layer::setAutoRefresh(bool autoRefresh) {
3502 mDrawingState.autoRefresh = autoRefresh;
3503}
3504
3505bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3506 // We need to update the sideband stream if the layer has both a buffer and a sideband stream.
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003507 auto* snapshot = editLayerSnapshot();
3508 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003509
3510 if (mSidebandStreamChanged.exchange(false)) {
3511 const State& s(getDrawingState());
3512 // mSidebandStreamChanged was true
3513 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003514 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003515 if (mSidebandStream != nullptr) {
3516 setTransactionFlags(eTransactionNeeded);
3517 mFlinger->setTransactionFlags(eTraversalNeeded);
3518 }
3519 recomputeVisibleRegions = true;
3520
3521 return true;
3522 }
3523 return false;
3524}
3525
3526bool Layer::hasFrameUpdate() const {
3527 const State& c(getDrawingState());
3528 return (mDrawingStateModified || mDrawingState.modified) &&
3529 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3530}
3531
Vishnu Naird47bcee2023-02-24 18:08:51 +00003532void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003533 const State& s(getDrawingState());
3534
3535 if (!s.buffer) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003536 if (bgColorOnly || mBufferInfo.mBuffer) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003537 for (auto& handle : mDrawingState.callbackHandles) {
3538 handle->latchTime = latchTime;
3539 }
3540 }
3541 return;
3542 }
3543
3544 for (auto& handle : mDrawingState.callbackHandles) {
3545 if (handle->frameNumber == mDrawingState.frameNumber) {
3546 handle->latchTime = latchTime;
3547 }
3548 }
3549
3550 const int32_t layerId = getSequence();
3551 const uint64_t bufferId = mDrawingState.buffer->getId();
3552 const uint64_t frameNumber = mDrawingState.frameNumber;
3553 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3554 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3555 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3556
3557 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3558 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3559 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3560 FrameTracer::FrameEvent::LATCH);
3561
3562 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3563 if (bufferSurfaceFrame != nullptr &&
3564 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3565 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3566 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3567 // are processing the next state.
3568 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3569 mDrawingState.acquireFenceTime->getSignalTime(),
3570 latchTime);
3571 mDrawingState.bufferSurfaceFrameTX.reset();
3572 }
3573
3574 std::deque<sp<CallbackHandle>> remainingHandles;
3575 mFlinger->getTransactionCallbackInvoker()
3576 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3577 mDrawingState.callbackHandles = remainingHandles;
3578
3579 mDrawingStateModified = false;
3580}
3581
3582void Layer::gatherBufferInfo() {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003583 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3584 mPreviousReleaseBufferEndpoint = mBufferInfo.mReleaseBufferEndpoint;
3585 if (!mDrawingState.buffer) {
3586 mBufferInfo = {};
3587 return;
3588 }
3589
3590 if ((!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer))) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003591 decrementPendingBufferCount();
3592 }
3593
Patrick Williamsbb25f802022-08-30 23:02:34 +00003594 mBufferInfo.mBuffer = mDrawingState.buffer;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003595 mBufferInfo.mReleaseBufferEndpoint = mDrawingState.releaseBufferEndpoint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003596 mBufferInfo.mFence = mDrawingState.acquireFence;
3597 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3598 mBufferInfo.mPixelFormat =
3599 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3600 mBufferInfo.mFrameLatencyNeeded = true;
3601 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3602 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3603 mBufferInfo.mFence = mDrawingState.acquireFence;
3604 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3605 auto lastDataspace = mBufferInfo.mDataspace;
3606 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
Alec Mouri74c7ae12023-03-26 02:57:47 +00003607 if (mBufferInfo.mBuffer != nullptr) {
3608 auto& mapper = GraphicBufferMapper::get();
3609 // TODO: We should measure if it's faster to do a blind write if we're on newer api levels
3610 // and don't need to possibly remaps buffers.
3611 ui::Dataspace dataspace = ui::Dataspace::UNKNOWN;
3612 status_t err = OK;
3613 {
3614 ATRACE_NAME("getDataspace");
3615 err = mapper.getDataspace(mBufferInfo.mBuffer->getBuffer()->handle, &dataspace);
3616 }
3617 if (err != OK || dataspace != mBufferInfo.mDataspace) {
3618 {
3619 ATRACE_NAME("setDataspace");
3620 err = mapper.setDataspace(mBufferInfo.mBuffer->getBuffer()->handle,
3621 static_cast<ui::Dataspace>(mBufferInfo.mDataspace));
3622 }
3623
3624 // Some GPU drivers may cache gralloc metadata which means before we composite we need
3625 // to upsert RenderEngine's caches. Put in a special workaround to be backwards
3626 // compatible with old vendors, with a ticking clock.
3627 static const int32_t kVendorVersion =
3628 base::GetIntProperty("ro.vndk.version", __ANDROID_API_FUTURE__);
3629 if (const auto format =
3630 static_cast<aidl::android::hardware::graphics::common::PixelFormat>(
3631 mBufferInfo.mBuffer->getPixelFormat());
3632 err == OK && kVendorVersion < __ANDROID_API_U__ &&
3633 (format ==
3634 aidl::android::hardware::graphics::common::PixelFormat::
3635 IMPLEMENTATION_DEFINED ||
3636 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_420_888 ||
3637 format == aidl::android::hardware::graphics::common::PixelFormat::YV12 ||
3638 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_P010)) {
3639 mBufferInfo.mBuffer->remapBuffer();
3640 }
3641 }
3642 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003643 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003644 mFlinger->mHdrLayerInfoChanged = true;
3645 }
Sally Qi963049b2023-03-23 14:06:21 -07003646 if (mBufferInfo.mDesiredHdrSdrRatio != mDrawingState.desiredHdrSdrRatio) {
3647 mBufferInfo.mDesiredHdrSdrRatio = mDrawingState.desiredHdrSdrRatio;
John Reck68796592023-01-25 13:47:12 -05003648 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003649 }
3650 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3651 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3652 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3653 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3654 mBufferInfo.mApi = mDrawingState.api;
3655 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003656}
3657
3658Rect Layer::computeBufferCrop(const State& s) {
3659 if (s.buffer && !s.bufferCrop.isEmpty()) {
3660 Rect bufferCrop;
3661 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3662 return bufferCrop;
3663 } else if (s.buffer) {
3664 return s.buffer->getBounds();
3665 } else {
3666 return s.bufferCrop;
3667 }
3668}
3669
Vishnu Nairde177252023-04-21 12:44:10 -07003670sp<Layer> Layer::createClone(uint32_t mirrorRootId) {
Kean Mariotti4ba343c2023-04-19 13:31:02 +00003671 surfaceflinger::LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0,
3672 LayerMetadata());
Patrick Williams83f36b22022-09-14 17:57:35 +00003673 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Vishnu Nairde177252023-04-21 12:44:10 -07003674 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this), mirrorRootId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003675 return layer;
3676}
3677
Patrick Williamsbb25f802022-08-30 23:02:34 +00003678void Layer::decrementPendingBufferCount() {
3679 int32_t pendingBuffers = --mPendingBufferTransactions;
3680 tracePendingBufferCount(pendingBuffers);
3681}
3682
3683void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3684 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3685}
3686
3687/*
3688 * We don't want to send the layer's transform to input, but rather the
3689 * parent's transform. This is because Layer's transform is
3690 * information about how the buffer is placed on screen. The parent's
3691 * transform makes more sense to send since it's information about how the
3692 * layer is placed on screen. This transform is used by input to determine
3693 * how to go from screen space back to window space.
3694 */
3695ui::Transform Layer::getInputTransform() const {
3696 if (!hasBufferOrSidebandStream()) {
3697 return getTransform();
3698 }
3699 sp<Layer> parent = mDrawingParent.promote();
3700 if (parent == nullptr) {
3701 return ui::Transform();
3702 }
3703
3704 return parent->getTransform();
3705}
3706
3707/**
Vishnu Nairfed7c122023-03-18 01:54:43 +00003708 * Returns the bounds used to fill the input frame and the touchable region.
3709 *
Patrick Williamsbb25f802022-08-30 23:02:34 +00003710 * Similar to getInputTransform, we need to update the bounds to include the transform.
3711 * This is because bounds don't include the buffer transform, where the input assumes
3712 * that's already included.
3713 */
Vishnu Nairfed7c122023-03-18 01:54:43 +00003714std::pair<FloatRect, bool> Layer::getInputBounds(bool fillParentBounds) const {
3715 Rect croppedBufferSize = getCroppedBufferSize(getDrawingState());
3716 FloatRect inputBounds = croppedBufferSize.toFloatRect();
3717 if (hasBufferOrSidebandStream() && croppedBufferSize.isValid() &&
3718 mDrawingState.transform.getType() != ui::Transform::IDENTITY) {
3719 inputBounds = mDrawingState.transform.transform(inputBounds);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003720 }
3721
Vishnu Nairfed7c122023-03-18 01:54:43 +00003722 bool inputBoundsValid = croppedBufferSize.isValid();
3723 if (!inputBoundsValid) {
3724 /**
3725 * Input bounds are based on the layer crop or buffer size. But if we are using
3726 * the layer bounds as the input bounds (replaceTouchableRegionWithCrop flag) then
3727 * we can use the parent bounds as the input bounds if the layer does not have buffer
3728 * or a crop. We want to unify this logic but because of compat reasons we cannot always
3729 * use the parent bounds. A layer without a buffer can get input. So when a window is
3730 * initially added, its touchable region can fill its parent layer bounds and that can
3731 * have negative consequences.
3732 */
3733 inputBounds = fillParentBounds ? mBounds : FloatRect{};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003734 }
Vishnu Nairfed7c122023-03-18 01:54:43 +00003735
3736 // Clamp surface inset to the input bounds.
3737 const float inset = static_cast<float>(mDrawingState.inputInfo.surfaceInset);
3738 const float xSurfaceInset = std::clamp(inset, 0.f, inputBounds.getWidth() / 2.f);
3739 const float ySurfaceInset = std::clamp(inset, 0.f, inputBounds.getHeight() / 2.f);
3740
3741 // Apply the insets to the input bounds.
3742 inputBounds.left += xSurfaceInset;
3743 inputBounds.top += ySurfaceInset;
3744 inputBounds.right -= xSurfaceInset;
3745 inputBounds.bottom -= ySurfaceInset;
3746
3747 return {inputBounds, inputBoundsValid};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003748}
3749
Ady Abraham005398b2023-06-05 13:59:41 -07003750bool Layer::isSimpleBufferUpdate(const layer_state_t& s) const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003751 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3752
3753 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3754 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3755 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3756 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3757 layer_state_t::eReparent;
3758
Patrick Williamsbb25f802022-08-30 23:02:34 +00003759 if ((s.what & requiredFlags) != requiredFlags) {
Ady Abraham005398b2023-06-05 13:59:41 -07003760 ATRACE_FORMAT_INSTANT("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3761 (s.what | requiredFlags) & ~s.what);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003762 return false;
3763 }
3764
3765 if (s.what & deniedFlags) {
Ady Abraham005398b2023-06-05 13:59:41 -07003766 ATRACE_FORMAT_INSTANT("%s: false [has denied flags 0x%" PRIx64 "]", __func__,
3767 s.what & deniedFlags);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003768 return false;
3769 }
3770
Patrick Williamsbb25f802022-08-30 23:02:34 +00003771 if (s.what & layer_state_t::ePositionChanged) {
3772 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
Ady Abraham005398b2023-06-05 13:59:41 -07003773 ATRACE_FORMAT_INSTANT("%s: false [ePositionChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003774 return false;
3775 }
3776 }
3777
3778 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003779 if (mDrawingState.color.a != s.color.a) {
Ady Abraham005398b2023-06-05 13:59:41 -07003780 ATRACE_FORMAT_INSTANT("%s: false [eAlphaChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003781 return false;
3782 }
3783 }
3784
3785 if (s.what & layer_state_t::eColorTransformChanged) {
3786 if (mDrawingState.colorTransform != s.colorTransform) {
Ady Abraham005398b2023-06-05 13:59:41 -07003787 ATRACE_FORMAT_INSTANT("%s: false [eColorTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003788 return false;
3789 }
3790 }
3791
3792 if (s.what & layer_state_t::eBackgroundColorChanged) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003793 if (mDrawingState.bgColorLayer || s.bgColor.a != 0) {
Ady Abraham005398b2023-06-05 13:59:41 -07003794 ATRACE_FORMAT_INSTANT("%s: false [eBackgroundColorChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003795 return false;
3796 }
3797 }
3798
3799 if (s.what & layer_state_t::eMatrixChanged) {
3800 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3801 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3802 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3803 mRequestedTransform.dsdy() != s.matrix.dsdy) {
Ady Abraham005398b2023-06-05 13:59:41 -07003804 ATRACE_FORMAT_INSTANT("%s: false [eMatrixChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003805 return false;
3806 }
3807 }
3808
3809 if (s.what & layer_state_t::eCornerRadiusChanged) {
3810 if (mDrawingState.cornerRadius != s.cornerRadius) {
Ady Abraham005398b2023-06-05 13:59:41 -07003811 ATRACE_FORMAT_INSTANT("%s: false [eCornerRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003812 return false;
3813 }
3814 }
3815
3816 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3817 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
Ady Abraham005398b2023-06-05 13:59:41 -07003818 ATRACE_FORMAT_INSTANT("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003819 return false;
3820 }
3821 }
3822
Vishnu Nairbbceb462022-10-10 04:52:13 +00003823 if (s.what & layer_state_t::eBufferTransformChanged) {
3824 if (mDrawingState.bufferTransform != s.bufferTransform) {
Ady Abraham005398b2023-06-05 13:59:41 -07003825 ATRACE_FORMAT_INSTANT("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003826 return false;
3827 }
3828 }
3829
3830 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3831 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
Ady Abraham005398b2023-06-05 13:59:41 -07003832 ATRACE_FORMAT_INSTANT("%s: false [eTransformToDisplayInverseChanged changed]",
3833 __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003834 return false;
3835 }
3836 }
3837
3838 if (s.what & layer_state_t::eCropChanged) {
3839 if (mDrawingState.crop != s.crop) {
Ady Abraham005398b2023-06-05 13:59:41 -07003840 ATRACE_FORMAT_INSTANT("%s: false [eCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003841 return false;
3842 }
3843 }
3844
3845 if (s.what & layer_state_t::eDataspaceChanged) {
3846 if (mDrawingState.dataspace != s.dataspace) {
Ady Abraham005398b2023-06-05 13:59:41 -07003847 ATRACE_FORMAT_INSTANT("%s: false [eDataspaceChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003848 return false;
3849 }
3850 }
3851
3852 if (s.what & layer_state_t::eHdrMetadataChanged) {
3853 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
Ady Abraham005398b2023-06-05 13:59:41 -07003854 ATRACE_FORMAT_INSTANT("%s: false [eHdrMetadataChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003855 return false;
3856 }
3857 }
3858
3859 if (s.what & layer_state_t::eSidebandStreamChanged) {
3860 if (mDrawingState.sidebandStream != s.sidebandStream) {
Ady Abraham005398b2023-06-05 13:59:41 -07003861 ATRACE_FORMAT_INSTANT("%s: false [eSidebandStreamChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003862 return false;
3863 }
3864 }
3865
3866 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3867 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
Ady Abraham005398b2023-06-05 13:59:41 -07003868 ATRACE_FORMAT_INSTANT("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003869 return false;
3870 }
3871 }
3872
3873 if (s.what & layer_state_t::eShadowRadiusChanged) {
3874 if (mDrawingState.shadowRadius != s.shadowRadius) {
Ady Abraham005398b2023-06-05 13:59:41 -07003875 ATRACE_FORMAT_INSTANT("%s: false [eShadowRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003876 return false;
3877 }
3878 }
3879
3880 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3881 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
Ady Abraham005398b2023-06-05 13:59:41 -07003882 ATRACE_FORMAT_INSTANT("%s: false [eFixedTransformHintChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003883 return false;
3884 }
3885 }
3886
3887 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3888 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
Ady Abraham005398b2023-06-05 13:59:41 -07003889 ATRACE_FORMAT_INSTANT("%s: false [eTrustedOverlayChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003890 return false;
3891 }
3892 }
3893
3894 if (s.what & layer_state_t::eStretchChanged) {
3895 StretchEffect temp = s.stretchEffect;
3896 temp.sanitize();
3897 if (mDrawingState.stretchEffect != temp) {
Ady Abraham005398b2023-06-05 13:59:41 -07003898 ATRACE_FORMAT_INSTANT("%s: false [eStretchChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003899 return false;
3900 }
3901 }
3902
3903 if (s.what & layer_state_t::eBufferCropChanged) {
3904 if (mDrawingState.bufferCrop != s.bufferCrop) {
Ady Abraham005398b2023-06-05 13:59:41 -07003905 ATRACE_FORMAT_INSTANT("%s: false [eBufferCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003906 return false;
3907 }
3908 }
3909
3910 if (s.what & layer_state_t::eDestinationFrameChanged) {
3911 if (mDrawingState.destinationFrame != s.destinationFrame) {
Ady Abraham005398b2023-06-05 13:59:41 -07003912 ATRACE_FORMAT_INSTANT("%s: false [eDestinationFrameChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003913 return false;
3914 }
3915 }
3916
3917 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3918 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
Ady Abraham005398b2023-06-05 13:59:41 -07003919 ATRACE_FORMAT_INSTANT("%s: false [eDimmingEnabledChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003920 return false;
3921 }
3922 }
3923
John Reck68796592023-01-25 13:47:12 -05003924 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
Sally Qi963049b2023-03-23 14:06:21 -07003925 if (mDrawingState.currentHdrSdrRatio != s.currentHdrSdrRatio ||
3926 mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
Ady Abraham005398b2023-06-05 13:59:41 -07003927 ATRACE_FORMAT_INSTANT("%s: false [eExtendedRangeBrightnessChanged changed]", __func__);
John Reck68796592023-01-25 13:47:12 -05003928 return false;
3929 }
3930 }
3931
Patrick Williamsbb25f802022-08-30 23:02:34 +00003932 return true;
3933}
3934
Vishnu Naire14c6b32022-08-06 04:20:15 +00003935sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003936 // There's no need to get a CE Layer if the layer isn't going to draw anything.
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003937 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003938}
3939
Vishnu Naire14c6b32022-08-06 04:20:15 +00003940const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003941 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003942}
3943
Vishnu Naire14c6b32022-08-06 04:20:15 +00003944LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003945 return mSnapshot.get();
3946}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003947
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003948std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
3949 return std::move(mSnapshot);
3950}
3951
3952void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
3953 mSnapshot = std::move(snapshot);
3954}
3955
Patrick Williamsbb25f802022-08-30 23:02:34 +00003956const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003957 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003958}
3959
Patrick Williams7584c6a2022-10-29 02:10:58 +00003960sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003961 auto result = mFlinger->getFactory().createLayerFE(mName);
Patrick Williams7584c6a2022-10-29 02:10:58 +00003962 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3963 return result;
3964}
3965
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003966sp<LayerFE> Layer::getCompositionEngineLayerFE(
3967 const frontend::LayerHierarchy::TraversalPath& path) {
3968 for (auto& [p, layerFE] : mLayerFEs) {
3969 if (p == path) {
3970 return layerFE;
3971 }
3972 }
3973 auto layerFE = mFlinger->getFactory().createLayerFE(mName);
3974 mLayerFEs.emplace_back(path, layerFE);
3975 return layerFE;
3976}
3977
Patrick Williamsbb25f802022-08-30 23:02:34 +00003978void Layer::useSurfaceDamage() {
3979 if (mFlinger->mForceFullDamage) {
3980 surfaceDamageRegion = Region::INVALID_REGION;
3981 } else {
3982 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3983 }
3984}
3985
3986void Layer::useEmptyDamage() {
3987 surfaceDamageRegion.clear();
3988}
3989
3990bool Layer::isOpaque(const Layer::State& s) const {
3991 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3992 // layer's opaque flag.
3993 if (!hasSomethingToDraw()) {
3994 return false;
3995 }
3996
3997 // if the layer has the opaque flag, then we're always opaque
3998 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3999 return true;
4000 }
4001
4002 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004003 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004004 return true;
4005 }
4006
4007 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
4008 return fillsColor() && getAlpha() == 1.0_hf;
4009}
4010
4011bool Layer::canReceiveInput() const {
4012 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
4013}
4014
4015bool Layer::isVisible() const {
4016 if (!hasSomethingToDraw()) {
4017 return false;
4018 }
4019
4020 if (isHiddenByPolicy()) {
4021 return false;
4022 }
4023
4024 return getAlpha() > 0.0f || hasBlur();
4025}
4026
Leon Scroggins III5b581492023-10-31 14:29:41 -04004027void Layer::onCompositionPresented(const DisplayDevice* display,
4028 const std::shared_ptr<FenceTime>& glDoneFence,
4029 const std::shared_ptr<FenceTime>& presentFence,
4030 const CompositorTiming& compositorTiming) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004031 // mFrameLatencyNeeded is true when a new frame was latched for the
4032 // composition.
4033 if (!mBufferInfo.mFrameLatencyNeeded) return;
4034
4035 for (const auto& handle : mDrawingState.callbackHandles) {
4036 handle->gpuCompositionDoneFence = glDoneFence;
4037 handle->compositorTiming = compositorTiming;
4038 }
4039
4040 // Update mFrameTracker.
4041 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
4042 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
4043
4044 const int32_t layerId = getSequence();
4045 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
4046
4047 const auto outputLayer = findOutputLayerForDisplay(display);
4048 if (outputLayer && outputLayer->requiresClientComposition()) {
4049 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
4050 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
4051 clientCompositionTimestamp,
4052 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
4053 // Update the SurfaceFrames in the drawing state
4054 if (mDrawingState.bufferSurfaceFrameTX) {
4055 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
4056 }
4057 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
4058 surfaceFrame->setGpuComposition();
4059 }
4060 }
4061
4062 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
4063 if (frameReadyFence->isValid()) {
4064 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
4065 } else {
4066 // There was no fence for this frame, so assume that it was ready
4067 // to be presented at the desired present time.
4068 mFrameTracker.setFrameReadyTime(desiredPresentTime);
4069 }
4070
4071 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08004072 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004073 const std::optional<Fps> renderRate =
4074 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
4075
Alec Mouri7c1d8b52023-08-29 20:14:46 +00004076 const auto vote = frameRateToSetFrameRateVotePayload(getFrameRateForLayerTree());
Patrick Williamsbb25f802022-08-30 23:02:34 +00004077 const auto gameMode = getGameMode();
4078
4079 if (presentFence->isValid()) {
4080 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
4081 refreshRate, renderRate, vote, gameMode);
4082 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
4083 presentFence,
4084 FrameTracer::FrameEvent::PRESENT_FENCE);
4085 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
4086 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
4087 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04004088 // The HWC doesn't support present fences, so use the present timestamp instead.
4089 const nsecs_t presentTimestamp =
4090 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
4091
4092 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
4093 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
4094 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
4095
Patrick Williamsbb25f802022-08-30 23:02:34 +00004096 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
4097 refreshRate, renderRate, vote, gameMode);
4098 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
4099 mCurrentFrameNumber, actualPresentTime,
4100 FrameTracer::FrameEvent::PRESENT_FENCE);
4101 mFrameTracker.setActualPresentTime(actualPresentTime);
4102 }
4103 }
4104
4105 mFrameTracker.advanceFrame();
4106 mBufferInfo.mFrameLatencyNeeded = false;
4107}
4108
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004109bool Layer::willReleaseBufferOnLatch() const {
4110 return !mDrawingState.buffer && mBufferInfo.mBuffer;
4111}
4112
Patrick Williamsbb25f802022-08-30 23:02:34 +00004113bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00004114 const bool bgColorOnly = mDrawingState.bgColorLayer != nullptr;
4115 return latchBufferImpl(recomputeVisibleRegions, latchTime, bgColorOnly);
4116}
4117
4118bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004119 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
4120 getDrawingState().frameNumber);
4121
4122 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
4123
4124 if (refreshRequired) {
4125 return refreshRequired;
4126 }
4127
4128 // If the head buffer's acquire fence hasn't signaled yet, return and
4129 // try again later
4130 if (!fenceHasSignaled()) {
4131 ATRACE_NAME("!fenceHasSignaled()");
4132 mFlinger->onLayerUpdate();
4133 return false;
4134 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00004135 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00004136
4137 // Capture the old state of the layer for comparisons later
4138 BufferInfo oldBufferInfo = mBufferInfo;
4139 const bool oldOpacity = isOpaque(mDrawingState);
4140 mPreviousFrameNumber = mCurrentFrameNumber;
4141 mCurrentFrameNumber = mDrawingState.frameNumber;
4142 gatherBufferInfo();
4143
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004144 if (mBufferInfo.mBuffer) {
4145 // We latched a buffer that will be presented soon. Clear the previously presented layer
4146 // stack list.
4147 mPreviouslyPresentedLayerStacks.clear();
4148 }
4149
4150 if (mDrawingState.buffer == nullptr) {
4151 const bool bufferReleased = oldBufferInfo.mBuffer != nullptr;
4152 recomputeVisibleRegions = bufferReleased;
4153 return bufferReleased;
4154 }
4155
Patrick Williamsbb25f802022-08-30 23:02:34 +00004156 if (oldBufferInfo.mBuffer == nullptr) {
4157 // the first time we receive a buffer, we need to trigger a
4158 // geometry invalidation.
4159 recomputeVisibleRegions = true;
4160 }
4161
4162 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
4163 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
4164 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
4165 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
4166 recomputeVisibleRegions = true;
4167 }
4168
4169 if (oldBufferInfo.mBuffer != nullptr) {
4170 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
4171 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
4172 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
4173 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
4174 recomputeVisibleRegions = true;
4175 }
4176 }
4177
4178 if (oldOpacity != isOpaque(mDrawingState)) {
4179 recomputeVisibleRegions = true;
4180 }
4181
4182 return true;
4183}
4184
4185bool Layer::hasReadyFrame() const {
4186 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
4187}
4188
4189bool Layer::isProtected() const {
4190 return (mBufferInfo.mBuffer != nullptr) &&
4191 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
4192}
4193
Patrick Williamsbb25f802022-08-30 23:02:34 +00004194void Layer::latchAndReleaseBuffer() {
4195 if (hasReadyFrame()) {
4196 bool ignored = false;
4197 latchBuffer(ignored, systemTime());
4198 }
4199 releasePendingBuffer(systemTime());
4200}
4201
4202PixelFormat Layer::getPixelFormat() const {
4203 return mBufferInfo.mPixelFormat;
4204}
4205
4206bool Layer::getTransformToDisplayInverse() const {
4207 return mBufferInfo.mTransformToDisplayInverse;
4208}
4209
4210Rect Layer::getBufferCrop() const {
4211 // this is the crop rectangle that applies to the buffer
4212 // itself (as opposed to the window)
4213 if (!mBufferInfo.mCrop.isEmpty()) {
4214 // if the buffer crop is defined, we use that
4215 return mBufferInfo.mCrop;
4216 } else if (mBufferInfo.mBuffer != nullptr) {
4217 // otherwise we use the whole buffer
4218 return mBufferInfo.mBuffer->getBounds();
4219 } else {
4220 // if we don't have a buffer yet, we use an empty/invalid crop
4221 return Rect();
4222 }
4223}
4224
4225uint32_t Layer::getBufferTransform() const {
4226 return mBufferInfo.mTransform;
4227}
4228
4229ui::Dataspace Layer::getDataSpace() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004230 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
4231}
4232
4233ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
4234 ui::Dataspace updatedDataspace = dataspace;
4235 // translate legacy dataspaces to modern dataspaces
4236 switch (dataspace) {
Alec Mouri74c7ae12023-03-26 02:57:47 +00004237 // Treat unknown dataspaces as V0_sRGB
4238 case ui::Dataspace::UNKNOWN:
Patrick Williamsbb25f802022-08-30 23:02:34 +00004239 case ui::Dataspace::SRGB:
4240 updatedDataspace = ui::Dataspace::V0_SRGB;
4241 break;
4242 case ui::Dataspace::SRGB_LINEAR:
4243 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
4244 break;
4245 case ui::Dataspace::JFIF:
4246 updatedDataspace = ui::Dataspace::V0_JFIF;
4247 break;
4248 case ui::Dataspace::BT601_625:
4249 updatedDataspace = ui::Dataspace::V0_BT601_625;
4250 break;
4251 case ui::Dataspace::BT601_525:
4252 updatedDataspace = ui::Dataspace::V0_BT601_525;
4253 break;
4254 case ui::Dataspace::BT709:
4255 updatedDataspace = ui::Dataspace::V0_BT709;
4256 break;
4257 default:
4258 break;
4259 }
4260
4261 return updatedDataspace;
4262}
4263
4264sp<GraphicBuffer> Layer::getBuffer() const {
4265 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4266}
4267
Vishnu Nairb76d99a2023-03-19 18:22:31 -07004268void Layer::setTransformHintLegacy(ui::Transform::RotationFlags displayTransformHint) {
4269 mTransformHintLegacy = getFixedTransformHint();
4270 if (mTransformHintLegacy == ui::Transform::ROT_INVALID) {
4271 mTransformHintLegacy = displayTransformHint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004272 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07004273 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004274}
4275
4276const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4277 return mBufferInfo.mBuffer;
4278}
4279
4280bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00004281 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004282 return false;
4283 }
4284
4285 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00004286 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004287 mDrawingState.modified = true;
4288 setTransactionFlags(eTransactionNeeded);
4289 return true;
4290}
4291
4292bool Layer::fillsColor() const {
4293 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4294 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4295}
4296
4297bool Layer::hasBlur() const {
4298 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4299}
4300
Vishnu Nairba354102022-08-01 00:14:18 +00004301void Layer::updateSnapshot(bool updateGeometry) {
4302 if (!getCompositionEngineLayerFE()) {
4303 return;
4304 }
4305
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004306 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004307 if (updateGeometry) {
4308 prepareBasicGeometryCompositionState();
4309 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004310 snapshot->roundedCorner = getRoundedCornerState();
4311 snapshot->stretchEffect = getStretchEffect();
4312 snapshot->transformedBounds = mScreenBounds;
4313 if (mEffectiveShadowRadius > 0.f) {
4314 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4315
4316 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4317 // it if transparent regions are present. This may not be necessary since shadows are
4318 // typically cast by layers without transparent regions.
4319 snapshot->shadowSettings.boundaries = mBounds;
4320
4321 const float casterAlpha = snapshot->alpha;
4322 const bool casterIsOpaque =
4323 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4324
4325 // If the casting layer is translucent, we need to fill in the shadow underneath the
4326 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4327 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4328 snapshot->shadowSettings.ambientColor *= casterAlpha;
4329 snapshot->shadowSettings.spotColor *= casterAlpha;
4330 }
4331 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004332 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004333 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004334 snapshot->layerOpaqueFlagSet =
4335 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004336 sp<Layer> p = mDrawingParent.promote();
4337 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004338 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004339 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004340 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004341 }
4342 snapshot->bufferSize = getBufferSize(mDrawingState);
4343 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004344 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00004345 preparePerFrameCompositionState();
4346}
4347
Vishnu Naire14c6b32022-08-06 04:20:15 +00004348void Layer::updateChildrenSnapshots(bool updateGeometry) {
4349 for (const sp<Layer>& child : mDrawingChildren) {
4350 child->updateSnapshot(updateGeometry);
4351 child->updateChildrenSnapshots(updateGeometry);
4352 }
4353}
4354
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004355void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4356 mSnapshot->layerMetadata = parentMetadata;
4357 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4358 for (const sp<Layer>& child : mDrawingChildren) {
4359 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4360 }
4361}
4362
4363void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4364 std::unordered_set<Layer*>& visited) {
4365 if (visited.find(this) != visited.end()) {
4366 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4367 return;
4368 }
4369 visited.insert(this);
4370
4371 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4372
4373 if (mDrawingState.zOrderRelatives.empty()) {
4374 return;
4375 }
4376 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4377 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4378 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4379 sp<Layer> relative = weakRelative.promote();
4380 if (!relative) {
4381 continue;
4382 }
4383 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4384 }
4385}
4386
Chavi Weingarten328a8312023-01-26 21:17:52 +00004387bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00004388 TrustedPresentationListener const& listener) {
4389 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4390 mTrustedPresentationListener = listener;
4391 mTrustedPresentationThresholds = thresholds;
4392 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4393 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4394 mFlinger->mNumTrustedPresentationListeners++;
4395 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4396 mFlinger->mNumTrustedPresentationListeners--;
4397 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00004398
4399 // Reset trusted presentation states to ensure we start the time again.
4400 mEnteredTrustedPresentationStateTime = -1;
4401 mLastReportedTrustedPresentationState = false;
4402 mLastComputedTrustedPresentationState = false;
4403
4404 // If there's a new trusted presentation listener, the code needs to go through the composite
4405 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
4406 // we're already in the requested state.
4407 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00004408}
4409
Vishnu Naira156f482023-02-22 00:23:38 +00004410void Layer::updateLastLatchTime(nsecs_t latchTime) {
4411 mLastLatchTime = latchTime;
4412}
4413
Arthur Hung69f95222023-10-04 07:39:02 +00004414void Layer::setIsSmallDirty(const Region& damageRegion,
4415 const ui::Transform& layerToDisplayTransform) {
4416 mSmallDirty = false;
Arthur Hungc70bee22023-06-02 01:35:52 +00004417 if (!mFlinger->mScheduler->supportSmallDirtyDetection()) {
4418 return;
4419 }
4420
4421 if (mWindowType != WindowInfo::Type::APPLICATION &&
4422 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
4423 return;
4424 }
Arthur Hung69f95222023-10-04 07:39:02 +00004425
4426 Rect bounds = damageRegion.getBounds();
Arthur Hungc70bee22023-06-02 01:35:52 +00004427 if (!bounds.isValid()) {
4428 return;
4429 }
4430
Arthur Hung69f95222023-10-04 07:39:02 +00004431 // Transform to screen space.
4432 bounds = layerToDisplayTransform.transform(bounds);
4433
Arthur Hungc70bee22023-06-02 01:35:52 +00004434 // If the damage region is a small dirty, this could give the hint for the layer history that
4435 // it could suppress the heuristic rate when calculating.
Tony Huangf3621102023-09-04 17:14:22 +08004436 mSmallDirty = mFlinger->mScheduler->isSmallDirtyArea(mOwnerAppId,
Tony Huang9ac5e6e2023-08-24 09:01:44 +00004437 bounds.getWidth() * bounds.getHeight());
Arthur Hungc70bee22023-06-02 01:35:52 +00004438}
4439
Arthur Hung69f95222023-10-04 07:39:02 +00004440void Layer::setIsSmallDirty(frontend::LayerSnapshot* snapshot) {
4441 setIsSmallDirty(snapshot->surfaceDamage, snapshot->localTransform);
4442 snapshot->isSmallDirty = mSmallDirty;
4443}
4444
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004445} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004446
4447#if defined(__gl_h_)
4448#error "don't include gl/gl.h in this file"
4449#endif
4450
4451#if defined(__gl2_h_)
4452#error "don't include gl2/gl2.h in this file"
4453#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004454
4455// TODO(b/129481165): remove the #pragma below and fix conversion issues
4456#pragma clang diagnostic pop // ignored "-Wconversion"