blob: 31b5e28e4ea59365b25e037b2362aa19df47f523 [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;
173 mDrawingState.crop.makeInvalid();
174 mDrawingState.acquireFence = sp<Fence>::make(-1);
175 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
Alec Mouri74c7ae12023-03-26 02:57:47 +0000176 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Robert Carr6a160312021-05-17 12:08:20 -0700177 mDrawingState.hdrMetadata.validTypes = 0;
178 mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
179 mDrawingState.cornerRadius = 0.0f;
180 mDrawingState.backgroundBlurRadius = 0;
181 mDrawingState.api = -1;
182 mDrawingState.hasColorTransform = false;
183 mDrawingState.colorSpaceAgnostic = false;
184 mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
185 mDrawingState.metadata = args.metadata;
186 mDrawingState.shadowRadius = 0.f;
187 mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
188 mDrawingState.frameTimelineInfo = {};
189 mDrawingState.postTime = -1;
190 mDrawingState.destinationFrame.makeInvalid();
Robin Leeedb375d2021-09-10 12:03:42 +0000191 mDrawingState.isTrustedOverlay = false;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -0700192 mDrawingState.dropInputMode = gui::DropInputMode::NONE;
Sally Qi81d95e62022-03-21 19:41:33 -0700193 mDrawingState.dimmingEnabled = true;
Andy Labrada096227e2022-06-15 16:58:11 +0000194 mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
Rachel Lee58cc90d2023-09-05 18:50:20 -0700195 mDrawingState.frameRateSelectionStrategy = FrameRateSelectionStrategy::Self;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700196
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700197 if (args.flags & ISurfaceComposerClient::eNoColorFill) {
198 // Set an invalid color so there is no color fill.
Robert Carr6a160312021-05-17 12:08:20 -0700199 mDrawingState.color.r = -1.0_hf;
200 mDrawingState.color.g = -1.0_hf;
201 mDrawingState.color.b = -1.0_hf;
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700202 }
Dominik Laskowski4376bd82022-07-07 11:50:20 -0700203
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500204 mFrameTracker.setDisplayRefreshPeriod(
205 args.flinger->mScheduler->getPacesetterVsyncPeriod().ns());
Robert Carr2e102c92018-10-23 12:11:15 -0700206
Vishnu Naircb8be502022-10-12 19:03:23 +0000207 mOwnerUid = args.ownerUid;
208 mOwnerPid = args.ownerPid;
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;
575 snapshot->shadowRadius = 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();
790 jankData.emplace_back(
791 JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
792 }
793 mPendingJankClassifications.pop_front();
794 }
795}
796
Mathias Agopian13127d82013-03-05 17:47:11 -0800797// ----------------------------------------------------------------------------
798// transaction
799// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800800
Vishnu Naira156f482023-02-22 00:23:38 +0000801uint32_t Layer::doTransaction(uint32_t flags) {
Marissa Wall61c58622018-07-18 10:12:20 -0700802 ATRACE_CALL();
803
Robert Carr0758e5d2021-03-11 22:15:04 -0800804 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700805 mDrawingStateModified = mDrawingState.modified;
806 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700807
Alec Mourib416efd2018-09-06 21:01:59 +0000808 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700809
Robert Carr6a160312021-05-17 12:08:20 -0700810 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800811 // invalidate and recompute the visible regions if needed
812 flags |= Layer::eVisibleRegion;
813 }
814
Robert Carr6a160312021-05-17 12:08:20 -0700815 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800816 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000817 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800818 flags |= eVisibleRegion;
819 this->contentDirty = true;
820
821 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700822 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800823 }
824
Arthur Hung9ed43392022-05-27 06:31:57 +0000825 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
826 mFlinger->mUpdateInputInfo = true;
827 }
828
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700829 commitTransaction();
Robert Carra1257842020-01-31 13:48:28 -0800830
Mathias Agopian13127d82013-03-05 17:47:11 -0800831 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800832}
833
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700834void Layer::commitTransaction() {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000835 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
836 // bufferSurfaceFrameTX will be presented in latchBuffer.
837 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
838 if (surfaceFrame->getPresentState() != PresentState::Presented) {
839 // With applyPendingStates, we could end up having presented surfaceframes from previous
840 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800841 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000842 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
843 }
844 }
Robert Carr6a160312021-05-17 12:08:20 -0700845 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700846}
847
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700848uint32_t Layer::clearTransactionFlags(uint32_t mask) {
849 const auto flags = mTransactionFlags & mask;
850 mTransactionFlags &= ~mask;
851 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800852}
853
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700854void Layer::setTransactionFlags(uint32_t mask) {
855 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800856}
857
Robert Carr1f0a16a2016-10-24 16:27:39 -0700858bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
859 ssize_t idx = mCurrentChildren.indexOf(childLayer);
860 if (idx < 0) {
861 return false;
862 }
863 if (childLayer->setLayer(z)) {
864 mCurrentChildren.removeAt(idx);
865 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800866 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700867 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800868 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700869}
870
Robert Carr503c7042017-09-27 15:06:08 -0700871bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
872 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
873 ssize_t idx = mCurrentChildren.indexOf(childLayer);
874 if (idx < 0) {
875 return false;
876 }
877 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
878 mCurrentChildren.removeAt(idx);
879 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800880 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700881 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800882 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700883}
884
Robert Carrae060832016-11-28 10:51:00 -0800885bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700886 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
887 mDrawingState.sequence++;
888 mDrawingState.z = z;
889 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700890
Robert Carra70e91c2021-06-11 13:59:52 -0700891 mFlinger->mSomeChildrenChanged = true;
892
Robert Carrdb66e622017-04-10 16:55:57 -0700893 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700894 if (mDrawingState.zOrderRelativeOf != nullptr) {
895 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700896 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700897 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700898 }
chaviw606e5cf2019-03-01 10:12:10 -0800899 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700900 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800901 setTransactionFlags(eTransactionNeeded);
902 return true;
903}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700904
Robert Carrdb66e622017-04-10 16:55:57 -0700905void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700906 mDrawingState.zOrderRelatives.remove(relative);
907 mDrawingState.sequence++;
908 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700909 setTransactionFlags(eTransactionNeeded);
910}
911
912void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700913 mDrawingState.zOrderRelatives.add(relative);
914 mDrawingState.modified = true;
915 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700916 setTransactionFlags(eTransactionNeeded);
917}
918
chaviw606e5cf2019-03-01 10:12:10 -0800919void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700920 mDrawingState.zOrderRelativeOf = relativeOf;
921 mDrawingState.sequence++;
922 mDrawingState.modified = true;
923 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700924
chaviw606e5cf2019-03-01 10:12:10 -0800925 setTransactionFlags(eTransactionNeeded);
926}
927
Robert Carr503d2bd2017-12-04 15:49:47 -0800928bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000929 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700930 if (relative == nullptr) {
931 return false;
932 }
933
Robert Carr6a160312021-05-17 12:08:20 -0700934 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
935 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800936 return false;
937 }
938
Robert Carr88b85e12022-03-21 15:47:35 -0700939 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
940 (relative->mDrawingState.zOrderRelativeOf == this)) {
941 ALOGE("Detected relative layer loop between %s and %s",
942 mName.c_str(), relative->mName.c_str());
943 ALOGE("Ignoring new call to set relative layer");
944 return false;
945 }
946
Robert Carra70e91c2021-06-11 13:59:52 -0700947 mFlinger->mSomeChildrenChanged = true;
948
Robert Carr6a160312021-05-17 12:08:20 -0700949 mDrawingState.sequence++;
950 mDrawingState.modified = true;
951 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700952
Robert Carr6a160312021-05-17 12:08:20 -0700953 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700954 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700955 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700956 }
chaviw606e5cf2019-03-01 10:12:10 -0800957 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700958 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700959
960 setTransactionFlags(eTransactionNeeded);
961
962 return true;
963}
964
Winson Chunga30f7c92021-06-29 15:42:56 -0700965bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
966 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
967 mDrawingState.isTrustedOverlay = isTrustedOverlay;
968 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000969 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700970 setTransactionFlags(eTransactionNeeded);
971 return true;
972}
973
974bool Layer::isTrustedOverlay() const {
975 if (getDrawingState().isTrustedOverlay) {
976 return true;
977 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000978 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700979 return (p != nullptr) && p->isTrustedOverlay();
980}
981
Dan Stoza9e56aa02015-11-02 13:00:03 -0800982bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700983 if (mDrawingState.color.a == alpha) return false;
984 mDrawingState.sequence++;
985 mDrawingState.color.a = alpha;
986 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800987 setTransactionFlags(eTransactionNeeded);
988 return true;
989}
chaviw13fdc492017-06-27 12:40:18 -0700990
Valerie Haudd0b7572019-01-29 14:59:27 -0800991bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700992 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700993 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800994 }
Robert Carr6a160312021-05-17 12:08:20 -0700995 mDrawingState.sequence++;
996 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -0800997 setTransactionFlags(eTransactionNeeded);
998
Robert Carr6a160312021-05-17 12:08:20 -0700999 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -08001000 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -08001001 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001002 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -07001003 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Kean Mariotti4ba343c2023-04-19 13:31:02 +00001004 surfaceflinger::LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
1005 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -07001006
Valerie Haudd0b7572019-01-29 14:59:27 -08001007 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -07001008 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -08001009 mFlinger->mLayersAdded = true;
1010 // set up SF to handle added color layer
1011 if (isRemovedFromCurrentState()) {
Josh Gao194ff392022-09-08 16:19:29 -07001012 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001013 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001014 }
1015 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001016 } else if (mDrawingState.bgColorLayer && alpha == 0) {
Josh Gao194ff392022-09-08 16:19:29 -07001017 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001018 mDrawingState.bgColorLayer->reparent(nullptr);
1019 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001020 return true;
1021 }
1022
Robert Carr6a160312021-05-17 12:08:20 -07001023 mDrawingState.bgColorLayer->setColor(color);
1024 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1025 mDrawingState.bgColorLayer->setAlpha(alpha);
1026 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001027
chaviw13fdc492017-06-27 12:40:18 -07001028 return true;
1029}
1030
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001031bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001032 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001033
Robert Carr6a160312021-05-17 12:08:20 -07001034 mDrawingState.sequence++;
1035 mDrawingState.cornerRadius = cornerRadius;
1036 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001037 setTransactionFlags(eTransactionNeeded);
1038 return true;
1039}
1040
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001041bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001042 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001043 // If we start or stop drawing blur then the layer's visibility state may change so increment
1044 // the magic sequence number.
1045 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1046 mDrawingState.sequence++;
1047 }
Robert Carr6a160312021-05-17 12:08:20 -07001048 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1049 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001050 setTransactionFlags(eTransactionNeeded);
1051 return true;
1052}
Marissa Wall61c58622018-07-18 10:12:20 -07001053
Mathias Agopian13127d82013-03-05 17:47:11 -08001054bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001055 mDrawingState.sequence++;
1056 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001057 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001058 setTransactionFlags(eTransactionNeeded);
1059 return true;
1060}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001061
Lucas Dupinc3800b82020-10-02 16:24:48 -07001062bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001063 // If we start or stop drawing blur then the layer's visibility state may change so increment
1064 // the magic sequence number.
1065 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1066 mDrawingState.sequence++;
1067 }
Robert Carr6a160312021-05-17 12:08:20 -07001068 mDrawingState.blurRegions = blurRegions;
1069 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001070 setTransactionFlags(eTransactionNeeded);
1071 return true;
1072}
1073
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001074bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001075 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1076 if (mDrawingState.flags == newFlags) return false;
1077 mDrawingState.sequence++;
1078 mDrawingState.flags = newFlags;
1079 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001080 setTransactionFlags(eTransactionNeeded);
1081 return true;
1082}
Robert Carr99e27f02016-06-16 15:18:02 -07001083
chaviw25714502021-02-11 10:01:08 -08001084bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001085 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001086 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001087 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001088
Robert Carr6a160312021-05-17 12:08:20 -07001089 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001090 setTransactionFlags(eTransactionNeeded);
1091 return true;
1092}
Robert Carr8d5227b2017-03-16 15:41:03 -07001093
Evan Roskyef876c92019-01-25 17:46:06 -08001094bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001095 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1096 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001097 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001098 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001099}
1100
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001101bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001102 if (mDrawingState.layerStack == layerStack) return false;
1103 mDrawingState.sequence++;
1104 mDrawingState.layerStack = layerStack;
1105 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001106 setTransactionFlags(eTransactionNeeded);
1107 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001108}
1109
Peiyong Linc502cb72019-03-01 15:00:23 -08001110bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001111 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001112 return false;
1113 }
Robert Carr6a160312021-05-17 12:08:20 -07001114 mDrawingState.sequence++;
1115 mDrawingState.colorSpaceAgnostic = agnostic;
1116 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001117 setTransactionFlags(eTransactionNeeded);
1118 return true;
1119}
1120
Sally Qi81d95e62022-03-21 19:41:33 -07001121bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1122 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1123
1124 mDrawingState.sequence++;
1125 mDrawingState.dimmingEnabled = dimmingEnabled;
1126 mDrawingState.modified = true;
1127 setTransactionFlags(eTransactionNeeded);
1128 return true;
1129}
1130
Ana Krulecc84d09b2019-11-02 23:10:29 +01001131bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001132 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1133 mDrawingState.frameRateSelectionPriority = priority;
1134 mDrawingState.sequence++;
1135 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001136 setTransactionFlags(eTransactionNeeded);
1137 return true;
1138}
1139
1140int32_t Layer::getFrameRateSelectionPriority() const {
1141 // Check if layer has priority set.
1142 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1143 return mDrawingState.frameRateSelectionPriority;
1144 }
1145 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001146 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001147 if (parent != nullptr) {
1148 return parent->getFrameRateSelectionPriority();
1149 }
1150
1151 return Layer::PRIORITY_UNSET;
1152}
1153
Andy Labrada096227e2022-06-15 16:58:11 +00001154bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1155 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1156 mDrawingState.defaultFrameRateCompatibility = compatibility;
1157 mDrawingState.modified = true;
1158 mFlinger->mScheduler->setDefaultFrameRateCompatibility(this);
1159 setTransactionFlags(eTransactionNeeded);
1160 return true;
1161}
1162
1163scheduler::LayerInfo::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
1164 return mDrawingState.defaultFrameRateCompatibility;
1165}
1166
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001167bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1168 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1169};
1170
Vishnu Nair73908d12022-10-24 21:46:42 -07001171ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1172 bool useDrawing = state == LayerVector::StateSet::Drawing;
1173 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1174 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001175 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001176 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001177 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001178}
1179
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001180bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001181 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001182 return false;
1183 }
1184
Robert Carr6a160312021-05-17 12:08:20 -07001185 mDrawingState.sequence++;
1186 mDrawingState.shadowRadius = shadowRadius;
1187 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001188 setTransactionFlags(eTransactionNeeded);
1189 return true;
1190}
1191
Vishnu Nair6213bd92020-05-08 17:42:25 -07001192bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001193 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001194 return false;
1195 }
1196
Robert Carr6a160312021-05-17 12:08:20 -07001197 mDrawingState.sequence++;
1198 mDrawingState.fixedTransformHint = fixedTransformHint;
1199 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001200 setTransactionFlags(eTransactionNeeded);
1201 return true;
1202}
1203
John Reckcdb4ed72021-02-04 13:39:33 -05001204bool Layer::setStretchEffect(const StretchEffect& effect) {
1205 StretchEffect temp = effect;
1206 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001207 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001208 return false;
1209 }
Robert Carr6a160312021-05-17 12:08:20 -07001210 mDrawingState.sequence++;
1211 mDrawingState.stretchEffect = temp;
1212 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001213 setTransactionFlags(eTransactionNeeded);
1214 return true;
1215}
1216
John Reckc00c6692021-02-16 11:37:33 -05001217StretchEffect Layer::getStretchEffect() const {
1218 if (mDrawingState.stretchEffect.hasEffect()) {
1219 return mDrawingState.stretchEffect;
1220 }
1221
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001222 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001223 if (parent != nullptr) {
1224 auto effect = parent->getStretchEffect();
1225 if (effect.hasEffect()) {
1226 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1227 return effect;
1228 }
1229 }
1230 return StretchEffect{};
1231}
1232
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001233bool Layer::enableBorder(bool shouldEnable, float width, const half4& color) {
1234 if (mBorderEnabled == shouldEnable && mBorderWidth == width && mBorderColor == color) {
Tianhao Yao67dd7122022-02-22 17:48:33 +00001235 return false;
1236 }
1237 mBorderEnabled = shouldEnable;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001238 mBorderWidth = width;
1239 mBorderColor = color;
Tianhao Yao67dd7122022-02-22 17:48:33 +00001240 return true;
1241}
1242
1243bool Layer::isBorderEnabled() {
1244 return mBorderEnabled;
1245}
1246
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001247float Layer::getBorderWidth() {
1248 return mBorderWidth;
1249}
1250
1251const half4& Layer::getBorderColor() {
1252 return mBorderColor;
1253}
1254
Ady Abrahama850c182021-08-04 13:04:37 -07001255bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool* transactionNeeded) {
1256 // The frame rate for layer tree is this layer's frame rate if present, or the parent frame rate
1257 const auto frameRate = [&] {
Rachel Leece6e0042023-06-27 11:22:54 -07001258 if (mDrawingState.frameRate.isValid()) {
Ady Abrahama850c182021-08-04 13:04:37 -07001259 return mDrawingState.frameRate;
1260 }
1261
1262 return parentFrameRate;
1263 }();
1264
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001265 *transactionNeeded |= setFrameRateForLayerTreeLegacy(frameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001266
1267 // The frame rate is propagated to the children
1268 bool childrenHaveFrameRate = false;
1269 for (const sp<Layer>& child : mCurrentChildren) {
1270 childrenHaveFrameRate |=
1271 child->propagateFrameRateForLayerTree(frameRate, transactionNeeded);
1272 }
1273
Rachel Leece6e0042023-06-27 11:22:54 -07001274 // If we don't have a valid frame rate specification, but the children do, we set this
Ady Abrahama850c182021-08-04 13:04:37 -07001275 // layer as NoVote to allow the children to control the refresh rate
Rachel Leece6e0042023-06-27 11:22:54 -07001276 if (!frameRate.isValid() && childrenHaveFrameRate) {
Ady Abrahama850c182021-08-04 13:04:37 -07001277 *transactionNeeded |=
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001278 setFrameRateForLayerTreeLegacy(FrameRate(Fps(), FrameRateCompatibility::NoVote));
Ady Abrahama850c182021-08-04 13:04:37 -07001279 }
1280
Rachel Leece6e0042023-06-27 11:22:54 -07001281 // We return whether this layer or its children has a vote. We ignore ExactOrMultiple votes for
Ady Abrahama850c182021-08-04 13:04:37 -07001282 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001283 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001284 const auto layerVotedWithDefaultCompatibility =
Rachel Leece6e0042023-06-27 11:22:54 -07001285 frameRate.vote.rate.isValid() && frameRate.vote.type == FrameRateCompatibility::Default;
1286 const auto layerVotedWithNoVote = frameRate.vote.type == FrameRateCompatibility::NoVote;
1287 const auto layerVotedWithCategory = frameRate.category != FrameRateCategory::Default;
Ady Abrahama850c182021-08-04 13:04:37 -07001288 const auto layerVotedWithExactCompatibility =
Rachel Leece6e0042023-06-27 11:22:54 -07001289 frameRate.vote.rate.isValid() && frameRate.vote.type == FrameRateCompatibility::Exact;
1290 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote || layerVotedWithCategory ||
Ady Abrahama850c182021-08-04 13:04:37 -07001291 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1292}
1293
Ady Abraham60e42ea2020-03-09 19:17:31 -07001294void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001295 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001296 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001297 while (auto parent = layer->getParent()) {
1298 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001299 }
Ady Abrahama850c182021-08-04 13:04:37 -07001300 return layer;
1301 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001302
Ady Abraham60e42ea2020-03-09 19:17:31 -07001303 bool transactionNeeded = false;
Ady Abrahama850c182021-08-04 13:04:37 -07001304 root->propagateFrameRateForLayerTree({}, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001305
Ady Abrahama850c182021-08-04 13:04:37 -07001306 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001307 if (transactionNeeded) {
1308 mFlinger->setTransactionFlags(eTraversalNeeded);
1309 }
1310}
1311
Rachel Leece6e0042023-06-27 11:22:54 -07001312bool Layer::setFrameRate(FrameRate::FrameRateVote frameRateVote) {
1313 if (mDrawingState.frameRate.vote == frameRateVote) {
Steven Thomas3172e202020-01-06 19:25:30 -08001314 return false;
1315 }
1316
Robert Carr6a160312021-05-17 12:08:20 -07001317 mDrawingState.sequence++;
Rachel Leece6e0042023-06-27 11:22:54 -07001318 mDrawingState.frameRate.vote = frameRateVote;
1319 mDrawingState.modified = true;
1320
1321 updateTreeHasFrameRateVote();
1322
1323 setTransactionFlags(eTransactionNeeded);
1324 return true;
1325}
1326
1327bool Layer::setFrameRateCategory(FrameRateCategory category) {
1328 if (mDrawingState.frameRate.category == category) {
1329 return false;
1330 }
1331
1332 mDrawingState.sequence++;
1333 mDrawingState.frameRate.category = category;
Robert Carr6a160312021-05-17 12:08:20 -07001334 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001335
1336 updateTreeHasFrameRateVote();
1337
Steven Thomas3172e202020-01-06 19:25:30 -08001338 setTransactionFlags(eTransactionNeeded);
1339 return true;
1340}
1341
Rachel Lee58cc90d2023-09-05 18:50:20 -07001342bool Layer::setFrameRateSelectionStrategy(FrameRateSelectionStrategy strategy) {
1343 if (mDrawingState.frameRateSelectionStrategy == strategy) return false;
1344 mDrawingState.frameRateSelectionStrategy = strategy;
1345 mDrawingState.sequence++;
1346 mDrawingState.modified = true;
1347 setTransactionFlags(eTransactionNeeded);
1348 return true;
1349}
1350
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001351void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1352 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001353 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001354
1355 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1356 // there are two transactions with the same token, the first one without a buffer and the
1357 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1358 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001359 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1360 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001361 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001362 mDrawingState.bufferSurfaceFrameTX = it->second;
1363 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1364 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1365 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001366 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001367 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001368 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1369 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001370
1371 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001372}
1373
1374void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1375 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001376 mDrawingState.frameTimelineInfo = info;
1377 mDrawingState.postTime = postTime;
1378 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001379 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001380
Robert Carr6a160312021-05-17 12:08:20 -07001381 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001382 bufferSurfaceFrameTX != nullptr) {
1383 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1384 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1385 // being used for BufferSurfaceFrame, don't create a new one.
1386 return;
1387 }
1388 }
1389 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1390 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1391 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001392 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1393 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001394 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001395 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001396 } else {
1397 if (it->second->getPresentState() == PresentState::Presented) {
1398 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1399 // have been from previous vsync.
1400 it->second = createSurfaceFrameForTransaction(info, postTime);
1401 }
1402 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001403
1404 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001405}
1406
1407void Layer::addSurfaceFrameDroppedForBuffer(
Ady Abraham5a3e3562023-06-07 10:32:08 -07001408 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t dropTime) {
1409 surfaceFrame->setDropTime(dropTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001410 surfaceFrame->setPresentState(PresentState::Dropped);
1411 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1412}
1413
1414void Layer::addSurfaceFramePresentedForBuffer(
1415 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1416 nsecs_t currentLatchTime) {
1417 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1418 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1419 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +00001420 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001421}
1422
1423std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1424 const FrameTimelineInfo& info, nsecs_t postTime) {
1425 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001426 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1427 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001428 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001429 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001430 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001431 // For Transactions, the post time is considered to be both queue and acquire fence time.
1432 surfaceFrame->setActualQueueTime(postTime);
1433 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001434 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1435 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001436 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001437 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001438 onSurfaceFrameCreated(surfaceFrame);
1439 return surfaceFrame;
1440}
1441
1442std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1443 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1444 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001445 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001446 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001447 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001448 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001449 // For buffers, acquire fence time will set during latch.
1450 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001451 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1452 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001453 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001454 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001455 onSurfaceFrameCreated(surfaceFrame);
1456 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001457}
1458
Ady Abraham5a3e3562023-06-07 10:32:08 -07001459void Layer::setFrameTimelineVsyncForSkippedFrames(const FrameTimelineInfo& info, nsecs_t postTime,
1460 std::string debugName) {
1461 if (info.skippedFrameVsyncId == FrameTimelineInfo::INVALID_VSYNC_ID) {
1462 return;
1463 }
1464
1465 FrameTimelineInfo skippedFrameTimelineInfo = info;
1466 skippedFrameTimelineInfo.vsyncId = info.skippedFrameVsyncId;
1467
1468 auto surfaceFrame =
1469 mFlinger->mFrameTimeline->createSurfaceFrameForToken(skippedFrameTimelineInfo,
1470 mOwnerPid, mOwnerUid,
1471 getSequence(), mName, debugName,
1472 /*isBuffer*/ false, getGameMode());
1473 surfaceFrame->setActualStartTime(skippedFrameTimelineInfo.skippedFrameStartTimeNanos);
1474 // For Transactions, the post time is considered to be both queue and acquire fence time.
1475 surfaceFrame->setActualQueueTime(postTime);
1476 surfaceFrame->setAcquireFenceTime(postTime);
1477 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1478 if (fps) {
1479 surfaceFrame->setRenderRate(*fps);
1480 }
1481 onSurfaceFrameCreated(surfaceFrame);
1482 addSurfaceFrameDroppedForBuffer(surfaceFrame, postTime);
1483}
1484
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001485bool Layer::setFrameRateForLayerTreeLegacy(FrameRate frameRate) {
Ady Abrahama850c182021-08-04 13:04:37 -07001486 if (mDrawingState.frameRateForLayerTree == frameRate) {
1487 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001488 }
1489
Ady Abrahama850c182021-08-04 13:04:37 -07001490 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001491
Ady Abrahama850c182021-08-04 13:04:37 -07001492 // TODO(b/195668952): we probably don't need to dirty visible regions here
1493 // or even store frameRateForLayerTree in mDrawingState
1494 mDrawingState.sequence++;
1495 mDrawingState.modified = true;
1496 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001497
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001498 mFlinger->mScheduler
1499 ->recordLayerHistory(sequence, getLayerProps(), systemTime(),
1500 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
1501 return true;
1502}
Ady Abrahama850c182021-08-04 13:04:37 -07001503
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001504bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps) {
1505 if (mDrawingState.frameRateForLayerTree == frameRate) {
1506 return false;
1507 }
1508
1509 mDrawingState.frameRateForLayerTree = frameRate;
1510 mFlinger->mScheduler
1511 ->recordLayerHistory(sequence, layerProps, systemTime(),
1512 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001513 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001514}
1515
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001516Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1517 return getDrawingState().frameRateForLayerTree;
1518}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001519
Robert Carr1f0a16a2016-10-24 16:27:39 -07001520bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001521 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001522 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001523 if (parent != nullptr && parent->isHiddenByPolicy()) {
1524 return true;
1525 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001526 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1527 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1528 if (zOrderRelativeOf != nullptr) {
1529 if (zOrderRelativeOf->isHiddenByPolicy()) {
1530 return true;
1531 }
1532 }
1533 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001534 if (CC_UNLIKELY(!isTransformValid())) {
1535 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1536 return true;
1537 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001538 return s.flags & layer_state_t::eLayerHidden;
1539}
1540
David Sodman41fdfc92017-11-06 16:09:56 -08001541uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001542 // TODO: should we do something special if mSecure is set?
1543 if (mProtectedByApp) {
1544 // need a hardware-protected path to external video sink
1545 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001546 }
Riley Andrews03414a12014-07-01 14:22:59 -07001547 if (mPotentialCursor) {
1548 usage |= GraphicBuffer::USAGE_CURSOR;
1549 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001550 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001551 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001552}
1553
Vishnu Nair71fcf912022-10-18 09:14:20 -07001554void Layer::skipReportingTransformHint() {
1555 mSkipReportingTransformHint = true;
1556}
1557
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001558void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1559 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1560 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001561 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001562
Vishnu Nairb76d99a2023-03-19 18:22:31 -07001563 setTransformHintLegacy(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001564}
1565
Mathias Agopian13127d82013-03-05 17:47:11 -08001566// ----------------------------------------------------------------------------
1567// debugging
1568// ----------------------------------------------------------------------------
1569
Marissa Wall61c58622018-07-18 10:12:20 -07001570// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001571gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001572 using namespace std::string_literals;
1573
Huihong Luo05539a12022-02-23 10:29:40 -08001574 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001575 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001576 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001577 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001578 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001579 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001580
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001581 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001582 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001583 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001584 info.mX = ds.transform.tx();
1585 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001586 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001587 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001588 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001589 info.mFlags = ds.flags;
1590 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001591 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001592 info.mMatrix[0][0] = ds.transform[0][0];
1593 info.mMatrix[0][1] = ds.transform[0][1];
1594 info.mMatrix[1][0] = ds.transform[1][0];
1595 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001596 {
chaviwd62d3062019-09-04 14:48:02 -07001597 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001598 if (buffer != 0) {
1599 info.mActiveBufferWidth = buffer->getWidth();
1600 info.mActiveBufferHeight = buffer->getHeight();
1601 info.mActiveBufferStride = buffer->getStride();
1602 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001603 } else {
1604 info.mActiveBufferWidth = 0;
1605 info.mActiveBufferHeight = 0;
1606 info.mActiveBufferStride = 0;
1607 info.mActiveBufferFormat = 0;
1608 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001609 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001610 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001611 info.mIsOpaque = isOpaque(ds);
1612 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001613 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001614 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001615}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001616
Yiwei Zhang5434a782018-12-05 18:06:32 -08001617void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001618 result.append(kDumpTableRowLength, '-');
1619 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001620 result.append(" Layer name\n");
1621 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001622 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001623 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001624 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001625 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001626 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001627 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1628 result.append(kDumpTableRowLength, '-');
1629 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001630}
1631
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001632void Layer::miniDumpLegacy(std::string& result, const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001633 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001634 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001635 return;
1636 }
1637
Yiwei Zhang5434a782018-12-05 18:06:32 -08001638 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001639 if (mName.length() > 77) {
1640 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001641 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001642 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001643 shortened.append(mName, mName.length() - 36);
1644 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001645 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001646 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001647 }
1648
Yiwei Zhang5434a782018-12-05 18:06:32 -08001649 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001650
Alec Mourib416efd2018-09-06 21:01:59 +00001651 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001652 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001653
Chia-I Wu1e043612018-03-01 09:45:09 -08001654 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001655 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001656 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001657 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001658 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001659 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001660 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001661 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1662 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001663 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001664 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001665 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001666 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001667 const auto frameRate = getFrameRateForLayerTree();
Rachel Leece6e0042023-06-27 11:22:54 -07001668 if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
1669 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.vote.rate).c_str(),
1670 ftl::enum_string(frameRate.vote.type).c_str(),
1671 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001672 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001673 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001674 }
Dan Stozae22aec72016-08-01 13:20:59 -07001675
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001676 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1677 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1678
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001679 result.append(kDumpTableRowLength, '-');
1680 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001681}
Dan Stozae22aec72016-08-01 13:20:59 -07001682
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001683void Layer::miniDump(std::string& result, const frontend::LayerSnapshot& snapshot,
1684 const DisplayDevice& display) const {
1685 const auto outputLayer = findOutputLayerForDisplay(&display, snapshot.path);
1686 if (!outputLayer) {
1687 return;
1688 }
1689
1690 StringAppendF(&result, " %s\n", snapshot.debugName.c_str());
1691 StringAppendF(&result, " %10zu | ", snapshot.globalZ);
1692 StringAppendF(&result, " %10d | ",
1693 snapshot.layerMetadata.getInt32(gui::METADATA_WINDOW_TYPE, 0));
1694 StringAppendF(&result, "%10s | ", toString(getCompositionType(outputLayer)).c_str());
1695 const auto& outputLayerState = outputLayer->getState();
1696 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1697 const Rect& frame = outputLayerState.displayFrame;
1698 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
1699 const FloatRect& crop = outputLayerState.sourceCrop;
1700 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
1701 crop.bottom);
1702 const auto frameRate = snapshot.frameRate;
Rachel Leece6e0042023-06-27 11:22:54 -07001703 if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
1704 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.vote.rate).c_str(),
1705 ftl::enum_string(frameRate.vote.type).c_str(),
1706 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001707 } else {
1708 result.append(41, ' ');
1709 }
1710
1711 const auto focused = isLayerFocusedBasedOnPriority(snapshot.frameRateSelectionPriority);
1712 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1713
1714 result.append(kDumpTableRowLength, '-');
1715 result.append("\n");
1716}
1717
Yiwei Zhang5434a782018-12-05 18:06:32 -08001718void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001719 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001720}
1721
Svetoslavd85084b2014-03-20 10:28:31 -07001722void Layer::clearFrameStats() {
1723 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001724}
1725
Jamie Gennis6547ff42013-07-16 20:12:42 -07001726void Layer::logFrameStats() {
1727 mFrameTracker.logAndResetStats(mName);
1728}
1729
Svetoslavd85084b2014-03-20 10:28:31 -07001730void Layer::getFrameStats(FrameStats* outStats) const {
1731 mFrameTracker.getStats(outStats);
1732}
1733
Vishnu Nair76554eb2022-12-09 03:38:36 +00001734void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1735 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
Vishnu Nair3be61902023-04-26 19:47:29 -07001736 StringAppendF(&result, "Layer %s%s pid:%d uid:%d%s\n", getName().c_str(), hasBuffer.c_str(),
1737 mOwnerPid, mOwnerUid, isHandleAlive() ? " handleAlive" : "");
Vishnu Nair0f085c62019-08-30 08:49:12 -07001738}
1739
Brian Anderson5ea5e592016-12-01 16:54:33 -08001740void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001741 const int32_t layerId = getSequence();
1742 mFlinger->mTimeStats->onDestroy(layerId);
1743 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001744}
1745
Vishnu Nair787aa782023-03-17 13:46:46 -07001746size_t Layer::getDescendantCount() const {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001747 size_t count = 0;
Vishnu Nair787aa782023-03-17 13:46:46 -07001748 for (const sp<Layer>& child : mDrawingChildren) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001749 count += 1 + child->getChildrenCount();
1750 }
1751 return count;
1752}
1753
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001754void Layer::setGameModeForTree(GameMode gameMode) {
1755 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001756 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1757 gameMode =
1758 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001759 }
1760 setGameMode(gameMode);
1761 for (const sp<Layer>& child : mCurrentChildren) {
1762 child->setGameModeForTree(gameMode);
1763 }
1764}
1765
Robert Carr1f0a16a2016-10-24 16:27:39 -07001766void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001767 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001768 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001769
Robert Carr1f0a16a2016-10-24 16:27:39 -07001770 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001771 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001772 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001773 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001774}
1775
1776ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001777 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001778 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001779
Robert Carr1323c952019-01-28 18:13:27 -08001780 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001781 const auto removeResult = mCurrentChildren.remove(layer);
1782
1783 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001784 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001785 layer->updateTreeHasFrameRateVote();
1786
1787 return removeResult;
1788}
1789
Robert Carr15eae092018-03-23 13:43:53 -07001790void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001791 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001792 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001793 const float parentShadowRadius =
1794 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001795 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001796 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001797 }
1798}
1799
chaviwf1961f72017-09-18 16:41:07 -07001800bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001801 sp<Layer> newParent;
1802 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001803 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001804 if (newParent == nullptr) {
1805 ALOGE("Unable to promote Layer handle");
1806 return false;
1807 }
1808 if (newParent == this) {
1809 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1810 return false;
1811 }
1812 }
1813
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001814 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001815 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001816 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001817 }
1818
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001819 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001820 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001821 if (!newParent->isRemovedFromCurrentState()) {
1822 addToCurrentState();
1823 } else {
1824 onRemovedFromCurrentState();
1825 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001826 } else {
1827 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001828 }
1829
chaviw06178942017-07-27 10:25:59 -07001830 return true;
1831}
1832
Peiyong Lind3788632018-09-18 16:01:31 -07001833bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001834 static const mat4 identityMatrix = mat4();
1835
Robert Carr6a160312021-05-17 12:08:20 -07001836 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001837 return false;
1838 }
Robert Carr6a160312021-05-17 12:08:20 -07001839 ++mDrawingState.sequence;
1840 mDrawingState.colorTransform = matrix;
1841 mDrawingState.hasColorTransform = matrix != identityMatrix;
1842 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001843 setTransactionFlags(eTransactionNeeded);
1844 return true;
1845}
1846
chaviwf66724d2018-11-28 16:35:21 -08001847mat4 Layer::getColorTransform() const {
1848 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001849 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001850 colorTransform = parent->getColorTransform() * colorTransform;
1851 }
1852 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001853}
1854
1855bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001856 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001857 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001858 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1859 }
1860 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001861}
1862
Chia-I Wu11481472018-05-04 10:43:19 -07001863bool Layer::isLegacyDataSpace() const {
1864 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001865 return !(getDataSpace() &
1866 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1867 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001868}
1869
Robert Carr1f0a16a2016-10-24 16:27:39 -07001870void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001871 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001872}
1873
Robert Carr6a160312021-05-17 12:08:20 -07001874int32_t Layer::getZ(LayerVector::StateSet) const {
1875 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001876}
1877
Robert Carr1c5481e2019-07-01 14:42:27 -07001878bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001879 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001880 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001881 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001882}
1883
David Sodman41fdfc92017-11-06 16:09:56 -08001884__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001885 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001886 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1887 "makeTraversalList received invalid stateSet");
1888 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1889 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001890 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001891
Robert Carr29abff82017-12-04 13:51:20 -08001892 if (state.zOrderRelatives.size() == 0) {
1893 *outSkipRelativeZUsers = true;
1894 return children;
1895 }
1896
chaviwfd462612018-05-31 16:11:27 -07001897 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001898 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001899 sp<Layer> strongRelative = weakRelative.promote();
1900 if (strongRelative != nullptr) {
1901 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001902 }
1903 }
1904
Dan Stoza412903f2017-04-27 13:42:17 -07001905 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001906 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001907 continue;
1908 }
Robert Carrdb66e622017-04-10 16:55:57 -07001909 traverse.add(child);
1910 }
1911
1912 return traverse;
1913}
1914
Robert Carr1f0a16a2016-10-24 16:27:39 -07001915/**
Robert Carrdb66e622017-04-10 16:55:57 -07001916 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001917 */
Dan Stoza412903f2017-04-27 13:42:17 -07001918void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001919 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1920 // produce a new list for traversing, including our relatives, and not including our children
1921 // who are relatives of another surface. In the case that there are no relative Z,
1922 // makeTraversalList returns our children directly to avoid significant overhead.
1923 // However in this case we need to take the responsibility for filtering children which
1924 // are relatives of another surface here.
1925 bool skipRelativeZUsers = false;
1926 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001927
Robert Carr1f0a16a2016-10-24 16:27:39 -07001928 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001929 for (; i < list.size(); i++) {
1930 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001931 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1932 continue;
1933 }
1934
chaviw301b1d82019-11-06 13:15:09 -08001935 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001936 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001937 }
Dan Stoza412903f2017-04-27 13:42:17 -07001938 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001939 }
Robert Carr29abff82017-12-04 13:51:20 -08001940
Dan Stoza412903f2017-04-27 13:42:17 -07001941 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001942 for (; i < list.size(); i++) {
1943 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001944
Robert Carr29abff82017-12-04 13:51:20 -08001945 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1946 continue;
1947 }
Dan Stoza412903f2017-04-27 13:42:17 -07001948 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001949 }
1950}
1951
1952/**
Robert Carrdb66e622017-04-10 16:55:57 -07001953 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001954 */
Dan Stoza412903f2017-04-27 13:42:17 -07001955void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1956 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001957 // See traverseInZOrder for documentation.
1958 bool skipRelativeZUsers = false;
1959 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001960
Robert Carr1f0a16a2016-10-24 16:27:39 -07001961 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001962 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001963 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001964
1965 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1966 continue;
1967 }
1968
chaviw301b1d82019-11-06 13:15:09 -08001969 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001970 break;
1971 }
Dan Stoza412903f2017-04-27 13:42:17 -07001972 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001973 }
Dan Stoza412903f2017-04-27 13:42:17 -07001974 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001975 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001976 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001977
1978 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1979 continue;
1980 }
1981
Dan Stoza412903f2017-04-27 13:42:17 -07001982 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001983 }
1984}
1985
Edgar Arriaga844fa672020-01-16 14:21:42 -08001986void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1987 visitor(this);
1988 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001989 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001990 for (const sp<Layer>& child : children) {
1991 child->traverse(state, visitor);
1992 }
1993}
1994
Vishnu Nair787aa782023-03-17 13:46:46 -07001995void Layer::traverseChildren(const LayerVector::Visitor& visitor) {
1996 for (const sp<Layer>& child : mDrawingChildren) {
1997 visitor(child.get());
1998 }
1999}
2000
chaviw4b129c22018-04-09 16:19:43 -07002001LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
2002 const std::vector<Layer*>& layersInTree) {
2003 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2004 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07002005 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2006 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002007 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07002008
chaviwfd462612018-05-31 16:11:27 -07002009 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07002010 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2011 sp<Layer> strongRelative = weakRelative.promote();
2012 // Only add relative layers that are also descendents of the top most parent of the tree.
2013 // If a relative layer is not a descendent, then it should be ignored.
2014 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
2015 traverse.add(strongRelative);
2016 }
2017 }
2018
2019 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07002020 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07002021 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
2022 // descendent of the top most parent of the tree. If it's not a descendent, then just add
2023 // the child here since it won't be added later as a relative.
2024 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
2025 childState.zOrderRelativeOf.promote().get())) {
2026 continue;
2027 }
2028 traverse.add(child);
2029 }
2030
2031 return traverse;
2032}
2033
2034void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
2035 LayerVector::StateSet stateSet,
2036 const LayerVector::Visitor& visitor) {
2037 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07002038
2039 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07002040 for (; i < list.size(); i++) {
2041 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08002042 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07002043 break;
2044 }
chaviw4b129c22018-04-09 16:19:43 -07002045 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002046 }
chaviw4b129c22018-04-09 16:19:43 -07002047
chaviwa76b2712017-09-20 12:02:26 -07002048 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07002049 for (; i < list.size(); i++) {
2050 const auto& relative = list[i];
2051 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002052 }
2053}
2054
chaviw4b129c22018-04-09 16:19:43 -07002055std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
2056 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2057 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2058
2059 std::vector<Layer*> layersInTree = {this};
2060 for (size_t i = 0; i < children.size(); i++) {
2061 const auto& child = children[i];
2062 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
2063 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
2064 }
2065
2066 return layersInTree;
2067}
2068
2069void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
2070 const LayerVector::Visitor& visitor) {
2071 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
2072 std::sort(layersInTree.begin(), layersInTree.end());
2073 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
2074}
2075
Peiyong Linefefaac2018-08-17 12:27:51 -07002076ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08002077 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002078}
2079
Garfield Tan2c1782c2022-02-16 15:25:05 -08002080bool Layer::isTransformValid() const {
2081 float transformDet = getTransform().det();
2082 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
2083}
2084
chaviw13fdc492017-06-27 12:40:18 -07002085half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002086 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002087
chaviw13fdc492017-06-27 12:40:18 -07002088 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2089 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002090}
Robert Carr6452f122017-03-21 10:41:29 -07002091
Vishnu Nair6213bd92020-05-08 17:42:25 -07002092ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07002093 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07002094 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2095 return fixedTransformHint;
2096 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002097 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07002098 if (!p) return fixedTransformHint;
2099 return p->getFixedTransformHint();
2100}
2101
chaviw13fdc492017-06-27 12:40:18 -07002102half4 Layer::getColor() const {
2103 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002104 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002105}
Robert Carr6452f122017-03-21 10:41:29 -07002106
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002107int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002108 if (getDrawingState().backgroundBlurRadius == 0) {
2109 return 0;
2110 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002111
Vishnu Nair29810f72022-07-01 16:38:41 +00002112 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002113 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2114 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002115}
2116
Galia Peychevae0acf382021-04-12 21:22:34 +02002117const std::vector<BlurRegion> Layer::getBlurRegions() const {
2118 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002119 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002120 for (auto& region : regionsCopy) {
2121 region.alpha = region.alpha * layerAlpha;
2122 }
2123 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002124}
2125
Vishnu Naire14c6b32022-08-06 04:20:15 +00002126RoundedCornerState Layer::getRoundedCornerState() const {
Leon Scroggins IIIc1dbfcb2022-03-21 16:48:10 -04002127 // Today's DPUs cannot do rounded corners. If RenderEngine cannot render
2128 // protected content, remove rounded corners from protected content so it
2129 // can be rendered by the DPU.
2130 if (isProtected() && !mFlinger->getRenderEngine().supportsProtectedContent()) {
2131 return {};
2132 }
2133
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002134 // Get parent settings
2135 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002136 const auto& parent = mDrawingParent.promote();
2137 if (parent != nullptr) {
2138 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002139 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002140 ui::Transform t = getActiveTransform(getDrawingState());
2141 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002142 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002143 parentSettings.radius.x *= t.getScaleX();
2144 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002145 }
2146 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002147
2148 // Get layer settings
2149 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002150 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002151 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002152 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002153
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002154 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002155 // If the parent and the layer have rounded corner settings, use the parent settings if the
2156 // parent crop is entirely inside the layer crop.
2157 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2158 if (parentSettings.cropRect.left > layerCropRect.left &&
2159 parentSettings.cropRect.top > layerCropRect.top &&
2160 parentSettings.cropRect.right < layerCropRect.right &&
2161 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2162 return parentSettings;
2163 } else {
2164 return layerSettings;
2165 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002166 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002167 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002168 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002169 return parentSettings;
2170 }
2171 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002172}
2173
Robert Carr88b85e12022-03-21 15:47:35 -07002174bool Layer::findInHierarchy(const sp<Layer>& l) {
2175 if (l == this) {
2176 return true;
2177 }
2178 for (auto& child : mDrawingChildren) {
2179 if (child->findInHierarchy(l)) {
2180 return true;
2181 }
2182 }
2183 return false;
2184}
2185
Robert Carr1f0a16a2016-10-24 16:27:39 -07002186void Layer::commitChildList() {
2187 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2188 const auto& child = mCurrentChildren[i];
2189 child->commitChildList();
2190 }
2191 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002192 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002193 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2194 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2195 if (zOrderRelativeOf == nullptr) return;
2196 if (findInHierarchy(zOrderRelativeOf)) {
2197 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2198 zOrderRelativeOf->mName.c_str());
2199 ALOGE("Severing rel Z loop, potentially dangerous");
2200 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002201 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002202 }
2203 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002204}
2205
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002206
chaviw3277faf2021-05-19 16:45:23 -05002207void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002208 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002209 mDrawingState.touchableRegionCrop =
2210 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002211 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002212 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002213 setTransactionFlags(eTransactionNeeded);
2214}
2215
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002216perfetto::protos::LayerProto* Layer::writeToProto(perfetto::protos::LayersProto& layersProto,
2217 uint32_t traceFlags) {
2218 perfetto::protos::LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002219 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002220 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2221
Vishnu Nair00b90132021-11-05 14:03:40 -07002222 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Vishnu Nair2f65e972023-04-04 16:36:28 +00002223 ui::LayerStack layerStack =
2224 (mSnapshot) ? mSnapshot->outputFilter.layerStack : ui::INVALID_LAYER_STACK;
2225 writeCompositionStateToProto(layerProto, layerStack);
Alec Mouri6b9e9912020-01-21 10:50:24 -08002226 }
2227
chaviw08f3cb22020-01-13 13:17:21 -08002228 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002229 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002230 }
chaviw6d89e2d2020-01-14 14:42:01 -08002231
2232 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002233}
2234
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002235void Layer::writeCompositionStateToProto(perfetto::protos::LayerProto* layerProto,
2236 ui::LayerStack layerStack) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002237 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002238 ftl::FakeGuard mainThreadGuard(kMainThreadContext);
Vishnu Nairea6ff812023-02-27 17:41:39 +00002239
2240 // Only populate for the primary display.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002241 if (const auto display = mFlinger->getDisplayFromLayerStack(layerStack)) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002242 const auto compositionType = getCompositionType(*display);
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002243 layerProto->set_hwc_composition_type(
2244 static_cast<perfetto::protos::HwcCompositionType>(compositionType));
Vishnu Nair2f65e972023-04-04 16:36:28 +00002245 LayerProtoHelper::writeToProto(getVisibleRegion(display),
Vishnu Nairea6ff812023-02-27 17:41:39 +00002246 [&]() { return layerProto->mutable_visible_region(); });
2247 }
2248}
2249
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002250void Layer::writeToProtoDrawingState(perfetto::protos::LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002251 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002252 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002253 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002254 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002255 [&]() { return layerInfo->mutable_active_buffer(); });
2256 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2257 layerInfo->mutable_buffer_transform());
2258 }
2259 layerInfo->set_invalidate(contentDirty);
2260 layerInfo->set_is_protected(isProtected());
2261 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2262 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002263 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002264 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002265 layerInfo->set_corner_radius(
2266 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002267 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2268 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2269 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2270 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2271 [&]() { return layerInfo->mutable_position(); });
2272 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002273 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2274 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002275
Vishnu Nair00b90132021-11-05 14:03:40 -07002276 if (hasColorTransform()) {
2277 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002278 }
2279
Vishnu Nair60db8c02020-04-02 11:55:16 -07002280 LayerProtoHelper::writeToProto(mSourceBounds,
2281 [&]() { return layerInfo->mutable_source_bounds(); });
2282 LayerProtoHelper::writeToProto(mScreenBounds,
2283 [&]() { return layerInfo->mutable_screen_bounds(); });
2284 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2285 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2286 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002287}
2288
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002289void Layer::writeToProtoCommonState(perfetto::protos::LayerProto* layerInfo,
2290 LayerVector::StateSet stateSet, uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002291 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2292 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002293 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002294
chaviw766c9c52021-02-10 17:36:47 -08002295 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002296
Vishnu Nair00b90132021-11-05 14:03:40 -07002297 layerInfo->set_id(sequence);
2298 layerInfo->set_name(getName().c_str());
2299 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002300
Vishnu Nair00b90132021-11-05 14:03:40 -07002301 for (const auto& child : children) {
2302 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002303 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002304
Vishnu Nair00b90132021-11-05 14:03:40 -07002305 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2306 sp<Layer> strongRelative = weakRelative.promote();
2307 if (strongRelative != nullptr) {
2308 layerInfo->add_relatives(strongRelative->sequence);
2309 }
2310 }
2311
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002312 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002313 [&]() { return layerInfo->mutable_transparent_region(); });
2314
2315 layerInfo->set_layer_stack(getLayerStack().id);
2316 layerInfo->set_z(state.z);
2317
2318 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2319 return layerInfo->mutable_requested_position();
2320 });
2321
Vishnu Nair00b90132021-11-05 14:03:40 -07002322 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2323
2324 layerInfo->set_is_opaque(isOpaque(state));
2325
2326 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2327 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2328 LayerProtoHelper::writeToProto(state.color,
2329 [&]() { return layerInfo->mutable_requested_color(); });
2330 layerInfo->set_flags(state.flags);
2331
2332 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2333 layerInfo->mutable_requested_transform());
2334
2335 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2336 if (parent != nullptr) {
2337 layerInfo->set_parent(parent->sequence);
Vishnu Nair00b90132021-11-05 14:03:40 -07002338 }
2339
2340 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2341 if (zOrderRelativeOf != nullptr) {
2342 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
Vishnu Nair00b90132021-11-05 14:03:40 -07002343 }
2344
2345 layerInfo->set_is_relative_of(state.isRelativeOf);
2346
2347 layerInfo->set_owner_uid(mOwnerUid);
2348
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002349 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002350 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002351 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002352 info = fillInputInfo(
2353 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002354 } else {
2355 info = state.inputInfo;
2356 }
2357
2358 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002359 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002360 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002361
Vishnu Nair00b90132021-11-05 14:03:40 -07002362 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002363 auto protoMap = layerInfo->mutable_metadata();
2364 for (const auto& entry : state.metadata.mMap) {
2365 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2366 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002367 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002368
2369 LayerProtoHelper::writeToProto(state.destinationFrame,
2370 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002371}
2372
Robert Carr2e102c92018-10-23 12:11:15 -07002373bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002374 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002375}
2376
Prabir Pradhan33da9462022-06-14 14:55:57 +00002377// Applies the given transform to the region, while protecting against overflows caused by any
2378// offsets. If applying the offset in the transform to any of the Rects in the region would result
2379// in an overflow, they are not added to the output Region.
2380static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2381 const std::string& debugWindowName) {
2382 // Round the translation using the same rounding strategy used by ui::Transform.
2383 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2384 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2385
2386 ui::Transform transformWithoutOffset = t;
2387 transformWithoutOffset.set(0.f, 0.f);
2388
2389 const Region transformed = transformWithoutOffset.transform(r);
2390
2391 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2392 Region ret;
2393 for (const auto& rect : transformed) {
2394 Rect newRect;
2395 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2396 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2397 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2398 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2399 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2400 debugWindowName.c_str());
2401 continue;
2402 }
2403 ret.orSelf(newRect);
2404 }
2405 return ret;
2406}
2407
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002408void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002409 auto [inputBounds, inputBoundsValid] = getInputBounds(/*fillParentBounds=*/false);
2410 if (!inputBoundsValid) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002411 info.touchableRegion.clear();
chaviw7e72caf2020-12-02 16:50:43 -08002412 }
2413
Chavi Weingarten7f019192023-08-08 20:39:01 +00002414 info.frame = getInputBoundsInDisplaySpace(inputBounds, screenToDisplay);
chaviw1ff3d1e2020-07-01 15:53:47 -07002415
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002416 ui::Transform inputToLayer;
Vishnu Nairfed7c122023-03-18 01:54:43 +00002417 inputToLayer.set(inputBounds.left, inputBounds.top);
2418 const ui::Transform layerToScreen = getInputTransform();
2419 const ui::Transform inputToDisplay = screenToDisplay * layerToScreen * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002420
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002421 // InputDispatcher expects a display-to-input transform.
2422 info.transform = inputToDisplay.inverse();
2423
2424 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002425 info.touchableRegion =
2426 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002427}
2428
chaviw3277faf2021-05-19 16:45:23 -05002429void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002430 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002431 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002432 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002433 }
2434 if (p != nullptr) {
2435 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2436 }
2437}
2438
Vishnu Naira066d902021-09-13 18:40:17 -07002439gui::DropInputMode Layer::getDropInputMode() const {
2440 gui::DropInputMode mode = mDrawingState.dropInputMode;
2441 if (mode == gui::DropInputMode::ALL) {
2442 return mode;
2443 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002444 sp<Layer> parent = mDrawingParent.promote();
2445 if (parent) {
2446 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002447 if (parentMode != gui::DropInputMode::NONE) {
2448 return parentMode;
2449 }
2450 }
2451 return mode;
2452}
2453
2454void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002455 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002456 return;
2457 }
2458
2459 // Check if we need to drop input unconditionally
2460 gui::DropInputMode dropInputMode = getDropInputMode();
2461 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002462 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002463 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2464 return;
2465 }
2466
2467 // Check if we need to check if the window is obscured by parent
2468 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2469 return;
2470 }
2471
2472 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002473 sp<Layer> parent = mDrawingParent.promote();
2474 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002475 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002476 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2477 static_cast<float>(getAlpha()));
2478 }
2479
2480 // Check if the parent has cropped the buffer
2481 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2482 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002483 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002484 return;
2485 }
2486
2487 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2488 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2489 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2490 // match then the layer has not been cropped by its parents.
2491 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2492 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2493
2494 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002495 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002496 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2497 getDebugName());
2498 } else {
2499 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2500 // input if the window is obscured. This check should be done in surfaceflinger but the
2501 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2502 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002503 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002504 }
2505}
2506
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002507WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002508 if (!hasInputInfo()) {
2509 mDrawingState.inputInfo.name = getName();
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002510 mDrawingState.inputInfo.ownerUid = gui::Uid{mOwnerUid};
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00002511 mDrawingState.inputInfo.ownerPid = gui::Pid{mOwnerPid};
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002512 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002513 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002514 }
2515
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002516 const ui::Transform& displayTransform =
2517 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2518
chaviw3277faf2021-05-19 16:45:23 -05002519 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002520 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002521 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002522
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002523 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002524
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002525 if (displayArgs.transform == nullptr) {
2526 // Do not let the window receive touches if it is not associated with a valid display
2527 // transform. We still allow the window to receive keys and prevent ANRs.
2528 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2529 }
2530
Patrick Williams1caf3b72023-03-31 10:59:10 -05002531 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !isVisibleForInput());
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002532
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002533 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002534 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002535 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002536
Vishnu Nair16a938f2021-09-24 07:14:54 -07002537 // If the window will be blacked out on a display because the display does not have the secure
2538 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002539 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002540 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002541 }
2542
Vishnu Nairfed7c122023-03-18 01:54:43 +00002543 sp<Layer> cropLayer = mDrawingState.touchableRegionCrop.promote();
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002544 if (info.replaceTouchableRegionWithCrop) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002545 Rect inputBoundsInDisplaySpace;
2546 if (!cropLayer) {
2547 FloatRect inputBounds = getInputBounds(/*fillParentBounds=*/true).first;
2548 inputBoundsInDisplaySpace = getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2549 } else {
2550 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2551 inputBoundsInDisplaySpace =
2552 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2553 }
2554 info.touchableRegion = Region(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002555 } else if (cropLayer != nullptr) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002556 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2557 Rect inputBoundsInDisplaySpace =
2558 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2559 info.touchableRegion = info.touchableRegion.intersect(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002560 }
2561
Winson Chunga30f7c92021-06-29 15:42:56 -07002562 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2563 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002564 if (isTrustedOverlay()) {
2565 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2566 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002567
chaviwaf87b3e2019-10-01 16:59:28 -07002568 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2569 // touches from going outside the cloned area.
2570 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002571 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002572 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2573 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002574 info.touchableRegion = info.touchableRegion.intersect(rect);
2575 }
2576 }
2577
Robert Carr720e5062018-07-30 17:45:14 -07002578 return info;
2579}
2580
Vishnu Nairfed7c122023-03-18 01:54:43 +00002581Rect Layer::getInputBoundsInDisplaySpace(const FloatRect& inputBounds,
2582 const ui::Transform& screenToDisplay) {
2583 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2584 // frame and transform used for the layer, which determines the bounds and the coordinate space
2585 // within which the layer will receive input.
2586
2587 // Coordinate space definitions:
2588 // - display: The display device's coordinate space. Correlates to pixels on the display.
2589 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2590 // - layer: The coordinate space of this layer.
2591 // - input: The coordinate space in which this layer will receive input events. This could be
2592 // different than layer space if a surfaceInset is used, which changes the origin
2593 // of the input space.
2594
2595 // Crop the input bounds to ensure it is within the parent's bounds.
2596 const FloatRect croppedInputBounds = mBounds.intersect(inputBounds);
2597 const ui::Transform layerToScreen = getInputTransform();
2598 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
2599 return Rect{layerToDisplay.transform(croppedInputBounds)};
2600}
2601
chaviwaf87b3e2019-10-01 16:59:28 -07002602sp<Layer> Layer::getClonedRoot() {
2603 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002604 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002605 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002606 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002607 return nullptr;
2608 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002609 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002610}
2611
Robert Carredd13602020-04-13 17:24:34 -07002612bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002613 return mDrawingState.inputInfo.token != nullptr ||
2614 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002615}
2616
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002617compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002618 const DisplayDevice* display) const {
2619 if (!display) return nullptr;
Lloyd Pique30db6402023-06-26 18:56:51 +00002620 if (!mFlinger->mLayerLifecycleManagerEnabled) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00002621 return display->getCompositionDisplay()->getOutputLayerForLayer(
2622 getCompositionEngineLayerFE());
2623 }
2624 sp<LayerFE> layerFE;
2625 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
2626 for (auto& [p, layer] : mLayerFEs) {
2627 if (p == path) {
2628 layerFE = layer;
2629 }
2630 }
2631
2632 if (!layerFE) return nullptr;
2633 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002634}
2635
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002636compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
2637 const DisplayDevice* display, const frontend::LayerHierarchy::TraversalPath& path) const {
2638 if (!display) return nullptr;
Vishnu Naire9ee0002023-07-01 03:14:51 +00002639 if (!mFlinger->mLayerLifecycleManagerEnabled) {
2640 return display->getCompositionDisplay()->getOutputLayerForLayer(
2641 getCompositionEngineLayerFE());
2642 }
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002643 sp<LayerFE> layerFE;
2644 for (auto& [p, layer] : mLayerFEs) {
2645 if (p == path) {
2646 layerFE = layer;
2647 }
2648 }
2649
2650 if (!layerFE) return nullptr;
2651 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
2652}
2653
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002654Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2655 const auto outputLayer = findOutputLayerForDisplay(display);
2656 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002657}
2658
Vishnu Nairde177252023-04-21 12:44:10 -07002659void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom, uint32_t mirrorRootId) {
2660 mSnapshot->path.id = clonedFrom->getSequence();
Vishnu Nair6f878312023-09-08 11:05:01 -07002661 mSnapshot->path.mirrorRootIds.emplace_back(mirrorRootId);
Vishnu Nairde177252023-04-21 12:44:10 -07002662
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002663 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002664 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002665 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2666 mPotentialCursor = clonedFrom->mPotentialCursor;
2667 mProtectedByApp = clonedFrom->mProtectedByApp;
2668 updateCloneBufferInfo();
2669}
2670
2671void Layer::updateCloneBufferInfo() {
2672 if (!isClone() || !isClonedFromAlive()) {
2673 return;
2674 }
2675
2676 sp<Layer> clonedFrom = getClonedFrom();
2677 mBufferInfo = clonedFrom->mBufferInfo;
2678 mSidebandStream = clonedFrom->mSidebandStream;
2679 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2680 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2681 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2682
2683 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2684 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2685 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2686 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2687 // the cloned drawingState again.
2688 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2689 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2690 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2691 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2692
2693 cloneDrawingState(clonedFrom.get());
2694
2695 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2696 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2697 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2698 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002699}
chaviw74b03172019-08-19 11:09:03 -07002700
Vishnu Nair3be61902023-04-26 19:47:29 -07002701bool Layer::updateMirrorInfo(const std::deque<Layer*>& cloneRootsPendingUpdates) {
chaviw74b03172019-08-19 11:09:03 -07002702 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2703 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2704 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2705 // that case, we want to delete the reference to the clone since we want it to get
2706 // destroyed. The root, this layer, will still be around since the client can continue
2707 // to hold a reference, but no cloned layers will be displayed.
2708 mClonedChild = nullptr;
Vishnu Nair3be61902023-04-26 19:47:29 -07002709 return true;
chaviw74b03172019-08-19 11:09:03 -07002710 }
2711
2712 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2713 // If the real layer exists and is in current state, add the clone as a child of the root.
2714 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2715 // copied to drawingState for the root layer. So the clonedChild is always removed from
2716 // drawingState and then needs to be added back each traversal.
2717 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2718 addChildToDrawing(mClonedChild);
2719 }
2720
2721 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002722 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002723 mClonedChild->updateClonedRelatives(clonedLayersMap);
Vishnu Nair3be61902023-04-26 19:47:29 -07002724
2725 for (Layer* root : cloneRootsPendingUpdates) {
2726 if (clonedLayersMap.find(sp<Layer>::fromExisting(root)) != clonedLayersMap.end()) {
2727 return false;
2728 }
2729 }
2730 return true;
chaviw74b03172019-08-19 11:09:03 -07002731}
2732
2733void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2734 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2735 // to the clone. If the real layer is no longer alive, continue traversing the children
2736 // since we may be able to pull out other children that are still alive.
2737 if (isClonedFromAlive()) {
2738 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002739 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002740 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002741 }
2742
2743 // The clone layer may have children in drawingState since they may have been created and
2744 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2745 // that already exist, since we can just re-use them.
2746 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2747 // not updated in the regular traversal. They are skipped since the root will lose the
2748 // reference to them when it copies its currentChildren to drawing.
2749 for (sp<Layer>& child : mDrawingChildren) {
2750 child->updateClonedDrawingState(clonedLayersMap);
2751 }
2752}
2753
2754void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2755 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2756 mDrawingChildren.clear();
2757
2758 if (!isClonedFromAlive()) {
2759 return;
2760 }
2761
2762 sp<Layer> clonedFrom = getClonedFrom();
2763 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2764 if (child == mirrorRoot) {
2765 // This is to avoid cyclical mirroring.
2766 continue;
2767 }
2768 sp<Layer> clonedChild = clonedLayersMap[child];
2769 if (clonedChild == nullptr) {
Vishnu Nairde177252023-04-21 12:44:10 -07002770 clonedChild = child->createClone(mirrorRoot->getSequence());
chaviw74b03172019-08-19 11:09:03 -07002771 clonedLayersMap[child] = clonedChild;
2772 }
2773 addChildToDrawing(clonedChild);
2774 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2775 }
2776}
2777
chaviwaf87b3e2019-10-01 16:59:28 -07002778void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2779 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2780 if (cropLayer != nullptr) {
2781 if (clonedLayersMap.count(cropLayer) == 0) {
2782 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2783 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002784 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002785 } else {
2786 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2787 mDrawingState.touchableRegionCrop = clonedCropLayer;
2788 }
2789 }
2790 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2791 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002792 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002793}
2794
2795void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002796 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002797 mDrawingState.zOrderRelatives.clear();
2798
2799 if (!isClonedFromAlive()) {
2800 return;
2801 }
2802
chaviwaf87b3e2019-10-01 16:59:28 -07002803 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002804 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002805 const sp<Layer>& relative = relativeWeak.promote();
2806 if (clonedLayersMap.count(relative) > 0) {
2807 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002808 mDrawingState.zOrderRelatives.add(clonedRelative);
2809 }
2810 }
2811
2812 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2813 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2814 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2815 // still traverse the children, but the layer with the missing relativeOf will not be shown
2816 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002817 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2818 if (clonedLayersMap.count(relativeOf) > 0) {
2819 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002820 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2821 }
2822
chaviwaf87b3e2019-10-01 16:59:28 -07002823 updateClonedInputInfo(clonedLayersMap);
2824
chaviw74b03172019-08-19 11:09:03 -07002825 for (sp<Layer>& child : mDrawingChildren) {
2826 child->updateClonedRelatives(clonedLayersMap);
2827 }
2828}
2829
2830void Layer::addChildToDrawing(const sp<Layer>& layer) {
2831 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002832 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002833}
2834
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002835bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002836 const State& s(mDrawingState);
2837 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2838 return true;
2839 }
2840
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002841 sp<Layer> parent = mDrawingParent.promote();
2842 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002843}
2844
Robert Carr6a0382d2021-07-01 15:57:17 -07002845void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2846 mClonedChild = clonedChild;
2847 mHadClonedChild = true;
Vishnu Nair3be61902023-04-26 19:47:29 -07002848 mFlinger->mLayerMirrorRoots.push_back(this);
Robert Carr6a0382d2021-07-01 15:57:17 -07002849}
2850
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002851bool Layer::setDropInputMode(gui::DropInputMode mode) {
2852 if (mDrawingState.dropInputMode == mode) {
2853 return false;
2854 }
2855 mDrawingState.dropInputMode = mode;
2856 return true;
2857}
2858
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002859void Layer::cloneDrawingState(const Layer* from) {
2860 mDrawingState = from->mDrawingState;
2861 // Skip callback info since they are not applicable for cloned layers.
2862 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002863 // TODO (b/238781169) currently broken for mirror layers because we do not
2864 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002865 mDrawingState.callbackHandles = {};
2866}
2867
Patrick Williamsbb25f802022-08-30 23:02:34 +00002868void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2869 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08002870 const sp<Fence>& releaseFence) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002871 if (!listener) {
2872 return;
2873 }
2874 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
liulijuneb489f62022-10-17 22:02:14 +08002875 uint32_t currentMaxAcquiredBufferCount =
2876 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002877 listener->onReleaseBuffer({buffer->getId(), framenumber},
2878 releaseFence ? releaseFence : Fence::NO_FENCE,
2879 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002880}
2881
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002882void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult,
2883 ui::LayerStack layerStack) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002884 // If we are displayed on multiple displays in a single composition cycle then we would
2885 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2886 // For example we can only use it if all the displays are client comp, and we need
2887 // to merge all the client comp fences. We could do this, but for now we just
2888 // disable the optimization when a layer is composed on multiple displays.
2889 if (mClearClientCompositionFenceOnLayerDisplayed) {
2890 mLastClientCompositionFence = nullptr;
2891 } else {
2892 mClearClientCompositionFenceOnLayerDisplayed = true;
2893 }
2894
2895 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2896 // buffer that was presented on this layer. The first transaction that came in this frame that
2897 // replaced the previous buffer on this layer needs this release fence, because the fence will
2898 // let the client know when that previous buffer is removed from the screen.
2899 //
2900 // Every other transaction on this layer does not need a release fence because no other
2901 // Transactions that were set on this layer this frame are going to have their preceding buffer
2902 // removed from the display this frame.
2903 //
2904 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2905 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2906 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2907 // the previous buffer will be released this frame. The third transaction also contains a
2908 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2909 // transaction will now no longer be presented so it is released immediately and the third
2910 // transaction doesn't need a previous release fence.
2911 sp<CallbackHandle> ch;
2912 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002913 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002914 ch = handle;
2915 break;
2916 }
2917 }
2918
2919 // Prevent tracing the same release multiple times.
2920 if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
2921 mPreviousReleasedFrameNumber = mPreviousFrameNumber;
2922 }
2923
2924 if (ch != nullptr) {
2925 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2926 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2927 ch->name = mName;
2928 }
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002929 mPreviouslyPresentedLayerStacks.push_back(layerStack);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002930}
2931
2932void Layer::onSurfaceFrameCreated(
2933 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
2934 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
2935 // Too many SurfaceFrames pending classification. The front of the deque is probably not
2936 // tracked by FrameTimeline and will never be presented. This will only result in a memory
2937 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01002938 if (hasBufferOrSidebandStreamInDrawing()) {
2939 // Only log for layers with a buffer, since we expect the jank data to be drained for
2940 // these, while there may be no jank listeners for bufferless layers.
2941 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
2942 mName.c_str());
2943 std::string miniDump = mPendingJankClassifications.front()->miniDump();
2944 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
2945 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002946 mPendingJankClassifications.pop_front();
2947 }
2948 mPendingJankClassifications.emplace_back(surfaceFrame);
2949}
2950
2951void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2952 for (const auto& handle : mDrawingState.callbackHandles) {
Lloyd Pique30db6402023-06-26 18:56:51 +00002953 if (mFlinger->mLayerLifecycleManagerEnabled) {
Vishnu Nairb76d99a2023-03-19 18:22:31 -07002954 handle->transformHint = mTransformHint;
2955 } else {
2956 handle->transformHint = mSkipReportingTransformHint
2957 ? std::nullopt
2958 : std::make_optional<uint32_t>(mTransformHintLegacy);
2959 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002960 handle->dequeueReadyTime = dequeueReadyTime;
2961 handle->currentMaxAcquiredBufferCount =
2962 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
2963 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2964 handle->previousReleaseCallbackId.framenumber);
2965 }
2966
2967 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002968 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002969 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2970 break;
2971 }
2972 }
2973
2974 std::vector<JankData> jankData;
Pascal Muetschardf54181b2022-12-13 14:53:25 +01002975 transferAvailableJankData(mDrawingState.callbackHandles, jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002976 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
2977 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002978 mDrawingState.callbackHandles = {};
2979}
2980
2981bool Layer::willPresentCurrentTransaction() const {
2982 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2983 return (getSidebandStreamChanged() || getAutoRefresh() ||
2984 (mDrawingState.modified &&
2985 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2986}
2987
2988bool Layer::setTransform(uint32_t transform) {
2989 if (mDrawingState.bufferTransform == transform) return false;
2990 mDrawingState.bufferTransform = transform;
2991 mDrawingState.modified = true;
2992 setTransactionFlags(eTransactionNeeded);
2993 return true;
2994}
2995
2996bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
2997 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
2998 mDrawingState.sequence++;
2999 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
3000 mDrawingState.modified = true;
3001 setTransactionFlags(eTransactionNeeded);
3002 return true;
3003}
3004
3005bool Layer::setBufferCrop(const Rect& bufferCrop) {
3006 if (mDrawingState.bufferCrop == bufferCrop) return false;
3007
3008 mDrawingState.sequence++;
3009 mDrawingState.bufferCrop = bufferCrop;
3010
3011 mDrawingState.modified = true;
3012 setTransactionFlags(eTransactionNeeded);
3013 return true;
3014}
3015
3016bool Layer::setDestinationFrame(const Rect& destinationFrame) {
3017 if (mDrawingState.destinationFrame == destinationFrame) return false;
3018
3019 mDrawingState.sequence++;
3020 mDrawingState.destinationFrame = destinationFrame;
3021
3022 mDrawingState.modified = true;
3023 setTransactionFlags(eTransactionNeeded);
3024 return true;
3025}
3026
3027// Translate destination frame into scale and position. If a destination frame is not set, use the
3028// provided scale and position
3029bool Layer::updateGeometry() {
3030 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
3031 mDrawingState.destinationFrame.isEmpty()) {
3032 // If destination frame is not set, use the requested transform set via
3033 // Layer::setPosition and Layer::setMatrix.
3034 return assignTransform(&mDrawingState.transform, mRequestedTransform);
3035 }
3036
3037 Rect destRect = mDrawingState.destinationFrame;
3038 int32_t destW = destRect.width();
3039 int32_t destH = destRect.height();
3040 if (destRect.left < 0) {
3041 destRect.left = 0;
3042 destRect.right = destW;
3043 }
3044 if (destRect.top < 0) {
3045 destRect.top = 0;
3046 destRect.bottom = destH;
3047 }
3048
3049 if (!mDrawingState.buffer) {
3050 ui::Transform t;
3051 t.set(destRect.left, destRect.top);
3052 return assignTransform(&mDrawingState.transform, t);
3053 }
3054
3055 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
3056 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
3057 // Undo any transformations on the buffer.
3058 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
3059 std::swap(bufferWidth, bufferHeight);
3060 }
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003061 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003062 if (mDrawingState.transformToDisplayInverse) {
3063 if (invTransform & ui::Transform::ROT_90) {
3064 std::swap(bufferWidth, bufferHeight);
3065 }
3066 }
3067
3068 float sx = destW / static_cast<float>(bufferWidth);
3069 float sy = destH / static_cast<float>(bufferHeight);
3070 ui::Transform t;
3071 t.set(sx, 0, 0, sy);
3072 t.set(destRect.left, destRect.top);
3073 return assignTransform(&mDrawingState.transform, t);
3074}
3075
3076bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
3077 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
3078 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
3079 return false;
3080 }
3081
3082 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
3083
3084 mDrawingState.sequence++;
3085 mDrawingState.modified = true;
3086 setTransactionFlags(eTransactionNeeded);
3087
3088 return true;
3089}
3090
3091bool Layer::setPosition(float x, float y) {
3092 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3093 return false;
3094 }
3095
3096 mRequestedTransform.set(x, y);
3097
3098 mDrawingState.sequence++;
3099 mDrawingState.modified = true;
3100 setTransactionFlags(eTransactionNeeded);
3101
3102 return true;
3103}
3104
Dorin Drimuse5374e52023-08-02 17:52:43 +00003105void Layer::releasePreviousBuffer() {
3106 mReleasePreviousBuffer = true;
3107 if (!mBufferInfo.mBuffer ||
3108 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3109 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3110 // If mDrawingState has a buffer, and we are about to update again
3111 // before swapping to drawing state, then the first buffer will be
3112 // dropped and we should decrement the pending buffer count and
3113 // call any release buffer callbacks if set.
3114 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3115 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3116 mDrawingState.acquireFence);
3117 decrementPendingBufferCount();
3118 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3119 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3120 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX, systemTime());
3121 mDrawingState.bufferSurfaceFrameTX.reset();
3122 }
3123 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3124 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3125 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3126 mLastClientCompositionFence);
3127 mLastClientCompositionFence = nullptr;
3128 }
3129}
3130
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003131void Layer::resetDrawingStateBufferInfo() {
3132 mDrawingState.producerId = 0;
3133 mDrawingState.frameNumber = 0;
3134 mDrawingState.releaseBufferListener = nullptr;
3135 mDrawingState.buffer = nullptr;
3136 mDrawingState.acquireFence = sp<Fence>::make(-1);
3137 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3138 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3139 mDrawingState.releaseBufferEndpoint = nullptr;
3140}
3141
Patrick Williamsbb25f802022-08-30 23:02:34 +00003142bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3143 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3144 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07003145 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003146 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003147
3148 const bool frameNumberChanged =
3149 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3150 const uint64_t frameNumber =
3151 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003152 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003153
3154 if (mDrawingState.buffer) {
Dorin Drimuse5374e52023-08-02 17:52:43 +00003155 releasePreviousBuffer();
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003156 } else if (buffer) {
Vishnu Nairc09c0232023-03-02 03:22:35 +00003157 // if we are latching a buffer for the first time then clear the mLastLatchTime since
3158 // we don't want to incorrectly classify a frame if we miss the desired present time.
3159 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003160 }
3161
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003162 mDrawingState.desiredPresentTime = desiredPresentTime;
3163 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3164 mDrawingState.latchedVsyncId = info.vsyncId;
Ady Abraham55269162023-05-09 11:26:06 -07003165 mDrawingState.useVsyncIdForRefreshRateSelection = info.useForRefreshRateSelection;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003166 mDrawingState.modified = true;
3167 if (!buffer) {
3168 resetDrawingStateBufferInfo();
3169 setTransactionFlags(eTransactionNeeded);
3170 mDrawingState.bufferSurfaceFrameTX = nullptr;
3171 setFrameTimelineVsyncForBufferlessTransaction(info, postTime);
3172 return true;
Dorin Drimuse5374e52023-08-02 17:52:43 +00003173 } else {
3174 // release sideband stream if it exists and a non null buffer is being set
3175 if (mDrawingState.sidebandStream != nullptr) {
3176 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3177 mDrawingState.sidebandStream = nullptr;
3178 }
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003179 }
3180
Vishnu Naird1f74982023-06-15 20:16:51 -07003181 if ((mDrawingState.producerId > bufferData.producerId) ||
3182 ((mDrawingState.producerId == bufferData.producerId) &&
3183 (mDrawingState.frameNumber > frameNumber))) {
3184 ALOGE("Out of order buffers detected for %s producedId=%d frameNumber=%" PRIu64
3185 " -> producedId=%d frameNumber=%" PRIu64,
3186 getDebugName(), mDrawingState.producerId, mDrawingState.frameNumber,
3187 bufferData.producerId, frameNumber);
3188 TransactionTraceWriter::getInstance().invoke("out_of_order_buffers_", /*overwrite=*/false);
3189 }
3190
liulijuneb489f62022-10-17 22:02:14 +08003191 mDrawingState.producerId = bufferData.producerId;
Vishnu Nair63221212023-04-06 15:17:37 -07003192 mDrawingState.barrierProducerId =
3193 std::max(mDrawingState.producerId, mDrawingState.barrierProducerId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003194 mDrawingState.frameNumber = frameNumber;
Vishnu Nair63221212023-04-06 15:17:37 -07003195 mDrawingState.barrierFrameNumber =
3196 std::max(mDrawingState.frameNumber, mDrawingState.barrierFrameNumber);
3197
Patrick Williamsbb25f802022-08-30 23:02:34 +00003198 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3199 mDrawingState.buffer = std::move(buffer);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003200 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3201 ? bufferData.acquireFence
3202 : Fence::NO_FENCE;
3203 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3204 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3205 // We latched this buffer unsiganled, so we need to pass the acquire fence
3206 // on the callback instead of just the acquire time, since it's unknown at
3207 // this point.
3208 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3209 } else {
3210 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3211 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003212 setTransactionFlags(eTransactionNeeded);
3213
3214 const int32_t layerId = getSequence();
3215 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3216 mOwnerUid, postTime, getGameMode());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003217
Lloyd Pique30db6402023-06-26 18:56:51 +00003218 if (mFlinger->mLegacyFrontEndEnabled) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003219 recordLayerHistoryBufferUpdate(getLayerProps());
3220 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003221
3222 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3223
3224 if (dequeueTime && *dequeueTime != 0) {
3225 const uint64_t bufferId = mDrawingState.buffer->getId();
3226 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3227 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3228 FrameTracer::FrameEvent::DEQUEUE);
3229 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3230 FrameTracer::FrameEvent::QUEUE);
3231 }
3232
3233 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
Arthur Hungc70bee22023-06-02 01:35:52 +00003234
3235 // If the layer had been updated a TextureView, this would make sure the present time could be
3236 // same to TextureView update when it's a small dirty, and get the correct heuristic rate.
3237 if (mFlinger->mScheduler->supportSmallDirtyDetection()) {
3238 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
3239 mUsedVsyncIdForRefreshRateSelection = true;
3240 }
3241 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003242 return true;
3243}
3244
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003245void Layer::setDesiredPresentTime(nsecs_t desiredPresentTime, bool isAutoTimestamp) {
3246 mDrawingState.desiredPresentTime = desiredPresentTime;
3247 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3248}
3249
3250void Layer::recordLayerHistoryBufferUpdate(const scheduler::LayerProps& layerProps) {
Ady Abraham55269162023-05-09 11:26:06 -07003251 ATRACE_CALL();
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003252 const nsecs_t presentTime = [&] {
Ady Abraham55269162023-05-09 11:26:06 -07003253 if (!mDrawingState.isAutoTimestamp) {
3254 ATRACE_FORMAT_INSTANT("desiredPresentTime");
3255 return mDrawingState.desiredPresentTime;
3256 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003257
Ady Abraham55269162023-05-09 11:26:06 -07003258 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
3259 const auto prediction =
3260 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3261 mDrawingState.latchedVsyncId);
3262 if (prediction.has_value()) {
3263 ATRACE_FORMAT_INSTANT("predictedPresentTime");
Arthur Hungc70bee22023-06-02 01:35:52 +00003264 mMaxTimeForUseVsyncId = prediction->presentTime +
3265 scheduler::LayerHistory::kMaxPeriodForHistory.count();
Ady Abraham55269162023-05-09 11:26:06 -07003266 return prediction->presentTime;
3267 }
3268 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003269
Arthur Hungc70bee22023-06-02 01:35:52 +00003270 if (!mFlinger->mScheduler->supportSmallDirtyDetection()) {
3271 return static_cast<nsecs_t>(0);
3272 }
3273
3274 // If the layer is not an application and didn't set an explicit rate or desiredPresentTime,
3275 // return "0" to tell the layer history that it will use the max refresh rate without
3276 // calculating the adaptive rate.
3277 if (mWindowType != WindowInfo::Type::APPLICATION &&
3278 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
3279 return static_cast<nsecs_t>(0);
3280 }
3281
3282 // Return the valid present time only when the layer potentially updated a TextureView so
3283 // LayerHistory could heuristically calculate the rate if the UI is continually updating.
3284 if (mUsedVsyncIdForRefreshRateSelection) {
3285 const auto prediction =
3286 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3287 mDrawingState.latchedVsyncId);
3288 if (prediction.has_value()) {
3289 if (mMaxTimeForUseVsyncId >= prediction->presentTime) {
3290 return prediction->presentTime;
3291 }
3292 mUsedVsyncIdForRefreshRateSelection = false;
3293 }
3294 }
3295
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003296 return static_cast<nsecs_t>(0);
3297 }();
Ady Abraham55269162023-05-09 11:26:06 -07003298
3299 if (ATRACE_ENABLED() && presentTime > 0) {
3300 const auto presentIn = TimePoint::fromNs(presentTime) - TimePoint::now();
3301 ATRACE_FORMAT_INSTANT("presentIn %s", to_string(presentIn).c_str());
3302 }
3303
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003304 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3305 scheduler::LayerHistory::LayerUpdateType::Buffer);
3306}
3307
3308void Layer::recordLayerHistoryAnimationTx(const scheduler::LayerProps& layerProps) {
3309 const nsecs_t presentTime =
3310 mDrawingState.isAutoTimestamp ? 0 : mDrawingState.desiredPresentTime;
3311 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime,
3312 scheduler::LayerHistory::LayerUpdateType::AnimationTX);
3313}
3314
Patrick Williamsbb25f802022-08-30 23:02:34 +00003315bool Layer::setDataspace(ui::Dataspace dataspace) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003316 if (mDrawingState.dataspace == dataspace) return false;
3317 mDrawingState.dataspace = dataspace;
3318 mDrawingState.modified = true;
3319 setTransactionFlags(eTransactionNeeded);
3320 return true;
3321}
3322
John Reck68796592023-01-25 13:47:12 -05003323bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
Sally Qi963049b2023-03-23 14:06:21 -07003324 if (mDrawingState.currentHdrSdrRatio == currentBufferRatio &&
3325 mDrawingState.desiredHdrSdrRatio == desiredRatio)
John Reck68796592023-01-25 13:47:12 -05003326 return false;
Sally Qi963049b2023-03-23 14:06:21 -07003327 mDrawingState.currentHdrSdrRatio = currentBufferRatio;
3328 mDrawingState.desiredHdrSdrRatio = desiredRatio;
John Reck68796592023-01-25 13:47:12 -05003329 mDrawingState.modified = true;
3330 setTransactionFlags(eTransactionNeeded);
3331 return true;
3332}
3333
Alec Mourif4af03e2023-02-11 00:25:24 +00003334bool Layer::setCachingHint(gui::CachingHint cachingHint) {
3335 if (mDrawingState.cachingHint == cachingHint) return false;
3336 mDrawingState.cachingHint = cachingHint;
3337 mDrawingState.modified = true;
3338 setTransactionFlags(eTransactionNeeded);
3339 return true;
3340}
3341
Patrick Williamsbb25f802022-08-30 23:02:34 +00003342bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3343 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3344 mDrawingState.hdrMetadata = hdrMetadata;
3345 mDrawingState.modified = true;
3346 setTransactionFlags(eTransactionNeeded);
3347 return true;
3348}
3349
3350bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Sally Qi2b1b4292023-03-14 16:47:39 +00003351 if (mDrawingState.surfaceDamageRegion.hasSameRects(surfaceDamage)) return false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003352 mDrawingState.surfaceDamageRegion = surfaceDamage;
3353 mDrawingState.modified = true;
3354 setTransactionFlags(eTransactionNeeded);
Arthur Hungc70bee22023-06-02 01:35:52 +00003355 setIsSmallDirty();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003356 return true;
3357}
3358
3359bool Layer::setApi(int32_t api) {
3360 if (mDrawingState.api == api) return false;
3361 mDrawingState.api = api;
3362 mDrawingState.modified = true;
3363 setTransactionFlags(eTransactionNeeded);
3364 return true;
3365}
3366
Dorin Drimuse5374e52023-08-02 17:52:43 +00003367bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream, const FrameTimelineInfo& info,
3368 nsecs_t postTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003369 if (mDrawingState.sidebandStream == sidebandStream) return false;
3370
3371 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3372 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3373 } else if (sidebandStream != nullptr) {
3374 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3375 }
3376
3377 mDrawingState.sidebandStream = sidebandStream;
3378 mDrawingState.modified = true;
Dorin Drimuse5374e52023-08-02 17:52:43 +00003379 if (sidebandStream != nullptr && mDrawingState.buffer != nullptr) {
3380 releasePreviousBuffer();
3381 resetDrawingStateBufferInfo();
3382 mDrawingState.bufferSurfaceFrameTX = nullptr;
3383 setFrameTimelineVsyncForBufferlessTransaction(info, postTime);
3384 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003385 setTransactionFlags(eTransactionNeeded);
3386 if (!mSidebandStreamChanged.exchange(true)) {
3387 // mSidebandStreamChanged was false
3388 mFlinger->onLayerUpdate();
3389 }
3390 return true;
3391}
3392
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003393bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3394 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003395 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3396 if (handles.empty()) {
3397 mReleasePreviousBuffer = false;
3398 return false;
3399 }
3400
Pascal Muetschard81cef292023-02-06 12:18:52 +01003401 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003402 for (const auto& handle : handles) {
3403 // If this transaction set a buffer on this layer, release its previous buffer
3404 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3405
3406 // If this layer will be presented in this frame
3407 if (willPresent) {
3408 // If this transaction set an acquire fence on this layer, set its acquire time
3409 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3410 handle->frameNumber = mDrawingState.frameNumber;
3411
3412 // Store so latched time and release fence can be set
3413 mDrawingState.callbackHandles.push_back(handle);
3414
3415 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01003416 // Queue this handle to be notified below.
3417 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003418 }
3419 }
3420
Pascal Muetschard81cef292023-02-06 12:18:52 +01003421 if (!remainingHandles.empty()) {
3422 // Notify the transaction completed threads these handles are done. These are only the
3423 // handles that were not added to the mDrawingState, which will be notified later.
3424 std::vector<JankData> jankData;
3425 transferAvailableJankData(remainingHandles, jankData);
3426 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles, jankData);
3427 }
3428
Patrick Williamsbb25f802022-08-30 23:02:34 +00003429 mReleasePreviousBuffer = false;
3430 mCallbackHandleAcquireTimeOrFence = -1;
3431
3432 return willPresent;
3433}
3434
3435Rect Layer::getBufferSize(const State& /*s*/) const {
3436 // for buffer state layers we use the display frame size as the buffer size.
3437
3438 if (mBufferInfo.mBuffer == nullptr) {
3439 return Rect::INVALID_RECT;
3440 }
3441
3442 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3443 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3444
3445 // Undo any transformations on the buffer and return the result.
3446 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3447 std::swap(bufWidth, bufHeight);
3448 }
3449
3450 if (getTransformToDisplayInverse()) {
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003451 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003452 if (invTransform & ui::Transform::ROT_90) {
3453 std::swap(bufWidth, bufHeight);
3454 }
3455 }
3456
3457 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3458}
3459
3460FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3461 if (mBufferInfo.mBuffer == nullptr) {
3462 return parentBounds;
3463 }
3464
3465 return getBufferSize(getDrawingState()).toFloatRect();
3466}
3467
3468bool Layer::fenceHasSignaled() const {
3469 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3470 return true;
3471 }
3472
3473 const bool fenceSignaled =
3474 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3475 if (!fenceSignaled) {
3476 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3477 TimeStats::LatchSkipReason::LateAcquire);
3478 }
3479
3480 return fenceSignaled;
3481}
3482
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003483void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003484 for (const auto& handle : mDrawingState.callbackHandles) {
3485 handle->refreshStartTime = refreshStartTime;
3486 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003487}
3488
3489void Layer::setAutoRefresh(bool autoRefresh) {
3490 mDrawingState.autoRefresh = autoRefresh;
3491}
3492
3493bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3494 // 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 +00003495 auto* snapshot = editLayerSnapshot();
3496 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003497
3498 if (mSidebandStreamChanged.exchange(false)) {
3499 const State& s(getDrawingState());
3500 // mSidebandStreamChanged was true
3501 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003502 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003503 if (mSidebandStream != nullptr) {
3504 setTransactionFlags(eTransactionNeeded);
3505 mFlinger->setTransactionFlags(eTraversalNeeded);
3506 }
3507 recomputeVisibleRegions = true;
3508
3509 return true;
3510 }
3511 return false;
3512}
3513
3514bool Layer::hasFrameUpdate() const {
3515 const State& c(getDrawingState());
3516 return (mDrawingStateModified || mDrawingState.modified) &&
3517 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3518}
3519
Vishnu Naird47bcee2023-02-24 18:08:51 +00003520void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003521 const State& s(getDrawingState());
3522
3523 if (!s.buffer) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003524 if (bgColorOnly || mBufferInfo.mBuffer) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003525 for (auto& handle : mDrawingState.callbackHandles) {
3526 handle->latchTime = latchTime;
3527 }
3528 }
3529 return;
3530 }
3531
3532 for (auto& handle : mDrawingState.callbackHandles) {
3533 if (handle->frameNumber == mDrawingState.frameNumber) {
3534 handle->latchTime = latchTime;
3535 }
3536 }
3537
3538 const int32_t layerId = getSequence();
3539 const uint64_t bufferId = mDrawingState.buffer->getId();
3540 const uint64_t frameNumber = mDrawingState.frameNumber;
3541 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3542 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3543 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3544
3545 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3546 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3547 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3548 FrameTracer::FrameEvent::LATCH);
3549
3550 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3551 if (bufferSurfaceFrame != nullptr &&
3552 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3553 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3554 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3555 // are processing the next state.
3556 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3557 mDrawingState.acquireFenceTime->getSignalTime(),
3558 latchTime);
3559 mDrawingState.bufferSurfaceFrameTX.reset();
3560 }
3561
3562 std::deque<sp<CallbackHandle>> remainingHandles;
3563 mFlinger->getTransactionCallbackInvoker()
3564 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3565 mDrawingState.callbackHandles = remainingHandles;
3566
3567 mDrawingStateModified = false;
3568}
3569
3570void Layer::gatherBufferInfo() {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003571 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3572 mPreviousReleaseBufferEndpoint = mBufferInfo.mReleaseBufferEndpoint;
3573 if (!mDrawingState.buffer) {
3574 mBufferInfo = {};
3575 return;
3576 }
3577
3578 if ((!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer))) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003579 decrementPendingBufferCount();
3580 }
3581
Patrick Williamsbb25f802022-08-30 23:02:34 +00003582 mBufferInfo.mBuffer = mDrawingState.buffer;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003583 mBufferInfo.mReleaseBufferEndpoint = mDrawingState.releaseBufferEndpoint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003584 mBufferInfo.mFence = mDrawingState.acquireFence;
3585 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3586 mBufferInfo.mPixelFormat =
3587 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3588 mBufferInfo.mFrameLatencyNeeded = true;
3589 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3590 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3591 mBufferInfo.mFence = mDrawingState.acquireFence;
3592 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3593 auto lastDataspace = mBufferInfo.mDataspace;
3594 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
Alec Mouri74c7ae12023-03-26 02:57:47 +00003595 if (mBufferInfo.mBuffer != nullptr) {
3596 auto& mapper = GraphicBufferMapper::get();
3597 // TODO: We should measure if it's faster to do a blind write if we're on newer api levels
3598 // and don't need to possibly remaps buffers.
3599 ui::Dataspace dataspace = ui::Dataspace::UNKNOWN;
3600 status_t err = OK;
3601 {
3602 ATRACE_NAME("getDataspace");
3603 err = mapper.getDataspace(mBufferInfo.mBuffer->getBuffer()->handle, &dataspace);
3604 }
3605 if (err != OK || dataspace != mBufferInfo.mDataspace) {
3606 {
3607 ATRACE_NAME("setDataspace");
3608 err = mapper.setDataspace(mBufferInfo.mBuffer->getBuffer()->handle,
3609 static_cast<ui::Dataspace>(mBufferInfo.mDataspace));
3610 }
3611
3612 // Some GPU drivers may cache gralloc metadata which means before we composite we need
3613 // to upsert RenderEngine's caches. Put in a special workaround to be backwards
3614 // compatible with old vendors, with a ticking clock.
3615 static const int32_t kVendorVersion =
3616 base::GetIntProperty("ro.vndk.version", __ANDROID_API_FUTURE__);
3617 if (const auto format =
3618 static_cast<aidl::android::hardware::graphics::common::PixelFormat>(
3619 mBufferInfo.mBuffer->getPixelFormat());
3620 err == OK && kVendorVersion < __ANDROID_API_U__ &&
3621 (format ==
3622 aidl::android::hardware::graphics::common::PixelFormat::
3623 IMPLEMENTATION_DEFINED ||
3624 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_420_888 ||
3625 format == aidl::android::hardware::graphics::common::PixelFormat::YV12 ||
3626 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_P010)) {
3627 mBufferInfo.mBuffer->remapBuffer();
3628 }
3629 }
3630 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003631 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003632 mFlinger->mHdrLayerInfoChanged = true;
3633 }
Sally Qi963049b2023-03-23 14:06:21 -07003634 if (mBufferInfo.mDesiredHdrSdrRatio != mDrawingState.desiredHdrSdrRatio) {
3635 mBufferInfo.mDesiredHdrSdrRatio = mDrawingState.desiredHdrSdrRatio;
John Reck68796592023-01-25 13:47:12 -05003636 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003637 }
3638 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3639 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3640 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3641 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3642 mBufferInfo.mApi = mDrawingState.api;
3643 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003644}
3645
3646Rect Layer::computeBufferCrop(const State& s) {
3647 if (s.buffer && !s.bufferCrop.isEmpty()) {
3648 Rect bufferCrop;
3649 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3650 return bufferCrop;
3651 } else if (s.buffer) {
3652 return s.buffer->getBounds();
3653 } else {
3654 return s.bufferCrop;
3655 }
3656}
3657
Vishnu Nairde177252023-04-21 12:44:10 -07003658sp<Layer> Layer::createClone(uint32_t mirrorRootId) {
Kean Mariotti4ba343c2023-04-19 13:31:02 +00003659 surfaceflinger::LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0,
3660 LayerMetadata());
Patrick Williams83f36b22022-09-14 17:57:35 +00003661 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Vishnu Nairde177252023-04-21 12:44:10 -07003662 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this), mirrorRootId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003663 return layer;
3664}
3665
Patrick Williamsbb25f802022-08-30 23:02:34 +00003666void Layer::decrementPendingBufferCount() {
3667 int32_t pendingBuffers = --mPendingBufferTransactions;
3668 tracePendingBufferCount(pendingBuffers);
3669}
3670
3671void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3672 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3673}
3674
3675/*
3676 * We don't want to send the layer's transform to input, but rather the
3677 * parent's transform. This is because Layer's transform is
3678 * information about how the buffer is placed on screen. The parent's
3679 * transform makes more sense to send since it's information about how the
3680 * layer is placed on screen. This transform is used by input to determine
3681 * how to go from screen space back to window space.
3682 */
3683ui::Transform Layer::getInputTransform() const {
3684 if (!hasBufferOrSidebandStream()) {
3685 return getTransform();
3686 }
3687 sp<Layer> parent = mDrawingParent.promote();
3688 if (parent == nullptr) {
3689 return ui::Transform();
3690 }
3691
3692 return parent->getTransform();
3693}
3694
3695/**
Vishnu Nairfed7c122023-03-18 01:54:43 +00003696 * Returns the bounds used to fill the input frame and the touchable region.
3697 *
Patrick Williamsbb25f802022-08-30 23:02:34 +00003698 * Similar to getInputTransform, we need to update the bounds to include the transform.
3699 * This is because bounds don't include the buffer transform, where the input assumes
3700 * that's already included.
3701 */
Vishnu Nairfed7c122023-03-18 01:54:43 +00003702std::pair<FloatRect, bool> Layer::getInputBounds(bool fillParentBounds) const {
3703 Rect croppedBufferSize = getCroppedBufferSize(getDrawingState());
3704 FloatRect inputBounds = croppedBufferSize.toFloatRect();
3705 if (hasBufferOrSidebandStream() && croppedBufferSize.isValid() &&
3706 mDrawingState.transform.getType() != ui::Transform::IDENTITY) {
3707 inputBounds = mDrawingState.transform.transform(inputBounds);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003708 }
3709
Vishnu Nairfed7c122023-03-18 01:54:43 +00003710 bool inputBoundsValid = croppedBufferSize.isValid();
3711 if (!inputBoundsValid) {
3712 /**
3713 * Input bounds are based on the layer crop or buffer size. But if we are using
3714 * the layer bounds as the input bounds (replaceTouchableRegionWithCrop flag) then
3715 * we can use the parent bounds as the input bounds if the layer does not have buffer
3716 * or a crop. We want to unify this logic but because of compat reasons we cannot always
3717 * use the parent bounds. A layer without a buffer can get input. So when a window is
3718 * initially added, its touchable region can fill its parent layer bounds and that can
3719 * have negative consequences.
3720 */
3721 inputBounds = fillParentBounds ? mBounds : FloatRect{};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003722 }
Vishnu Nairfed7c122023-03-18 01:54:43 +00003723
3724 // Clamp surface inset to the input bounds.
3725 const float inset = static_cast<float>(mDrawingState.inputInfo.surfaceInset);
3726 const float xSurfaceInset = std::clamp(inset, 0.f, inputBounds.getWidth() / 2.f);
3727 const float ySurfaceInset = std::clamp(inset, 0.f, inputBounds.getHeight() / 2.f);
3728
3729 // Apply the insets to the input bounds.
3730 inputBounds.left += xSurfaceInset;
3731 inputBounds.top += ySurfaceInset;
3732 inputBounds.right -= xSurfaceInset;
3733 inputBounds.bottom -= ySurfaceInset;
3734
3735 return {inputBounds, inputBoundsValid};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003736}
3737
Ady Abraham005398b2023-06-05 13:59:41 -07003738bool Layer::isSimpleBufferUpdate(const layer_state_t& s) const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003739 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3740
3741 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3742 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3743 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3744 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3745 layer_state_t::eReparent;
3746
Patrick Williamsbb25f802022-08-30 23:02:34 +00003747 if ((s.what & requiredFlags) != requiredFlags) {
Ady Abraham005398b2023-06-05 13:59:41 -07003748 ATRACE_FORMAT_INSTANT("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3749 (s.what | requiredFlags) & ~s.what);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003750 return false;
3751 }
3752
3753 if (s.what & deniedFlags) {
Ady Abraham005398b2023-06-05 13:59:41 -07003754 ATRACE_FORMAT_INSTANT("%s: false [has denied flags 0x%" PRIx64 "]", __func__,
3755 s.what & deniedFlags);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003756 return false;
3757 }
3758
Patrick Williamsbb25f802022-08-30 23:02:34 +00003759 if (s.what & layer_state_t::ePositionChanged) {
3760 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
Ady Abraham005398b2023-06-05 13:59:41 -07003761 ATRACE_FORMAT_INSTANT("%s: false [ePositionChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003762 return false;
3763 }
3764 }
3765
3766 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003767 if (mDrawingState.color.a != s.color.a) {
Ady Abraham005398b2023-06-05 13:59:41 -07003768 ATRACE_FORMAT_INSTANT("%s: false [eAlphaChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003769 return false;
3770 }
3771 }
3772
3773 if (s.what & layer_state_t::eColorTransformChanged) {
3774 if (mDrawingState.colorTransform != s.colorTransform) {
Ady Abraham005398b2023-06-05 13:59:41 -07003775 ATRACE_FORMAT_INSTANT("%s: false [eColorTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003776 return false;
3777 }
3778 }
3779
3780 if (s.what & layer_state_t::eBackgroundColorChanged) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003781 if (mDrawingState.bgColorLayer || s.bgColor.a != 0) {
Ady Abraham005398b2023-06-05 13:59:41 -07003782 ATRACE_FORMAT_INSTANT("%s: false [eBackgroundColorChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003783 return false;
3784 }
3785 }
3786
3787 if (s.what & layer_state_t::eMatrixChanged) {
3788 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3789 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3790 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3791 mRequestedTransform.dsdy() != s.matrix.dsdy) {
Ady Abraham005398b2023-06-05 13:59:41 -07003792 ATRACE_FORMAT_INSTANT("%s: false [eMatrixChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003793 return false;
3794 }
3795 }
3796
3797 if (s.what & layer_state_t::eCornerRadiusChanged) {
3798 if (mDrawingState.cornerRadius != s.cornerRadius) {
Ady Abraham005398b2023-06-05 13:59:41 -07003799 ATRACE_FORMAT_INSTANT("%s: false [eCornerRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003800 return false;
3801 }
3802 }
3803
3804 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3805 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
Ady Abraham005398b2023-06-05 13:59:41 -07003806 ATRACE_FORMAT_INSTANT("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003807 return false;
3808 }
3809 }
3810
Vishnu Nairbbceb462022-10-10 04:52:13 +00003811 if (s.what & layer_state_t::eBufferTransformChanged) {
3812 if (mDrawingState.bufferTransform != s.bufferTransform) {
Ady Abraham005398b2023-06-05 13:59:41 -07003813 ATRACE_FORMAT_INSTANT("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003814 return false;
3815 }
3816 }
3817
3818 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3819 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
Ady Abraham005398b2023-06-05 13:59:41 -07003820 ATRACE_FORMAT_INSTANT("%s: false [eTransformToDisplayInverseChanged changed]",
3821 __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003822 return false;
3823 }
3824 }
3825
3826 if (s.what & layer_state_t::eCropChanged) {
3827 if (mDrawingState.crop != s.crop) {
Ady Abraham005398b2023-06-05 13:59:41 -07003828 ATRACE_FORMAT_INSTANT("%s: false [eCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003829 return false;
3830 }
3831 }
3832
3833 if (s.what & layer_state_t::eDataspaceChanged) {
3834 if (mDrawingState.dataspace != s.dataspace) {
Ady Abraham005398b2023-06-05 13:59:41 -07003835 ATRACE_FORMAT_INSTANT("%s: false [eDataspaceChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003836 return false;
3837 }
3838 }
3839
3840 if (s.what & layer_state_t::eHdrMetadataChanged) {
3841 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
Ady Abraham005398b2023-06-05 13:59:41 -07003842 ATRACE_FORMAT_INSTANT("%s: false [eHdrMetadataChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003843 return false;
3844 }
3845 }
3846
3847 if (s.what & layer_state_t::eSidebandStreamChanged) {
3848 if (mDrawingState.sidebandStream != s.sidebandStream) {
Ady Abraham005398b2023-06-05 13:59:41 -07003849 ATRACE_FORMAT_INSTANT("%s: false [eSidebandStreamChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003850 return false;
3851 }
3852 }
3853
3854 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3855 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
Ady Abraham005398b2023-06-05 13:59:41 -07003856 ATRACE_FORMAT_INSTANT("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003857 return false;
3858 }
3859 }
3860
3861 if (s.what & layer_state_t::eShadowRadiusChanged) {
3862 if (mDrawingState.shadowRadius != s.shadowRadius) {
Ady Abraham005398b2023-06-05 13:59:41 -07003863 ATRACE_FORMAT_INSTANT("%s: false [eShadowRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003864 return false;
3865 }
3866 }
3867
3868 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3869 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
Ady Abraham005398b2023-06-05 13:59:41 -07003870 ATRACE_FORMAT_INSTANT("%s: false [eFixedTransformHintChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003871 return false;
3872 }
3873 }
3874
3875 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3876 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
Ady Abraham005398b2023-06-05 13:59:41 -07003877 ATRACE_FORMAT_INSTANT("%s: false [eTrustedOverlayChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003878 return false;
3879 }
3880 }
3881
3882 if (s.what & layer_state_t::eStretchChanged) {
3883 StretchEffect temp = s.stretchEffect;
3884 temp.sanitize();
3885 if (mDrawingState.stretchEffect != temp) {
Ady Abraham005398b2023-06-05 13:59:41 -07003886 ATRACE_FORMAT_INSTANT("%s: false [eStretchChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003887 return false;
3888 }
3889 }
3890
3891 if (s.what & layer_state_t::eBufferCropChanged) {
3892 if (mDrawingState.bufferCrop != s.bufferCrop) {
Ady Abraham005398b2023-06-05 13:59:41 -07003893 ATRACE_FORMAT_INSTANT("%s: false [eBufferCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003894 return false;
3895 }
3896 }
3897
3898 if (s.what & layer_state_t::eDestinationFrameChanged) {
3899 if (mDrawingState.destinationFrame != s.destinationFrame) {
Ady Abraham005398b2023-06-05 13:59:41 -07003900 ATRACE_FORMAT_INSTANT("%s: false [eDestinationFrameChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003901 return false;
3902 }
3903 }
3904
3905 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3906 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
Ady Abraham005398b2023-06-05 13:59:41 -07003907 ATRACE_FORMAT_INSTANT("%s: false [eDimmingEnabledChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003908 return false;
3909 }
3910 }
3911
John Reck68796592023-01-25 13:47:12 -05003912 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
Sally Qi963049b2023-03-23 14:06:21 -07003913 if (mDrawingState.currentHdrSdrRatio != s.currentHdrSdrRatio ||
3914 mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
Ady Abraham005398b2023-06-05 13:59:41 -07003915 ATRACE_FORMAT_INSTANT("%s: false [eExtendedRangeBrightnessChanged changed]", __func__);
John Reck68796592023-01-25 13:47:12 -05003916 return false;
3917 }
3918 }
3919
Patrick Williamsbb25f802022-08-30 23:02:34 +00003920 return true;
3921}
3922
Vishnu Naire14c6b32022-08-06 04:20:15 +00003923sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003924 // 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 +00003925 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003926}
3927
Vishnu Naire14c6b32022-08-06 04:20:15 +00003928const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003929 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003930}
3931
Vishnu Naire14c6b32022-08-06 04:20:15 +00003932LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003933 return mSnapshot.get();
3934}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003935
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003936std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
3937 return std::move(mSnapshot);
3938}
3939
3940void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
3941 mSnapshot = std::move(snapshot);
3942}
3943
Patrick Williamsbb25f802022-08-30 23:02:34 +00003944const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003945 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003946}
3947
Patrick Williams7584c6a2022-10-29 02:10:58 +00003948sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003949 auto result = mFlinger->getFactory().createLayerFE(mName);
Patrick Williams7584c6a2022-10-29 02:10:58 +00003950 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3951 return result;
3952}
3953
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003954sp<LayerFE> Layer::getCompositionEngineLayerFE(
3955 const frontend::LayerHierarchy::TraversalPath& path) {
3956 for (auto& [p, layerFE] : mLayerFEs) {
3957 if (p == path) {
3958 return layerFE;
3959 }
3960 }
3961 auto layerFE = mFlinger->getFactory().createLayerFE(mName);
3962 mLayerFEs.emplace_back(path, layerFE);
3963 return layerFE;
3964}
3965
Patrick Williamsbb25f802022-08-30 23:02:34 +00003966void Layer::useSurfaceDamage() {
3967 if (mFlinger->mForceFullDamage) {
3968 surfaceDamageRegion = Region::INVALID_REGION;
3969 } else {
3970 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3971 }
3972}
3973
3974void Layer::useEmptyDamage() {
3975 surfaceDamageRegion.clear();
3976}
3977
3978bool Layer::isOpaque(const Layer::State& s) const {
3979 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3980 // layer's opaque flag.
3981 if (!hasSomethingToDraw()) {
3982 return false;
3983 }
3984
3985 // if the layer has the opaque flag, then we're always opaque
3986 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3987 return true;
3988 }
3989
3990 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003991 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003992 return true;
3993 }
3994
3995 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3996 return fillsColor() && getAlpha() == 1.0_hf;
3997}
3998
3999bool Layer::canReceiveInput() const {
4000 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
4001}
4002
4003bool Layer::isVisible() const {
4004 if (!hasSomethingToDraw()) {
4005 return false;
4006 }
4007
4008 if (isHiddenByPolicy()) {
4009 return false;
4010 }
4011
4012 return getAlpha() > 0.0f || hasBlur();
4013}
4014
4015void Layer::onPostComposition(const DisplayDevice* display,
4016 const std::shared_ptr<FenceTime>& glDoneFence,
4017 const std::shared_ptr<FenceTime>& presentFence,
4018 const CompositorTiming& compositorTiming) {
4019 // mFrameLatencyNeeded is true when a new frame was latched for the
4020 // composition.
4021 if (!mBufferInfo.mFrameLatencyNeeded) return;
4022
4023 for (const auto& handle : mDrawingState.callbackHandles) {
4024 handle->gpuCompositionDoneFence = glDoneFence;
4025 handle->compositorTiming = compositorTiming;
4026 }
4027
4028 // Update mFrameTracker.
4029 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
4030 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
4031
4032 const int32_t layerId = getSequence();
4033 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
4034
4035 const auto outputLayer = findOutputLayerForDisplay(display);
4036 if (outputLayer && outputLayer->requiresClientComposition()) {
4037 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
4038 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
4039 clientCompositionTimestamp,
4040 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
4041 // Update the SurfaceFrames in the drawing state
4042 if (mDrawingState.bufferSurfaceFrameTX) {
4043 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
4044 }
4045 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
4046 surfaceFrame->setGpuComposition();
4047 }
4048 }
4049
4050 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
4051 if (frameReadyFence->isValid()) {
4052 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
4053 } else {
4054 // There was no fence for this frame, so assume that it was ready
4055 // to be presented at the desired present time.
4056 mFrameTracker.setFrameReadyTime(desiredPresentTime);
4057 }
4058
4059 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08004060 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004061 const std::optional<Fps> renderRate =
4062 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
4063
Alec Mouri7c1d8b52023-08-29 20:14:46 +00004064 const auto vote = frameRateToSetFrameRateVotePayload(getFrameRateForLayerTree());
Patrick Williamsbb25f802022-08-30 23:02:34 +00004065 const auto gameMode = getGameMode();
4066
4067 if (presentFence->isValid()) {
4068 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
4069 refreshRate, renderRate, vote, gameMode);
4070 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
4071 presentFence,
4072 FrameTracer::FrameEvent::PRESENT_FENCE);
4073 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
4074 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
4075 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04004076 // The HWC doesn't support present fences, so use the present timestamp instead.
4077 const nsecs_t presentTimestamp =
4078 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
4079
4080 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
4081 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
4082 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
4083
Patrick Williamsbb25f802022-08-30 23:02:34 +00004084 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
4085 refreshRate, renderRate, vote, gameMode);
4086 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
4087 mCurrentFrameNumber, actualPresentTime,
4088 FrameTracer::FrameEvent::PRESENT_FENCE);
4089 mFrameTracker.setActualPresentTime(actualPresentTime);
4090 }
4091 }
4092
4093 mFrameTracker.advanceFrame();
4094 mBufferInfo.mFrameLatencyNeeded = false;
4095}
4096
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004097bool Layer::willReleaseBufferOnLatch() const {
4098 return !mDrawingState.buffer && mBufferInfo.mBuffer;
4099}
4100
Patrick Williamsbb25f802022-08-30 23:02:34 +00004101bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00004102 const bool bgColorOnly = mDrawingState.bgColorLayer != nullptr;
4103 return latchBufferImpl(recomputeVisibleRegions, latchTime, bgColorOnly);
4104}
4105
4106bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004107 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
4108 getDrawingState().frameNumber);
4109
4110 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
4111
4112 if (refreshRequired) {
4113 return refreshRequired;
4114 }
4115
4116 // If the head buffer's acquire fence hasn't signaled yet, return and
4117 // try again later
4118 if (!fenceHasSignaled()) {
4119 ATRACE_NAME("!fenceHasSignaled()");
4120 mFlinger->onLayerUpdate();
4121 return false;
4122 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00004123 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00004124
4125 // Capture the old state of the layer for comparisons later
4126 BufferInfo oldBufferInfo = mBufferInfo;
4127 const bool oldOpacity = isOpaque(mDrawingState);
4128 mPreviousFrameNumber = mCurrentFrameNumber;
4129 mCurrentFrameNumber = mDrawingState.frameNumber;
4130 gatherBufferInfo();
4131
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004132 if (mBufferInfo.mBuffer) {
4133 // We latched a buffer that will be presented soon. Clear the previously presented layer
4134 // stack list.
4135 mPreviouslyPresentedLayerStacks.clear();
4136 }
4137
4138 if (mDrawingState.buffer == nullptr) {
4139 const bool bufferReleased = oldBufferInfo.mBuffer != nullptr;
4140 recomputeVisibleRegions = bufferReleased;
4141 return bufferReleased;
4142 }
4143
Patrick Williamsbb25f802022-08-30 23:02:34 +00004144 if (oldBufferInfo.mBuffer == nullptr) {
4145 // the first time we receive a buffer, we need to trigger a
4146 // geometry invalidation.
4147 recomputeVisibleRegions = true;
4148 }
4149
4150 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
4151 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
4152 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
4153 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
4154 recomputeVisibleRegions = true;
4155 }
4156
4157 if (oldBufferInfo.mBuffer != nullptr) {
4158 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
4159 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
4160 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
4161 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
4162 recomputeVisibleRegions = true;
4163 }
4164 }
4165
4166 if (oldOpacity != isOpaque(mDrawingState)) {
4167 recomputeVisibleRegions = true;
4168 }
4169
4170 return true;
4171}
4172
4173bool Layer::hasReadyFrame() const {
4174 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
4175}
4176
4177bool Layer::isProtected() const {
4178 return (mBufferInfo.mBuffer != nullptr) &&
4179 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
4180}
4181
Patrick Williamsbb25f802022-08-30 23:02:34 +00004182void Layer::latchAndReleaseBuffer() {
4183 if (hasReadyFrame()) {
4184 bool ignored = false;
4185 latchBuffer(ignored, systemTime());
4186 }
4187 releasePendingBuffer(systemTime());
4188}
4189
4190PixelFormat Layer::getPixelFormat() const {
4191 return mBufferInfo.mPixelFormat;
4192}
4193
4194bool Layer::getTransformToDisplayInverse() const {
4195 return mBufferInfo.mTransformToDisplayInverse;
4196}
4197
4198Rect Layer::getBufferCrop() const {
4199 // this is the crop rectangle that applies to the buffer
4200 // itself (as opposed to the window)
4201 if (!mBufferInfo.mCrop.isEmpty()) {
4202 // if the buffer crop is defined, we use that
4203 return mBufferInfo.mCrop;
4204 } else if (mBufferInfo.mBuffer != nullptr) {
4205 // otherwise we use the whole buffer
4206 return mBufferInfo.mBuffer->getBounds();
4207 } else {
4208 // if we don't have a buffer yet, we use an empty/invalid crop
4209 return Rect();
4210 }
4211}
4212
4213uint32_t Layer::getBufferTransform() const {
4214 return mBufferInfo.mTransform;
4215}
4216
4217ui::Dataspace Layer::getDataSpace() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004218 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
4219}
4220
4221ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
4222 ui::Dataspace updatedDataspace = dataspace;
4223 // translate legacy dataspaces to modern dataspaces
4224 switch (dataspace) {
Alec Mouri74c7ae12023-03-26 02:57:47 +00004225 // Treat unknown dataspaces as V0_sRGB
4226 case ui::Dataspace::UNKNOWN:
Patrick Williamsbb25f802022-08-30 23:02:34 +00004227 case ui::Dataspace::SRGB:
4228 updatedDataspace = ui::Dataspace::V0_SRGB;
4229 break;
4230 case ui::Dataspace::SRGB_LINEAR:
4231 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
4232 break;
4233 case ui::Dataspace::JFIF:
4234 updatedDataspace = ui::Dataspace::V0_JFIF;
4235 break;
4236 case ui::Dataspace::BT601_625:
4237 updatedDataspace = ui::Dataspace::V0_BT601_625;
4238 break;
4239 case ui::Dataspace::BT601_525:
4240 updatedDataspace = ui::Dataspace::V0_BT601_525;
4241 break;
4242 case ui::Dataspace::BT709:
4243 updatedDataspace = ui::Dataspace::V0_BT709;
4244 break;
4245 default:
4246 break;
4247 }
4248
4249 return updatedDataspace;
4250}
4251
4252sp<GraphicBuffer> Layer::getBuffer() const {
4253 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4254}
4255
Vishnu Nairb76d99a2023-03-19 18:22:31 -07004256void Layer::setTransformHintLegacy(ui::Transform::RotationFlags displayTransformHint) {
4257 mTransformHintLegacy = getFixedTransformHint();
4258 if (mTransformHintLegacy == ui::Transform::ROT_INVALID) {
4259 mTransformHintLegacy = displayTransformHint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004260 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07004261 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004262}
4263
4264const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4265 return mBufferInfo.mBuffer;
4266}
4267
4268bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00004269 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004270 return false;
4271 }
4272
4273 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00004274 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004275 mDrawingState.modified = true;
4276 setTransactionFlags(eTransactionNeeded);
4277 return true;
4278}
4279
4280bool Layer::fillsColor() const {
4281 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4282 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4283}
4284
4285bool Layer::hasBlur() const {
4286 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4287}
4288
Vishnu Nairba354102022-08-01 00:14:18 +00004289void Layer::updateSnapshot(bool updateGeometry) {
4290 if (!getCompositionEngineLayerFE()) {
4291 return;
4292 }
4293
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004294 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004295 if (updateGeometry) {
4296 prepareBasicGeometryCompositionState();
4297 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004298 snapshot->roundedCorner = getRoundedCornerState();
4299 snapshot->stretchEffect = getStretchEffect();
4300 snapshot->transformedBounds = mScreenBounds;
4301 if (mEffectiveShadowRadius > 0.f) {
4302 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4303
4304 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4305 // it if transparent regions are present. This may not be necessary since shadows are
4306 // typically cast by layers without transparent regions.
4307 snapshot->shadowSettings.boundaries = mBounds;
4308
4309 const float casterAlpha = snapshot->alpha;
4310 const bool casterIsOpaque =
4311 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4312
4313 // If the casting layer is translucent, we need to fill in the shadow underneath the
4314 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4315 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4316 snapshot->shadowSettings.ambientColor *= casterAlpha;
4317 snapshot->shadowSettings.spotColor *= casterAlpha;
4318 }
4319 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004320 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004321 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004322 snapshot->layerOpaqueFlagSet =
4323 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004324 sp<Layer> p = mDrawingParent.promote();
4325 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004326 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004327 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004328 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004329 }
4330 snapshot->bufferSize = getBufferSize(mDrawingState);
4331 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004332 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00004333 preparePerFrameCompositionState();
4334}
4335
Vishnu Naire14c6b32022-08-06 04:20:15 +00004336void Layer::updateChildrenSnapshots(bool updateGeometry) {
4337 for (const sp<Layer>& child : mDrawingChildren) {
4338 child->updateSnapshot(updateGeometry);
4339 child->updateChildrenSnapshots(updateGeometry);
4340 }
4341}
4342
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004343void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4344 mSnapshot->layerMetadata = parentMetadata;
4345 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4346 for (const sp<Layer>& child : mDrawingChildren) {
4347 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4348 }
4349}
4350
4351void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4352 std::unordered_set<Layer*>& visited) {
4353 if (visited.find(this) != visited.end()) {
4354 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4355 return;
4356 }
4357 visited.insert(this);
4358
4359 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4360
4361 if (mDrawingState.zOrderRelatives.empty()) {
4362 return;
4363 }
4364 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4365 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4366 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4367 sp<Layer> relative = weakRelative.promote();
4368 if (!relative) {
4369 continue;
4370 }
4371 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4372 }
4373}
4374
Chavi Weingarten328a8312023-01-26 21:17:52 +00004375bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00004376 TrustedPresentationListener const& listener) {
4377 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4378 mTrustedPresentationListener = listener;
4379 mTrustedPresentationThresholds = thresholds;
4380 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4381 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4382 mFlinger->mNumTrustedPresentationListeners++;
4383 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4384 mFlinger->mNumTrustedPresentationListeners--;
4385 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00004386
4387 // Reset trusted presentation states to ensure we start the time again.
4388 mEnteredTrustedPresentationStateTime = -1;
4389 mLastReportedTrustedPresentationState = false;
4390 mLastComputedTrustedPresentationState = false;
4391
4392 // If there's a new trusted presentation listener, the code needs to go through the composite
4393 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
4394 // we're already in the requested state.
4395 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00004396}
4397
Vishnu Naira156f482023-02-22 00:23:38 +00004398void Layer::updateLastLatchTime(nsecs_t latchTime) {
4399 mLastLatchTime = latchTime;
4400}
4401
Arthur Hungc70bee22023-06-02 01:35:52 +00004402void Layer::setIsSmallDirty() {
4403 if (!mFlinger->mScheduler->supportSmallDirtyDetection()) {
4404 return;
4405 }
4406
4407 if (mWindowType != WindowInfo::Type::APPLICATION &&
4408 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
4409 return;
4410 }
4411 Rect bounds = mDrawingState.surfaceDamageRegion.getBounds();
4412 if (!bounds.isValid()) {
4413 return;
4414 }
4415
4416 // If the damage region is a small dirty, this could give the hint for the layer history that
4417 // it could suppress the heuristic rate when calculating.
Tony Huang9ac5e6e2023-08-24 09:01:44 +00004418 mSmallDirty = mFlinger->mScheduler->isSmallDirtyArea(mOwnerUid,
4419 bounds.getWidth() * bounds.getHeight());
Arthur Hungc70bee22023-06-02 01:35:52 +00004420}
4421
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004422} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004423
4424#if defined(__gl_h_)
4425#error "don't include gl/gl.h in this file"
4426#endif
4427
4428#if defined(__gl2_h_)
4429#error "don't include gl2/gl2.h in this file"
4430#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004431
4432// TODO(b/129481165): remove the #pragma below and fix conversion issues
4433#pragma clang diagnostic pop // ignored "-Wconversion"