blob: 86c7d165e809cc68a3e18a88639f4bf25cab229b [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
Melody Hsue4ef87f2024-03-26 23:54:45 +000018
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080019#pragma clang diagnostic push
20#pragma clang diagnostic ignored "-Wconversion"
21
Dan Stoza9e56aa02015-11-02 13:00:03 -080022//#define LOG_NDEBUG 0
23#undef LOG_TAG
24#define LOG_TAG "Layer"
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080025#define ATRACE_TAG ATRACE_TAG_GRAPHICS
26
[1;3C2b9fc252021-02-04 16:16:50 -080027#include <android-base/properties.h>
Yiwei Zhang5434a782018-12-05 18:06:32 -080028#include <android-base/stringprintf.h>
Vishnu Nair0f085c62019-08-30 08:49:12 -070029#include <binder/IPCThreadState.h>
Vishnu Nairbe0ad902024-06-27 23:38:43 +000030#include <common/trace.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>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080042#include <gui/Surface.h>
Alec Mourie60041e2019-06-14 18:59:51 -070043#include <math.h>
chaviw250bcbb2020-08-05 11:17:54 -070044#include <private/android_filesystem_config.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080045#include <renderengine/RenderEngine.h>
Alec Mourie60041e2019-06-14 18:59:51 -070046#include <stdint.h>
47#include <stdlib.h>
48#include <sys/types.h>
Alec Mouridda07d92022-04-25 22:39:25 +000049#include <system/graphics-base-v1.0.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080050#include <ui/DebugUtils.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000051#include <ui/FloatRect.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080052#include <ui/GraphicBuffer.h>
Sally Qif6918d42023-08-07 15:28:30 -070053#include <ui/HdrRenderTypeUtils.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080054#include <ui/PixelFormat.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000055#include <ui/Rect.h>
56#include <ui/Transform.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080057#include <utils/Errors.h>
58#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080059#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060#include <utils/StopWatch.h>
61
Alec Mourie60041e2019-06-14 18:59:51 -070062#include <algorithm>
63#include <mutex>
Vishnu Nair71fcf912022-10-18 09:14:20 -070064#include <optional>
Alec Mourie60041e2019-06-14 18:59:51 -070065#include <sstream>
66
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070067#include "DisplayDevice.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080068#include "DisplayHardware/HWComposer.h"
Ady Abraham22c7b5c2020-09-22 19:33:40 -070069#include "FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -070070#include "FrameTracer/FrameTracer.h"
Vishnu Naircb8be502022-10-12 19:03:23 +000071#include "FrontEnd/LayerCreationArgs.h"
Vishnu Nair07e2a482022-10-18 19:18:16 +000072#include "FrontEnd/LayerHandle.h"
Melody Hsue4ef87f2024-03-26 23:54:45 +000073#include "Layer.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080074#include "LayerProtoHelper.h"
Josh Gao194ff392022-09-08 16:19:29 -070075#include "MutexUtils.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include "SurfaceFlinger.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080077#include "TimeStats/TimeStats.h"
Melody Hsue4ef87f2024-03-26 23:54:45 +000078#include "TransactionCallbackInvoker.h"
Robert Carr3e2a2992021-06-11 13:42:55 -070079#include "TunnelModeEnabledReporter.h"
Alec Mouri9892aac2023-12-11 21:16:59 +000080#include "Utils/FenceUtils.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 {
Alec Mouri9892aac2023-12-11 21:16:59 +000086using namespace std::chrono_literals;
Marin Shalamanov1876e2e2020-12-04 13:23:59 +010087namespace {
88constexpr int kDumpTableRowLength = 159;
Patrick Williamsbb25f802022-08-30 23:02:34 +000089
Prabir Pradhanda0f62c2022-07-22 19:53:04 +000090const ui::Transform kIdentityTransform;
Patrick Williamsbb25f802022-08-30 23:02:34 +000091
Linnan Li13bf76a2024-05-05 19:18:02 +080092ui::LogicalDisplayId toLogicalDisplayId(const ui::LayerStack& layerStack) {
93 return ui::LogicalDisplayId{static_cast<int32_t>(layerStack.id)};
94}
95
Patrick Williamsbb25f802022-08-30 23:02:34 +000096bool assignTransform(ui::Transform* dst, ui::Transform& from) {
97 if (*dst == from) {
98 return false;
99 }
100 *dst = from;
101 return true;
102}
103
104TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
105 using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
106 using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
107 const auto frameRateCompatibility = [frameRate] {
Rachel Leece6e0042023-06-27 11:22:54 -0700108 switch (frameRate.vote.type) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000109 case Layer::FrameRateCompatibility::Default:
110 return FrameRateCompatibility::Default;
111 case Layer::FrameRateCompatibility::ExactOrMultiple:
112 return FrameRateCompatibility::ExactOrMultiple;
113 default:
114 return FrameRateCompatibility::Undefined;
115 }
116 }();
117
118 const auto seamlessness = [frameRate] {
Rachel Leece6e0042023-06-27 11:22:54 -0700119 switch (frameRate.vote.seamlessness) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000120 case scheduler::Seamlessness::OnlySeamless:
121 return Seamlessness::ShouldBeSeamless;
122 case scheduler::Seamlessness::SeamedAndSeamless:
123 return Seamlessness::NotRequired;
124 default:
125 return Seamlessness::Undefined;
126 }
127 }();
128
Rachel Leece6e0042023-06-27 11:22:54 -0700129 return TimeStats::SetFrameRateVote{.frameRate = frameRate.vote.rate.getValue(),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000130 .frameRateCompatibility = frameRateCompatibility,
131 .seamlessness = seamlessness};
132}
133
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100134} // namespace
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800135
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700136using namespace ftl::flag_operators;
137
Yiwei Zhang5434a782018-12-05 18:06:32 -0800138using base::StringAppendF;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000139using frontend::LayerSnapshot;
140using frontend::RoundedCornerState;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800141using gui::GameMode;
142using gui::LayerMetadata;
chaviw3277faf2021-05-19 16:45:23 -0500143using gui::WindowInfo;
Vishnu Nair494a2e42023-11-10 17:21:19 -0800144using ui::Size;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800145
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700146using PresentState = frametimeline::SurfaceFrame::PresentState;
147
Kean Mariotti4ba343c2023-04-19 13:31:02 +0000148Layer::Layer(const surfaceflinger::LayerCreationArgs& args)
Vishnu Naircb8be502022-10-12 19:03:23 +0000149 : sequence(args.sequence),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700150 mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
Arthur Hung23e07502021-10-15 11:58:19 +0000151 mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
Ady Abraham8f1ee7f2019-04-05 10:32:50 -0700152 mClientRef(args.client),
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800153 mWindowType(static_cast<WindowInfo::Type>(
154 args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))),
Tianhao Yao67dd7122022-02-22 17:48:33 +0000155 mLayerCreationFlags(args.flags),
Lloyd Pique70ddc672024-04-30 18:20:40 -0700156 mLegacyLayerFE(args.flinger->getFactory().createLayerFE(mName, this)) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000157 ALOGV("Creating Layer %s", getDebugName());
158
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700159 uint32_t layerFlags = 0;
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700160 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
161 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
162 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
chaviwc5676c62020-09-18 15:01:04 -0700163 if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
164 layerFlags |= layer_state_t::eLayerSkipScreenshot;
Robert Carr6a160312021-05-17 12:08:20 -0700165 mDrawingState.flags = layerFlags;
Robert Carr6a160312021-05-17 12:08:20 -0700166 mDrawingState.crop.makeInvalid();
Robert Carr6a160312021-05-17 12:08:20 -0700167 mDrawingState.z = 0;
168 mDrawingState.color.a = 1.0f;
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700169 mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
Robert Carr6a160312021-05-17 12:08:20 -0700170 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700171 mDrawingState.transform.set(0, 0);
172 mDrawingState.frameNumber = 0;
Alec Mouri21d94322023-10-17 19:51:39 +0000173 mDrawingState.previousFrameNumber = 0;
Vishnu Nair63221212023-04-06 15:17:37 -0700174 mDrawingState.barrierFrameNumber = 0;
175 mDrawingState.producerId = 0;
176 mDrawingState.barrierProducerId = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700177 mDrawingState.bufferTransform = 0;
178 mDrawingState.transformToDisplayInverse = false;
Robert Carr6a160312021-05-17 12:08:20 -0700179 mDrawingState.acquireFence = sp<Fence>::make(-1);
180 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
Alec Mouri74c7ae12023-03-26 02:57:47 +0000181 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Robert Carr6a160312021-05-17 12:08:20 -0700182 mDrawingState.hdrMetadata.validTypes = 0;
183 mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
184 mDrawingState.cornerRadius = 0.0f;
185 mDrawingState.backgroundBlurRadius = 0;
186 mDrawingState.api = -1;
187 mDrawingState.hasColorTransform = false;
188 mDrawingState.colorSpaceAgnostic = false;
189 mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
190 mDrawingState.metadata = args.metadata;
191 mDrawingState.shadowRadius = 0.f;
192 mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
193 mDrawingState.frameTimelineInfo = {};
194 mDrawingState.postTime = -1;
195 mDrawingState.destinationFrame.makeInvalid();
Robin Leeedb375d2021-09-10 12:03:42 +0000196 mDrawingState.isTrustedOverlay = false;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -0700197 mDrawingState.dropInputMode = gui::DropInputMode::NONE;
Sally Qi81d95e62022-03-21 19:41:33 -0700198 mDrawingState.dimmingEnabled = true;
Andy Labrada096227e2022-06-15 16:58:11 +0000199 mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
Rachel Lee70f7b692023-11-22 11:24:02 -0800200 mDrawingState.frameRateSelectionStrategy = FrameRateSelectionStrategy::Propagate;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700201
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700202 if (args.flags & ISurfaceComposerClient::eNoColorFill) {
203 // Set an invalid color so there is no color fill.
Robert Carr6a160312021-05-17 12:08:20 -0700204 mDrawingState.color.r = -1.0_hf;
205 mDrawingState.color.g = -1.0_hf;
206 mDrawingState.color.b = -1.0_hf;
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700207 }
Dominik Laskowski4376bd82022-07-07 11:50:20 -0700208
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500209 mFrameTracker.setDisplayRefreshPeriod(
210 args.flinger->mScheduler->getPacesetterVsyncPeriod().ns());
Robert Carr2e102c92018-10-23 12:11:15 -0700211
Vishnu Naircb8be502022-10-12 19:03:23 +0000212 mOwnerUid = args.ownerUid;
213 mOwnerPid = args.ownerPid;
Tony Huangf3621102023-09-04 17:14:22 +0800214 mOwnerAppId = mOwnerUid % PER_USER_RANGE;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000215
216 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
217 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
218 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000219
220 mSnapshot->sequence = sequence;
221 mSnapshot->name = getDebugName();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000222 mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000223 mSnapshot->parentTransform = {};
Dominik Laskowski75848362019-11-11 17:57:20 -0800224}
225
226void Layer::onFirstRef() {
227 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700228}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700229
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700230Layer::~Layer() {
Patrick Williams70093fd2022-12-12 16:51:52 +0000231 LOG_ALWAYS_FATAL_IF(std::this_thread::get_id() != mFlinger->mMainThreadId,
232 "Layer destructor called off the main thread.");
233
Patrick Williamsbb25f802022-08-30 23:02:34 +0000234 // The original layer and the clone layer share the same texture and buffer. Therefore, only
235 // one of the layers, in this case the original layer, needs to handle the deletion. The
236 // original layer and the clone should be removed at the same time so there shouldn't be any
237 // issue with the clone layer trying to use the texture.
238 if (mBufferInfo.mBuffer != nullptr) {
239 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
240 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
liulijuneb489f62022-10-17 22:02:14 +0800241 mBufferInfo.mFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000242 }
Patrick Williamsbb25f802022-08-30 23:02:34 +0000243 const int32_t layerId = getSequence();
244 mFlinger->mTimeStats->onDestroy(layerId);
245 mFlinger->mFrameTracer->onDestroy(layerId);
246
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000247 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700248 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700249
250 if (mDrawingState.sidebandStream != nullptr) {
251 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
252 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700253 if (mHadClonedChild) {
Vishnu Nair3be61902023-04-26 19:47:29 -0700254 auto& roots = mFlinger->mLayerMirrorRoots;
255 roots.erase(std::remove(roots.begin(), roots.end(), this), roots.end());
Robert Carr6a0382d2021-07-01 15:57:17 -0700256 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000257 if (hasTrustedPresentationListener()) {
258 mFlinger->mNumTrustedPresentationListeners--;
Vishnu Nair781d7252023-01-30 18:16:01 +0000259 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Chavi Weingarten076acac2023-01-19 17:20:43 +0000260 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700261}
262
Mathias Agopian13127d82013-03-05 17:47:11 -0800263// ---------------------------------------------------------------------------
264// callbacks
265// ---------------------------------------------------------------------------
266
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700267void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700268 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700269 return;
270 }
Robert Carr2e102c92018-10-23 12:11:15 -0700271
Robert Carr6a160312021-05-17 12:08:20 -0700272 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700273 if (strongRelative == nullptr) {
274 setZOrderRelativeOf(nullptr);
275 return;
276 }
277
278 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700279 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700280 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800281 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700282 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700283}
284
285void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700286 if (!mRemovedFromDrawingState) {
287 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700288 mFlinger->mScheduler->deregisterLayer(this);
289 }
Vishnu Nair781d7252023-01-30 18:16:01 +0000290 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Rob Carr4bba3702018-10-08 21:53:30 +0000291
Ady Abrahamd11bade2022-08-01 16:18:03 -0700292 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700293}
Chia-I Wu38512252017-05-17 14:36:16 -0700294
chaviw68d4dab2020-06-08 15:07:32 -0700295sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000296 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700297 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700298 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700299 }
300 return parent->getRootLayer();
301}
302
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700303void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700304 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
305 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700306 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700307
Josh Gao194ff392022-09-08 16:19:29 -0700308 REQUIRE_MUTEX(mFlinger->mStateLock);
309 traverse(LayerVector::StateSet::Current,
310 [&](Layer* layer) REQUIRES(layer->mFlinger->mStateLock) {
311 layer->removeFromCurrentState();
312 layer->removeRelativeZ(layersInTree);
313 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700314}
315
chaviw61626f22018-11-15 16:26:27 -0800316void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700317 if (mRemovedFromDrawingState) {
318 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700319 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700320 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700321 }
chaviw61626f22018-11-15 16:26:27 -0800322
323 for (const auto& child : mCurrentChildren) {
324 child->addToCurrentState();
325 }
326}
327
Mathias Agopian13127d82013-03-05 17:47:11 -0800328// ---------------------------------------------------------------------------
329// set-up
330// ---------------------------------------------------------------------------
331
chaviw13fdc492017-06-27 12:40:18 -0700332bool Layer::getPremultipledAlpha() const {
333 return mPremultipliedAlpha;
334}
335
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700336sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800337 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700338 if (mGetHandleCalled) {
339 ALOGE("Get handle called twice" );
340 return nullptr;
341 }
342 mGetHandleCalled = true;
Vishnu Nair787aa782023-03-17 13:46:46 -0700343 mHandleAlive = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000344 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800345}
346
347// ---------------------------------------------------------------------------
348// h/w composer set-up
349// ---------------------------------------------------------------------------
350
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700351static Rect reduce(const Rect& win, const Region& exclude) {
352 if (CC_LIKELY(exclude.isEmpty())) {
353 return win;
354 }
355 if (exclude.isRect()) {
356 return win.reduce(exclude.getBounds());
357 }
358 return Region(win).subtract(exclude).getBounds();
359}
360
Dan Stoza80d61162017-12-20 15:57:52 -0800361static FloatRect reduce(const FloatRect& win, const Region& exclude) {
362 if (CC_LIKELY(exclude.isEmpty())) {
363 return win;
364 }
365 // Convert through Rect (by rounding) for lack of FloatRegion
366 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
367}
368
Vishnu Nair4351ad52019-02-11 14:13:02 -0800369Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800370 if (!reduceTransparentRegion) {
371 return Rect{mScreenBounds};
372 }
373
374 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800375 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800376 // Transform to screen space.
377 bounds = t.transform(bounds);
378 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700379}
380
Vishnu Nair4351ad52019-02-11 14:13:02 -0800381FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000382 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800383 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700384}
385
Vishnu Nairf0c28512019-02-08 12:40:28 -0800386FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
387 // Subtract the transparent region and snap to the bounds.
388 return reduce(mBounds, activeTransparentRegion);
389}
390
Chavi Weingarten076acac2023-01-19 17:20:43 +0000391// No early returns.
Vishnu Nair781d7252023-01-30 18:16:01 +0000392void Layer::updateTrustedPresentationState(const DisplayDevice* display,
393 const frontend::LayerSnapshot* snapshot,
394 int64_t time_in_ms, bool leaveState) {
Chavi Weingarten076acac2023-01-19 17:20:43 +0000395 if (!hasTrustedPresentationListener()) {
396 return;
397 }
398 const bool lastState = mLastComputedTrustedPresentationState;
399 mLastComputedTrustedPresentationState = false;
400
401 if (!leaveState) {
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000402 const auto outputLayer = findOutputLayerForDisplay(display, snapshot->path);
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000403 if (outputLayer != nullptr) {
404 if (outputLayer->getState().coveredRegionExcludingDisplayOverlays) {
405 Region coveredRegion =
406 *outputLayer->getState().coveredRegionExcludingDisplayOverlays;
407 mLastComputedTrustedPresentationState =
408 computeTrustedPresentationState(snapshot->geomLayerBounds,
409 snapshot->sourceBounds(), coveredRegion,
410 snapshot->transformedBounds,
411 snapshot->alpha,
412 snapshot->geomLayerTransform,
413 mTrustedPresentationThresholds);
414 } else {
415 ALOGE("CoveredRegionExcludingDisplayOverlays was not set for %s. Don't compute "
416 "TrustedPresentationState",
417 getDebugName());
418 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000419 }
420 }
421 const bool newState = mLastComputedTrustedPresentationState;
422 if (lastState && !newState) {
423 // We were in the trusted presentation state, but now we left it,
424 // emit the callback if needed
425 if (mLastReportedTrustedPresentationState) {
426 mLastReportedTrustedPresentationState = false;
427 mTrustedPresentationListener.invoke(false);
428 }
429 // Reset the timer
430 mEnteredTrustedPresentationStateTime = -1;
431 } else if (!lastState && newState) {
432 // We were not in the trusted presentation state, but we entered it, begin the timer
433 // and make sure this gets called at least once more!
434 mEnteredTrustedPresentationStateTime = time_in_ms;
435 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
436 }
437
438 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
439 if (!mLastReportedTrustedPresentationState && newState &&
440 (time_in_ms - mEnteredTrustedPresentationStateTime >
441 mTrustedPresentationThresholds.stabilityRequirementMs)) {
442 mLastReportedTrustedPresentationState = true;
443 mTrustedPresentationListener.invoke(true);
444 }
445}
446
447/**
448 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
449 * of how the parameters and thresholds are interpreted. The general spirit is
450 * to produce an upper bound on the amount of the buffer which was presented.
451 */
452bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
453 const Region& coveredRegion,
454 const FloatRect& screenBounds, float alpha,
455 const ui::Transform& effectiveTransform,
456 const TrustedPresentationThresholds& thresholds) {
457 if (alpha < thresholds.minAlpha) {
458 return false;
459 }
460 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
461 return false;
462 }
463 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
464 return false;
465 }
466
467 const float sx = effectiveTransform.dsdx();
468 const float sy = effectiveTransform.dsdy();
469 float fractionRendered = std::min(sx * sy, 1.0f);
470
471 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
472 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
473 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
474
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000475 Region tJunctionFreeRegion = Region::createTJunctionFreeRegion(coveredRegion);
476 // Compute the size of all the rects since they may be disconnected.
477 float coveredSize = 0;
478 for (auto rect = tJunctionFreeRegion.begin(); rect < tJunctionFreeRegion.end(); rect++) {
479 float size = rect->width() * rect->height();
480 coveredSize += size;
481 }
482
483 fractionRendered *= (1 - (coveredSize / (screenBounds.getWidth() * screenBounds.getHeight())));
Chavi Weingarten076acac2023-01-19 17:20:43 +0000484
485 if (fractionRendered < thresholds.minFractionRendered) {
486 return false;
487 }
488
489 return true;
490}
491
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700492void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
493 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800494 const State& s(getDrawingState());
495
496 // Calculate effective layer transform
497 mEffectiveTransform = parentTransform * getActiveTransform(s);
498
Garfield Tan2c1782c2022-02-16 15:25:05 -0800499 if (CC_UNLIKELY(!isTransformValid())) {
500 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
501 getDebugName());
502 return;
503 }
504
Vishnu Nair4351ad52019-02-11 14:13:02 -0800505 // Transform parent bounds to layer space
506 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
507
Vishnu Nairc652ff82019-03-15 12:48:54 -0700508 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800509 mSourceBounds = computeSourceBounds(parentBounds);
510
511 // Calculate bounds by croping diplay frame with layer crop and parent bounds
512 FloatRect bounds = mSourceBounds;
513 const Rect layerCrop = getCrop(s);
514 if (!layerCrop.isEmpty()) {
515 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
516 }
517 bounds = bounds.intersect(parentBounds);
518
519 mBounds = bounds;
520 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700521
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700522 // Use the layer's own shadow radius if set. Otherwise get the radius from
523 // parent.
524 if (s.shadowRadius > 0.f) {
525 mEffectiveShadowRadius = s.shadowRadius;
526 } else {
527 mEffectiveShadowRadius = parentShadowRadius;
528 }
529
530 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
531 // don't pass it to its children.
532 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
533
Vishnu Nair4351ad52019-02-11 14:13:02 -0800534 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700535 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800536 }
Vishnu Nairba354102022-08-01 00:14:18 +0000537
538 if (mPotentialCursor) {
539 prepareCursorCompositionState();
540 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800541}
542
Vishnu Nair60356342018-11-13 13:00:45 -0800543Rect Layer::getCroppedBufferSize(const State& s) const {
544 Rect size = getBufferSize(s);
545 Rect crop = getCrop(s);
546 if (!crop.isEmpty() && size.isValid()) {
547 size.intersect(crop, &size);
548 } else if (!crop.isEmpty()) {
549 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700550 }
Vishnu Nair60356342018-11-13 13:00:45 -0800551 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800552}
553
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700554void Layer::setupRoundedCornersCropCoordinates(Rect win,
555 const FloatRect& roundedCornersCrop) const {
556 // Translate win by the rounded corners rect coordinates, to have all values in
557 // layer coordinate space.
558 win.left -= roundedCornersCrop.left;
559 win.right -= roundedCornersCrop.left;
560 win.top -= roundedCornersCrop.top;
561 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700562}
563
Lloyd Piquede196652020-01-22 17:29:58 -0800564void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800565 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800566 const auto alpha = static_cast<float>(getAlpha());
567 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700568 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800569
570 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
571 if (!opaque || alpha != 1.0f) {
572 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
573 : Hwc2::IComposerClient::BlendMode::COVERAGE;
574 }
575
Alec Mourif4af03e2023-02-11 00:25:24 +0000576 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000577 auto* snapshot = editLayerSnapshot();
578 snapshot->outputFilter = getOutputFilter();
579 snapshot->isVisible = isVisible();
580 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
Vishnu Naird9e4f462023-10-06 04:05:45 +0000581 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800582
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000583 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800584 contentDirty = false;
585
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000586 snapshot->geomLayerBounds = mBounds;
587 snapshot->geomLayerTransform = getTransform();
588 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
589 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000590 snapshot->localTransform = getActiveTransform(drawingState);
591 snapshot->localTransformInverse = snapshot->localTransform.inverse();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000592 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
593 snapshot->alpha = alpha;
Vishnu Nairc6384702023-07-31 12:22:20 -0700594 snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
595 snapshot->blurRegions = getBlurRegions();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000596 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800597}
598
Lloyd Piquede196652020-01-22 17:29:58 -0800599void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800600 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000601 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700602
Alec Mourif4af03e2023-02-11 00:25:24 +0000603 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000604 snapshot->geomBufferSize = getBufferSize(drawingState);
605 snapshot->geomContentCrop = getBufferCrop();
606 snapshot->geomCrop = getCrop(drawingState);
607 snapshot->geomBufferTransform = getBufferTransform();
608 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
609 snapshot->geomUsesSourceCrop = usesSourceCrop();
610 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800611
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000612 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800613 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
614 for (const auto& [key, mandatory] : supportedMetadata) {
615 const auto& genericLayerMetadataCompatibilityMap =
616 mFlinger->getGenericLayerMetadataKeyMap();
617 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
618 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
619 continue;
620 }
621 const uint32_t id = compatIter->second;
622
623 auto it = drawingState.metadata.mMap.find(id);
624 if (it == std::end(drawingState.metadata.mMap)) {
625 continue;
626 }
627
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000628 snapshot->metadata.emplace(key,
629 compositionengine::GenericLayerMetadataEntry{mandatory,
630 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800631 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800632}
David Sodmanba340492018-08-05 21:51:33 -0700633
Lloyd Piquede196652020-01-22 17:29:58 -0800634void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800635 const auto& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000636 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000637 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800638
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000639 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800640
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000641 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
642 snapshot->dataspace = getDataSpace();
643 snapshot->colorTransform = getColorTransform();
644 snapshot->colorTransformIsIdentity = !hasColorTransform();
645 snapshot->surfaceDamage = surfaceDamageRegion;
646 snapshot->hasProtectedContent = isProtected();
647 snapshot->dimmingEnabled = isDimmingEnabled();
Sally Qi963049b2023-03-23 14:06:21 -0700648 snapshot->currentHdrSdrRatio = getCurrentHdrSdrRatio();
649 snapshot->desiredHdrSdrRatio = getDesiredHdrSdrRatio();
Alec Mourif4af03e2023-02-11 00:25:24 +0000650 snapshot->cachingHint = getCachingHint();
Lloyd Pique688abd42019-02-15 15:42:24 -0800651
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700652 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700653
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000654 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800655
656 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400657 // Rounded corners no longer force client composition, since we may use a
658 // hole punch so that the layer will appear to have rounded corners.
Alec Mouri994761f2023-08-04 21:50:55 +0000659 if (drawShadows() || snapshot->stretchEffect.hasEffect()) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000660 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800661 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700662 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairc6384702023-07-31 12:22:20 -0700663 snapshot->blurRegions = getBlurRegions();
664 snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400665
666 // Layer framerate is used in caching decisions.
667 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
668 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000669 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000670
671 if (hasBufferOrSidebandStream()) {
672 preparePerFrameBufferCompositionState();
673 } else {
674 preparePerFrameEffectsCompositionState();
675 }
676}
677
678void Layer::preparePerFrameBufferCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000679 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000680 auto* snapshot = editLayerSnapshot();
Alec Mourif4af03e2023-02-11 00:25:24 +0000681 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000682 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
683 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000684 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
685 return;
686 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000687 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000688 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
ramindanib2158ee2023-02-13 20:29:59 -0800689 } else if ((mDrawingState.flags & layer_state_t::eLayerIsRefreshRateIndicator) != 0) {
690 snapshot->compositionType =
691 aidl::android::hardware::graphics::composer3::Composition::REFRESH_RATE_INDICATOR;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000692 } else {
693 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000694 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
695 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000696 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
697 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
698 }
699
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000700 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000701 snapshot->acquireFence = mBufferInfo.mFence;
702 snapshot->frameNumber = mBufferInfo.mFrameNumber;
703 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000704}
705
706void Layer::preparePerFrameEffectsCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000707 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000708 auto* snapshot = editLayerSnapshot();
709 snapshot->color = getColor();
710 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000711 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800712}
713
Lloyd Piquede196652020-01-22 17:29:58 -0800714void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800715 const State& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000716 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000717 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800718
719 // Apply the layer's transform, followed by the display's global transform
720 // Here we're guaranteed that the layer's transform preserves rects
721 Rect win = getCroppedBufferSize(drawingState);
722 // Subtract the transparent region and snap to the bounds
723 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
724 Rect frame(getTransform().transform(bounds));
725
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000726 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800727}
728
Lloyd Piquea83776c2019-01-29 18:42:32 -0800729const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700730 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800731}
732
Mathias Agopian13127d82013-03-05 17:47:11 -0800733// ---------------------------------------------------------------------------
734// drawing...
735// ---------------------------------------------------------------------------
736
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500737aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
738 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700739 const auto outputLayer = findOutputLayerForDisplay(&display);
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000740 return getCompositionType(outputLayer);
741}
742
743aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
744 const compositionengine::OutputLayer* outputLayer) const {
Alec Mouri6b9e9912020-01-21 10:50:24 -0800745 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500746 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800747 }
748 if (outputLayer->getState().hwc) {
749 return (*outputLayer->getState().hwc).hwcCompositionType;
750 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500751 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800752 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800753}
754
Mathias Agopian13127d82013-03-05 17:47:11 -0800755// ----------------------------------------------------------------------------
756// local state
757// ----------------------------------------------------------------------------
758
David Sodman41fdfc92017-11-06 16:09:56 -0800759bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800760 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700761 if (s.flags & layer_state_t::eLayerSecure) {
762 return true;
763 }
764
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000765 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700766 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700767}
768
Mathias Agopian13127d82013-03-05 17:47:11 -0800769// ----------------------------------------------------------------------------
770// transaction
771// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800772
Vishnu Naira156f482023-02-22 00:23:38 +0000773uint32_t Layer::doTransaction(uint32_t flags) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000774 SFTRACE_CALL();
Marissa Wall61c58622018-07-18 10:12:20 -0700775
Robert Carr0758e5d2021-03-11 22:15:04 -0800776 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700777 mDrawingStateModified = mDrawingState.modified;
778 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700779
Alec Mourib416efd2018-09-06 21:01:59 +0000780 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700781
Robert Carr6a160312021-05-17 12:08:20 -0700782 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800783 // invalidate and recompute the visible regions if needed
784 flags |= Layer::eVisibleRegion;
785 }
786
Robert Carr6a160312021-05-17 12:08:20 -0700787 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800788 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000789 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800790 flags |= eVisibleRegion;
791 this->contentDirty = true;
792
793 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700794 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800795 }
796
Arthur Hung9ed43392022-05-27 06:31:57 +0000797 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
798 mFlinger->mUpdateInputInfo = true;
799 }
800
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700801 commitTransaction();
Robert Carra1257842020-01-31 13:48:28 -0800802
Mathias Agopian13127d82013-03-05 17:47:11 -0800803 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800804}
805
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700806void Layer::commitTransaction() {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000807 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
808 // bufferSurfaceFrameTX will be presented in latchBuffer.
809 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
810 if (surfaceFrame->getPresentState() != PresentState::Presented) {
811 // With applyPendingStates, we could end up having presented surfaceframes from previous
812 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800813 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000814 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
815 }
816 }
Robert Carr6a160312021-05-17 12:08:20 -0700817 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700818}
819
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700820uint32_t Layer::clearTransactionFlags(uint32_t mask) {
821 const auto flags = mTransactionFlags & mask;
822 mTransactionFlags &= ~mask;
823 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800824}
825
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700826void Layer::setTransactionFlags(uint32_t mask) {
827 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800828}
829
Robert Carr1f0a16a2016-10-24 16:27:39 -0700830bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
831 ssize_t idx = mCurrentChildren.indexOf(childLayer);
832 if (idx < 0) {
833 return false;
834 }
835 if (childLayer->setLayer(z)) {
836 mCurrentChildren.removeAt(idx);
837 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800838 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700839 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800840 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700841}
842
Robert Carr503c7042017-09-27 15:06:08 -0700843bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
844 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
845 ssize_t idx = mCurrentChildren.indexOf(childLayer);
846 if (idx < 0) {
847 return false;
848 }
849 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
850 mCurrentChildren.removeAt(idx);
851 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800852 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700853 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800854 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700855}
856
Robert Carrae060832016-11-28 10:51:00 -0800857bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700858 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
859 mDrawingState.sequence++;
860 mDrawingState.z = z;
861 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700862
Robert Carra70e91c2021-06-11 13:59:52 -0700863 mFlinger->mSomeChildrenChanged = true;
864
Robert Carrdb66e622017-04-10 16:55:57 -0700865 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700866 if (mDrawingState.zOrderRelativeOf != nullptr) {
867 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700868 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700869 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700870 }
chaviw606e5cf2019-03-01 10:12:10 -0800871 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700872 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800873 setTransactionFlags(eTransactionNeeded);
874 return true;
875}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700876
Robert Carrdb66e622017-04-10 16:55:57 -0700877void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700878 mDrawingState.zOrderRelatives.remove(relative);
879 mDrawingState.sequence++;
880 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700881 setTransactionFlags(eTransactionNeeded);
882}
883
884void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700885 mDrawingState.zOrderRelatives.add(relative);
886 mDrawingState.modified = true;
887 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700888 setTransactionFlags(eTransactionNeeded);
889}
890
chaviw606e5cf2019-03-01 10:12:10 -0800891void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700892 mDrawingState.zOrderRelativeOf = relativeOf;
893 mDrawingState.sequence++;
894 mDrawingState.modified = true;
895 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700896
chaviw606e5cf2019-03-01 10:12:10 -0800897 setTransactionFlags(eTransactionNeeded);
898}
899
Robert Carr503d2bd2017-12-04 15:49:47 -0800900bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000901 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700902 if (relative == nullptr) {
903 return false;
904 }
905
Robert Carr6a160312021-05-17 12:08:20 -0700906 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
907 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800908 return false;
909 }
910
Robert Carr88b85e12022-03-21 15:47:35 -0700911 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
912 (relative->mDrawingState.zOrderRelativeOf == this)) {
913 ALOGE("Detected relative layer loop between %s and %s",
914 mName.c_str(), relative->mName.c_str());
915 ALOGE("Ignoring new call to set relative layer");
916 return false;
917 }
918
Robert Carra70e91c2021-06-11 13:59:52 -0700919 mFlinger->mSomeChildrenChanged = true;
920
Robert Carr6a160312021-05-17 12:08:20 -0700921 mDrawingState.sequence++;
922 mDrawingState.modified = true;
923 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700924
Robert Carr6a160312021-05-17 12:08:20 -0700925 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700926 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700927 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700928 }
chaviw606e5cf2019-03-01 10:12:10 -0800929 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700930 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700931
932 setTransactionFlags(eTransactionNeeded);
933
934 return true;
935}
936
Winson Chunga30f7c92021-06-29 15:42:56 -0700937bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
938 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
939 mDrawingState.isTrustedOverlay = isTrustedOverlay;
940 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000941 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700942 setTransactionFlags(eTransactionNeeded);
943 return true;
944}
945
946bool Layer::isTrustedOverlay() const {
947 if (getDrawingState().isTrustedOverlay) {
948 return true;
949 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000950 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700951 return (p != nullptr) && p->isTrustedOverlay();
952}
953
Dan Stoza9e56aa02015-11-02 13:00:03 -0800954bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700955 if (mDrawingState.color.a == alpha) return false;
956 mDrawingState.sequence++;
957 mDrawingState.color.a = alpha;
958 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800959 setTransactionFlags(eTransactionNeeded);
960 return true;
961}
chaviw13fdc492017-06-27 12:40:18 -0700962
Valerie Haudd0b7572019-01-29 14:59:27 -0800963bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700964 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700965 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800966 }
Robert Carr6a160312021-05-17 12:08:20 -0700967 mDrawingState.sequence++;
968 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -0800969 setTransactionFlags(eTransactionNeeded);
970
Robert Carr6a160312021-05-17 12:08:20 -0700971 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -0800972 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -0800973 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700974 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -0700975 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Kean Mariotti4ba343c2023-04-19 13:31:02 +0000976 surfaceflinger::LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
977 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -0700978
Valerie Haudd0b7572019-01-29 14:59:27 -0800979 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -0700980 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -0800981 mFlinger->mLayersAdded = true;
982 // set up SF to handle added color layer
983 if (isRemovedFromCurrentState()) {
Josh Gao194ff392022-09-08 16:19:29 -0700984 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -0700985 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -0800986 }
987 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -0700988 } else if (mDrawingState.bgColorLayer && alpha == 0) {
Josh Gao194ff392022-09-08 16:19:29 -0700989 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -0700990 mDrawingState.bgColorLayer->reparent(nullptr);
991 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -0800992 return true;
993 }
994
Robert Carr6a160312021-05-17 12:08:20 -0700995 mDrawingState.bgColorLayer->setColor(color);
996 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
997 mDrawingState.bgColorLayer->setAlpha(alpha);
998 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -0800999
chaviw13fdc492017-06-27 12:40:18 -07001000 return true;
1001}
1002
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001003bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001004 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001005
Robert Carr6a160312021-05-17 12:08:20 -07001006 mDrawingState.sequence++;
1007 mDrawingState.cornerRadius = cornerRadius;
1008 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001009 setTransactionFlags(eTransactionNeeded);
1010 return true;
1011}
1012
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001013bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001014 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001015 // If we start or stop drawing blur then the layer's visibility state may change so increment
1016 // the magic sequence number.
1017 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1018 mDrawingState.sequence++;
1019 }
Robert Carr6a160312021-05-17 12:08:20 -07001020 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1021 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001022 setTransactionFlags(eTransactionNeeded);
1023 return true;
1024}
Marissa Wall61c58622018-07-18 10:12:20 -07001025
Mathias Agopian13127d82013-03-05 17:47:11 -08001026bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001027 mDrawingState.sequence++;
1028 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001029 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001030 setTransactionFlags(eTransactionNeeded);
1031 return true;
1032}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001033
Lucas Dupinc3800b82020-10-02 16:24:48 -07001034bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001035 // If we start or stop drawing blur then the layer's visibility state may change so increment
1036 // the magic sequence number.
1037 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1038 mDrawingState.sequence++;
1039 }
Robert Carr6a160312021-05-17 12:08:20 -07001040 mDrawingState.blurRegions = blurRegions;
1041 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001042 setTransactionFlags(eTransactionNeeded);
1043 return true;
1044}
1045
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001046bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001047 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1048 if (mDrawingState.flags == newFlags) return false;
1049 mDrawingState.sequence++;
1050 mDrawingState.flags = newFlags;
1051 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001052 setTransactionFlags(eTransactionNeeded);
1053 return true;
1054}
Robert Carr99e27f02016-06-16 15:18:02 -07001055
chaviw25714502021-02-11 10:01:08 -08001056bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001057 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001058 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001059 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001060
Robert Carr6a160312021-05-17 12:08:20 -07001061 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001062 setTransactionFlags(eTransactionNeeded);
1063 return true;
1064}
Robert Carr8d5227b2017-03-16 15:41:03 -07001065
Evan Roskyef876c92019-01-25 17:46:06 -08001066bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001067 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1068 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001069 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001070 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001071}
1072
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001073bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001074 if (mDrawingState.layerStack == layerStack) return false;
1075 mDrawingState.sequence++;
1076 mDrawingState.layerStack = layerStack;
1077 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001078 setTransactionFlags(eTransactionNeeded);
1079 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001080}
1081
Peiyong Linc502cb72019-03-01 15:00:23 -08001082bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001083 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001084 return false;
1085 }
Robert Carr6a160312021-05-17 12:08:20 -07001086 mDrawingState.sequence++;
1087 mDrawingState.colorSpaceAgnostic = agnostic;
1088 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001089 setTransactionFlags(eTransactionNeeded);
1090 return true;
1091}
1092
Sally Qi81d95e62022-03-21 19:41:33 -07001093bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1094 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1095
1096 mDrawingState.sequence++;
1097 mDrawingState.dimmingEnabled = dimmingEnabled;
1098 mDrawingState.modified = true;
1099 setTransactionFlags(eTransactionNeeded);
1100 return true;
1101}
1102
Ana Krulecc84d09b2019-11-02 23:10:29 +01001103bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001104 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1105 mDrawingState.frameRateSelectionPriority = priority;
1106 mDrawingState.sequence++;
1107 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001108 setTransactionFlags(eTransactionNeeded);
1109 return true;
1110}
1111
1112int32_t Layer::getFrameRateSelectionPriority() const {
1113 // Check if layer has priority set.
1114 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1115 return mDrawingState.frameRateSelectionPriority;
1116 }
1117 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001118 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001119 if (parent != nullptr) {
1120 return parent->getFrameRateSelectionPriority();
1121 }
1122
1123 return Layer::PRIORITY_UNSET;
1124}
1125
Andy Labrada096227e2022-06-15 16:58:11 +00001126bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1127 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1128 mDrawingState.defaultFrameRateCompatibility = compatibility;
1129 mDrawingState.modified = true;
Vishnu Nair80e8cfe2023-09-29 17:03:45 -07001130 mFlinger->mScheduler->setDefaultFrameRateCompatibility(sequence, compatibility);
Andy Labrada096227e2022-06-15 16:58:11 +00001131 setTransactionFlags(eTransactionNeeded);
1132 return true;
1133}
1134
Vishnu Nair3fbe3262023-09-29 17:07:00 -07001135scheduler::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
Andy Labrada096227e2022-06-15 16:58:11 +00001136 return mDrawingState.defaultFrameRateCompatibility;
1137}
1138
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001139bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1140 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1141};
1142
Vishnu Nair73908d12022-10-24 21:46:42 -07001143ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1144 bool useDrawing = state == LayerVector::StateSet::Drawing;
1145 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1146 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001147 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001148 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001149 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001150}
1151
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001152bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001153 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001154 return false;
1155 }
1156
Robert Carr6a160312021-05-17 12:08:20 -07001157 mDrawingState.sequence++;
1158 mDrawingState.shadowRadius = shadowRadius;
1159 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001160 setTransactionFlags(eTransactionNeeded);
1161 return true;
1162}
1163
Vishnu Nair6213bd92020-05-08 17:42:25 -07001164bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001165 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001166 return false;
1167 }
1168
Robert Carr6a160312021-05-17 12:08:20 -07001169 mDrawingState.sequence++;
1170 mDrawingState.fixedTransformHint = fixedTransformHint;
1171 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001172 setTransactionFlags(eTransactionNeeded);
1173 return true;
1174}
1175
John Reckcdb4ed72021-02-04 13:39:33 -05001176bool Layer::setStretchEffect(const StretchEffect& effect) {
1177 StretchEffect temp = effect;
1178 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001179 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001180 return false;
1181 }
Robert Carr6a160312021-05-17 12:08:20 -07001182 mDrawingState.sequence++;
1183 mDrawingState.stretchEffect = temp;
1184 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001185 setTransactionFlags(eTransactionNeeded);
1186 return true;
1187}
1188
John Reckc00c6692021-02-16 11:37:33 -05001189StretchEffect Layer::getStretchEffect() const {
1190 if (mDrawingState.stretchEffect.hasEffect()) {
1191 return mDrawingState.stretchEffect;
1192 }
1193
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001194 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001195 if (parent != nullptr) {
1196 auto effect = parent->getStretchEffect();
1197 if (effect.hasEffect()) {
1198 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1199 return effect;
1200 }
1201 }
1202 return StretchEffect{};
1203}
1204
Rachel Lee0faad6c2023-09-08 13:34:34 -07001205bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool overrideChildren,
1206 bool* transactionNeeded) {
1207 // Gets the frame rate to propagate to children.
Ady Abrahama850c182021-08-04 13:04:37 -07001208 const auto frameRate = [&] {
Rachel Lee0faad6c2023-09-08 13:34:34 -07001209 if (overrideChildren && parentFrameRate.isValid()) {
1210 return parentFrameRate;
1211 }
1212
Rachel Leece6e0042023-06-27 11:22:54 -07001213 if (mDrawingState.frameRate.isValid()) {
Ady Abrahama850c182021-08-04 13:04:37 -07001214 return mDrawingState.frameRate;
1215 }
1216
1217 return parentFrameRate;
1218 }();
1219
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001220 auto now = systemTime();
1221 *transactionNeeded |= setFrameRateForLayerTreeLegacy(frameRate, now);
Ady Abrahama850c182021-08-04 13:04:37 -07001222
Rachel Leea021bb02023-11-20 21:51:09 -08001223 // The frame rate is propagated to the children by default, but some properties may override it.
Ady Abrahama850c182021-08-04 13:04:37 -07001224 bool childrenHaveFrameRate = false;
Rachel Leea021bb02023-11-20 21:51:09 -08001225 const bool overrideChildrenFrameRate = overrideChildren || shouldOverrideChildrenFrameRate();
1226 const bool canPropagateFrameRate = shouldPropagateFrameRate() || overrideChildrenFrameRate;
Ady Abrahama850c182021-08-04 13:04:37 -07001227 for (const sp<Layer>& child : mCurrentChildren) {
1228 childrenHaveFrameRate |=
Rachel Leea021bb02023-11-20 21:51:09 -08001229 child->propagateFrameRateForLayerTree(canPropagateFrameRate ? frameRate
1230 : FrameRate(),
1231 overrideChildrenFrameRate, transactionNeeded);
Ady Abrahama850c182021-08-04 13:04:37 -07001232 }
1233
Rachel Leece6e0042023-06-27 11:22:54 -07001234 // If we don't have a valid frame rate specification, but the children do, we set this
Ady Abrahama850c182021-08-04 13:04:37 -07001235 // layer as NoVote to allow the children to control the refresh rate
Rachel Leece6e0042023-06-27 11:22:54 -07001236 if (!frameRate.isValid() && childrenHaveFrameRate) {
Ady Abrahama850c182021-08-04 13:04:37 -07001237 *transactionNeeded |=
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001238 setFrameRateForLayerTreeLegacy(FrameRate(Fps(), FrameRateCompatibility::NoVote),
1239 now);
Ady Abrahama850c182021-08-04 13:04:37 -07001240 }
1241
Rachel Leece6e0042023-06-27 11:22:54 -07001242 // We return whether this layer or its children has a vote. We ignore ExactOrMultiple votes for
Ady Abrahama850c182021-08-04 13:04:37 -07001243 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001244 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001245 const auto layerVotedWithDefaultCompatibility =
Rachel Leece6e0042023-06-27 11:22:54 -07001246 frameRate.vote.rate.isValid() && frameRate.vote.type == FrameRateCompatibility::Default;
1247 const auto layerVotedWithNoVote = frameRate.vote.type == FrameRateCompatibility::NoVote;
1248 const auto layerVotedWithCategory = frameRate.category != FrameRateCategory::Default;
Ady Abrahama850c182021-08-04 13:04:37 -07001249 const auto layerVotedWithExactCompatibility =
Rachel Leece6e0042023-06-27 11:22:54 -07001250 frameRate.vote.rate.isValid() && frameRate.vote.type == FrameRateCompatibility::Exact;
1251 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote || layerVotedWithCategory ||
Ady Abrahama850c182021-08-04 13:04:37 -07001252 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1253}
1254
Ady Abraham60e42ea2020-03-09 19:17:31 -07001255void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001256 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001257 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001258 while (auto parent = layer->getParent()) {
1259 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001260 }
Ady Abrahama850c182021-08-04 13:04:37 -07001261 return layer;
1262 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001263
Ady Abraham60e42ea2020-03-09 19:17:31 -07001264 bool transactionNeeded = false;
Rachel Lee0faad6c2023-09-08 13:34:34 -07001265 root->propagateFrameRateForLayerTree({}, false, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001266
Ady Abrahama850c182021-08-04 13:04:37 -07001267 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001268 if (transactionNeeded) {
1269 mFlinger->setTransactionFlags(eTraversalNeeded);
1270 }
1271}
1272
Rachel Leece6e0042023-06-27 11:22:54 -07001273bool Layer::setFrameRate(FrameRate::FrameRateVote frameRateVote) {
1274 if (mDrawingState.frameRate.vote == frameRateVote) {
Steven Thomas3172e202020-01-06 19:25:30 -08001275 return false;
1276 }
1277
Robert Carr6a160312021-05-17 12:08:20 -07001278 mDrawingState.sequence++;
Rachel Leece6e0042023-06-27 11:22:54 -07001279 mDrawingState.frameRate.vote = frameRateVote;
1280 mDrawingState.modified = true;
1281
1282 updateTreeHasFrameRateVote();
1283
1284 setTransactionFlags(eTransactionNeeded);
1285 return true;
1286}
1287
Rachel Lee67afbea2023-09-28 15:35:07 -07001288bool Layer::setFrameRateCategory(FrameRateCategory category, bool smoothSwitchOnly) {
1289 if (mDrawingState.frameRate.category == category &&
1290 mDrawingState.frameRate.categorySmoothSwitchOnly == smoothSwitchOnly) {
Rachel Leece6e0042023-06-27 11:22:54 -07001291 return false;
1292 }
1293
1294 mDrawingState.sequence++;
1295 mDrawingState.frameRate.category = category;
Rachel Lee67afbea2023-09-28 15:35:07 -07001296 mDrawingState.frameRate.categorySmoothSwitchOnly = smoothSwitchOnly;
Robert Carr6a160312021-05-17 12:08:20 -07001297 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001298
1299 updateTreeHasFrameRateVote();
1300
Steven Thomas3172e202020-01-06 19:25:30 -08001301 setTransactionFlags(eTransactionNeeded);
1302 return true;
1303}
1304
Rachel Lee58cc90d2023-09-05 18:50:20 -07001305bool Layer::setFrameRateSelectionStrategy(FrameRateSelectionStrategy strategy) {
1306 if (mDrawingState.frameRateSelectionStrategy == strategy) return false;
1307 mDrawingState.frameRateSelectionStrategy = strategy;
1308 mDrawingState.sequence++;
1309 mDrawingState.modified = true;
Rachel Leed7479502023-09-25 17:02:35 -07001310
1311 updateTreeHasFrameRateVote();
Rachel Lee58cc90d2023-09-05 18:50:20 -07001312 setTransactionFlags(eTransactionNeeded);
1313 return true;
1314}
1315
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001316void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1317 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001318 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001319
1320 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1321 // there are two transactions with the same token, the first one without a buffer and the
1322 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1323 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001324 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1325 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001326 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001327 mDrawingState.bufferSurfaceFrameTX = it->second;
1328 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1329 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1330 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001331 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001332 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001333 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
1334 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001335
1336 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001337}
1338
1339void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1340 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001341 mDrawingState.frameTimelineInfo = info;
1342 mDrawingState.postTime = postTime;
1343 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001344 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001345
Robert Carr6a160312021-05-17 12:08:20 -07001346 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001347 bufferSurfaceFrameTX != nullptr) {
1348 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1349 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1350 // being used for BufferSurfaceFrame, don't create a new one.
1351 return;
1352 }
1353 }
1354 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1355 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1356 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001357 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1358 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001359 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001360 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001361 } else {
1362 if (it->second->getPresentState() == PresentState::Presented) {
1363 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1364 // have been from previous vsync.
1365 it->second = createSurfaceFrameForTransaction(info, postTime);
1366 }
1367 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001368
1369 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001370}
1371
1372void Layer::addSurfaceFrameDroppedForBuffer(
Ady Abraham5a3e3562023-06-07 10:32:08 -07001373 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t dropTime) {
1374 surfaceFrame->setDropTime(dropTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001375 surfaceFrame->setPresentState(PresentState::Dropped);
1376 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1377}
1378
1379void Layer::addSurfaceFramePresentedForBuffer(
1380 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1381 nsecs_t currentLatchTime) {
1382 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1383 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1384 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +00001385 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001386}
1387
1388std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1389 const FrameTimelineInfo& info, nsecs_t postTime) {
1390 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001391 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1392 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001393 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001394 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001395 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001396 // For Transactions, the post time is considered to be both queue and acquire fence time.
1397 surfaceFrame->setActualQueueTime(postTime);
1398 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001399 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1400 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001401 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001402 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001403 return surfaceFrame;
1404}
1405
1406std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1407 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1408 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001409 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001410 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001411 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001412 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001413 // For buffers, acquire fence time will set during latch.
1414 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001415 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1416 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001417 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001418 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001419 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001420}
1421
Ady Abraham5a3e3562023-06-07 10:32:08 -07001422void Layer::setFrameTimelineVsyncForSkippedFrames(const FrameTimelineInfo& info, nsecs_t postTime,
1423 std::string debugName) {
1424 if (info.skippedFrameVsyncId == FrameTimelineInfo::INVALID_VSYNC_ID) {
1425 return;
1426 }
1427
1428 FrameTimelineInfo skippedFrameTimelineInfo = info;
1429 skippedFrameTimelineInfo.vsyncId = info.skippedFrameVsyncId;
1430
1431 auto surfaceFrame =
1432 mFlinger->mFrameTimeline->createSurfaceFrameForToken(skippedFrameTimelineInfo,
1433 mOwnerPid, mOwnerUid,
1434 getSequence(), mName, debugName,
1435 /*isBuffer*/ false, getGameMode());
1436 surfaceFrame->setActualStartTime(skippedFrameTimelineInfo.skippedFrameStartTimeNanos);
1437 // For Transactions, the post time is considered to be both queue and acquire fence time.
1438 surfaceFrame->setActualQueueTime(postTime);
1439 surfaceFrame->setAcquireFenceTime(postTime);
1440 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1441 if (fps) {
1442 surfaceFrame->setRenderRate(*fps);
1443 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001444 addSurfaceFrameDroppedForBuffer(surfaceFrame, postTime);
1445}
1446
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001447bool Layer::setFrameRateForLayerTreeLegacy(FrameRate frameRate, nsecs_t now) {
Ady Abrahama850c182021-08-04 13:04:37 -07001448 if (mDrawingState.frameRateForLayerTree == frameRate) {
1449 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001450 }
1451
Ady Abrahama850c182021-08-04 13:04:37 -07001452 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001453
Ady Abrahama850c182021-08-04 13:04:37 -07001454 // TODO(b/195668952): we probably don't need to dirty visible regions here
1455 // or even store frameRateForLayerTree in mDrawingState
1456 mDrawingState.sequence++;
1457 mDrawingState.modified = true;
1458 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001459
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001460 mFlinger->mScheduler
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001461 ->recordLayerHistory(sequence, getLayerProps(), now, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001462 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
1463 return true;
1464}
Ady Abrahama850c182021-08-04 13:04:37 -07001465
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001466bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps,
1467 nsecs_t now) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001468 if (mDrawingState.frameRateForLayerTree == frameRate) {
1469 return false;
1470 }
1471
1472 mDrawingState.frameRateForLayerTree = frameRate;
1473 mFlinger->mScheduler
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001474 ->recordLayerHistory(sequence, layerProps, now, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001475 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001476 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001477}
1478
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001479Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1480 return getDrawingState().frameRateForLayerTree;
1481}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001482
Robert Carr1f0a16a2016-10-24 16:27:39 -07001483bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001484 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001485 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001486 if (parent != nullptr && parent->isHiddenByPolicy()) {
1487 return true;
1488 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001489 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1490 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1491 if (zOrderRelativeOf != nullptr) {
1492 if (zOrderRelativeOf->isHiddenByPolicy()) {
1493 return true;
1494 }
1495 }
1496 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001497 if (CC_UNLIKELY(!isTransformValid())) {
1498 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1499 return true;
1500 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001501 return s.flags & layer_state_t::eLayerHidden;
1502}
1503
David Sodman41fdfc92017-11-06 16:09:56 -08001504uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001505 // TODO: should we do something special if mSecure is set?
1506 if (mProtectedByApp) {
1507 // need a hardware-protected path to external video sink
1508 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001509 }
Riley Andrews03414a12014-07-01 14:22:59 -07001510 if (mPotentialCursor) {
1511 usage |= GraphicBuffer::USAGE_CURSOR;
1512 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001513 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001514 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001515}
1516
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001517void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1518 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1519 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001520 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001521
Vishnu Nairb76d99a2023-03-19 18:22:31 -07001522 setTransformHintLegacy(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001523}
1524
Mathias Agopian13127d82013-03-05 17:47:11 -08001525// ----------------------------------------------------------------------------
1526// debugging
1527// ----------------------------------------------------------------------------
1528
Yiwei Zhang5434a782018-12-05 18:06:32 -08001529void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001530 result.append(kDumpTableRowLength, '-');
1531 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001532 result.append(" Layer name\n");
1533 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001534 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001535 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001536 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001537 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001538 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001539 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1540 result.append(kDumpTableRowLength, '-');
1541 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001542}
1543
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001544void Layer::miniDumpLegacy(std::string& result, const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001545 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001546 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001547 return;
1548 }
1549
Yiwei Zhang5434a782018-12-05 18:06:32 -08001550 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001551 if (mName.length() > 77) {
1552 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001553 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001554 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001555 shortened.append(mName, mName.length() - 36);
1556 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001557 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001558 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001559 }
1560
Yiwei Zhang5434a782018-12-05 18:06:32 -08001561 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001562
Alec Mourib416efd2018-09-06 21:01:59 +00001563 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001564 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001565
Chia-I Wu1e043612018-03-01 09:45:09 -08001566 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001567 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001568 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001569 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001570 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001571 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001572 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001573 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1574 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001575 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001576 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001577 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001578 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001579 const auto frameRate = getFrameRateForLayerTree();
Rachel Leece6e0042023-06-27 11:22:54 -07001580 if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
1581 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.vote.rate).c_str(),
1582 ftl::enum_string(frameRate.vote.type).c_str(),
1583 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001584 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001585 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001586 }
Dan Stozae22aec72016-08-01 13:20:59 -07001587
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001588 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1589 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1590
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001591 result.append(kDumpTableRowLength, '-');
1592 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001593}
Dan Stozae22aec72016-08-01 13:20:59 -07001594
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001595void Layer::miniDump(std::string& result, const frontend::LayerSnapshot& snapshot,
1596 const DisplayDevice& display) const {
1597 const auto outputLayer = findOutputLayerForDisplay(&display, snapshot.path);
1598 if (!outputLayer) {
1599 return;
1600 }
1601
1602 StringAppendF(&result, " %s\n", snapshot.debugName.c_str());
1603 StringAppendF(&result, " %10zu | ", snapshot.globalZ);
1604 StringAppendF(&result, " %10d | ",
1605 snapshot.layerMetadata.getInt32(gui::METADATA_WINDOW_TYPE, 0));
1606 StringAppendF(&result, "%10s | ", toString(getCompositionType(outputLayer)).c_str());
1607 const auto& outputLayerState = outputLayer->getState();
1608 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1609 const Rect& frame = outputLayerState.displayFrame;
1610 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
1611 const FloatRect& crop = outputLayerState.sourceCrop;
1612 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
1613 crop.bottom);
1614 const auto frameRate = snapshot.frameRate;
Ady Abraham77d406d2023-11-22 15:00:23 -08001615 std::string frameRateStr;
1616 if (frameRate.vote.rate.isValid()) {
1617 StringAppendF(&frameRateStr, "%.2f", frameRate.vote.rate.getValue());
1618 }
Rachel Leece6e0042023-06-27 11:22:54 -07001619 if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
Ady Abraham77d406d2023-11-22 15:00:23 -08001620 StringAppendF(&result, "%6s %15s %17s", frameRateStr.c_str(),
Rachel Leece6e0042023-06-27 11:22:54 -07001621 ftl::enum_string(frameRate.vote.type).c_str(),
1622 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Ady Abraham77d406d2023-11-22 15:00:23 -08001623 } else if (frameRate.category != FrameRateCategory::Default) {
1624 StringAppendF(&result, "%6s %15s %17s", frameRateStr.c_str(),
1625 (std::string("Cat::") + ftl::enum_string(frameRate.category)).c_str(),
1626 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001627 } else {
1628 result.append(41, ' ');
1629 }
1630
1631 const auto focused = isLayerFocusedBasedOnPriority(snapshot.frameRateSelectionPriority);
1632 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1633
1634 result.append(kDumpTableRowLength, '-');
1635 result.append("\n");
1636}
1637
Yiwei Zhang5434a782018-12-05 18:06:32 -08001638void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001639 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001640}
1641
Svetoslavd85084b2014-03-20 10:28:31 -07001642void Layer::clearFrameStats() {
1643 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001644}
1645
Jamie Gennis6547ff42013-07-16 20:12:42 -07001646void Layer::logFrameStats() {
1647 mFrameTracker.logAndResetStats(mName);
1648}
1649
Svetoslavd85084b2014-03-20 10:28:31 -07001650void Layer::getFrameStats(FrameStats* outStats) const {
1651 mFrameTracker.getStats(outStats);
1652}
1653
Vishnu Nair76554eb2022-12-09 03:38:36 +00001654void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1655 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
Vishnu Nair3be61902023-04-26 19:47:29 -07001656 StringAppendF(&result, "Layer %s%s pid:%d uid:%d%s\n", getName().c_str(), hasBuffer.c_str(),
1657 mOwnerPid, mOwnerUid, isHandleAlive() ? " handleAlive" : "");
Vishnu Nair0f085c62019-08-30 08:49:12 -07001658}
1659
Brian Anderson5ea5e592016-12-01 16:54:33 -08001660void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001661 const int32_t layerId = getSequence();
1662 mFlinger->mTimeStats->onDestroy(layerId);
1663 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001664}
1665
Vishnu Nair787aa782023-03-17 13:46:46 -07001666size_t Layer::getDescendantCount() const {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001667 size_t count = 0;
Vishnu Nair787aa782023-03-17 13:46:46 -07001668 for (const sp<Layer>& child : mDrawingChildren) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001669 count += 1 + child->getChildrenCount();
1670 }
1671 return count;
1672}
1673
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001674void Layer::setGameModeForTree(GameMode gameMode) {
1675 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001676 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1677 gameMode =
1678 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001679 }
1680 setGameMode(gameMode);
1681 for (const sp<Layer>& child : mCurrentChildren) {
1682 child->setGameModeForTree(gameMode);
1683 }
1684}
1685
Robert Carr1f0a16a2016-10-24 16:27:39 -07001686void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001687 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001688 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001689
Robert Carr1f0a16a2016-10-24 16:27:39 -07001690 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001691 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001692 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001693 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001694}
1695
1696ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001697 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001698 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001699
Robert Carr1323c952019-01-28 18:13:27 -08001700 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001701 const auto removeResult = mCurrentChildren.remove(layer);
1702
1703 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001704 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001705 layer->updateTreeHasFrameRateVote();
1706
1707 return removeResult;
1708}
1709
Robert Carr15eae092018-03-23 13:43:53 -07001710void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001711 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001712 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001713 const float parentShadowRadius =
1714 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001715 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001716 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001717 }
1718}
1719
chaviwf1961f72017-09-18 16:41:07 -07001720bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001721 sp<Layer> newParent;
1722 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001723 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001724 if (newParent == nullptr) {
1725 ALOGE("Unable to promote Layer handle");
1726 return false;
1727 }
1728 if (newParent == this) {
1729 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1730 return false;
1731 }
1732 }
1733
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001734 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001735 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001736 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001737 }
1738
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001739 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001740 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001741 if (!newParent->isRemovedFromCurrentState()) {
1742 addToCurrentState();
1743 } else {
1744 onRemovedFromCurrentState();
1745 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001746 } else {
1747 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001748 }
1749
chaviw06178942017-07-27 10:25:59 -07001750 return true;
1751}
1752
Peiyong Lind3788632018-09-18 16:01:31 -07001753bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001754 static const mat4 identityMatrix = mat4();
1755
Robert Carr6a160312021-05-17 12:08:20 -07001756 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001757 return false;
1758 }
Robert Carr6a160312021-05-17 12:08:20 -07001759 ++mDrawingState.sequence;
1760 mDrawingState.colorTransform = matrix;
1761 mDrawingState.hasColorTransform = matrix != identityMatrix;
1762 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001763 setTransactionFlags(eTransactionNeeded);
1764 return true;
1765}
1766
chaviwf66724d2018-11-28 16:35:21 -08001767mat4 Layer::getColorTransform() const {
1768 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001769 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001770 colorTransform = parent->getColorTransform() * colorTransform;
1771 }
1772 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001773}
1774
1775bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001776 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001777 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001778 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1779 }
1780 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001781}
1782
Chia-I Wu11481472018-05-04 10:43:19 -07001783bool Layer::isLegacyDataSpace() const {
1784 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001785 return !(getDataSpace() &
1786 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1787 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001788}
1789
Robert Carr1f0a16a2016-10-24 16:27:39 -07001790void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001791 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001792}
1793
Robert Carr6a160312021-05-17 12:08:20 -07001794int32_t Layer::getZ(LayerVector::StateSet) const {
1795 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001796}
1797
Robert Carr1c5481e2019-07-01 14:42:27 -07001798bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001799 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001800 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001801 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001802}
1803
David Sodman41fdfc92017-11-06 16:09:56 -08001804__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001805 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001806 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1807 "makeTraversalList received invalid stateSet");
1808 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1809 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001810 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001811
Robert Carr29abff82017-12-04 13:51:20 -08001812 if (state.zOrderRelatives.size() == 0) {
1813 *outSkipRelativeZUsers = true;
1814 return children;
1815 }
1816
chaviwfd462612018-05-31 16:11:27 -07001817 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001818 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001819 sp<Layer> strongRelative = weakRelative.promote();
1820 if (strongRelative != nullptr) {
1821 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001822 }
1823 }
1824
Dan Stoza412903f2017-04-27 13:42:17 -07001825 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001826 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001827 continue;
1828 }
Robert Carrdb66e622017-04-10 16:55:57 -07001829 traverse.add(child);
1830 }
1831
1832 return traverse;
1833}
1834
Robert Carr1f0a16a2016-10-24 16:27:39 -07001835/**
Robert Carrdb66e622017-04-10 16:55:57 -07001836 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001837 */
Dan Stoza412903f2017-04-27 13:42:17 -07001838void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001839 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1840 // produce a new list for traversing, including our relatives, and not including our children
1841 // who are relatives of another surface. In the case that there are no relative Z,
1842 // makeTraversalList returns our children directly to avoid significant overhead.
1843 // However in this case we need to take the responsibility for filtering children which
1844 // are relatives of another surface here.
1845 bool skipRelativeZUsers = false;
1846 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001847
Robert Carr1f0a16a2016-10-24 16:27:39 -07001848 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001849 for (; i < list.size(); i++) {
1850 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001851 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1852 continue;
1853 }
1854
chaviw301b1d82019-11-06 13:15:09 -08001855 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001856 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001857 }
Dan Stoza412903f2017-04-27 13:42:17 -07001858 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001859 }
Robert Carr29abff82017-12-04 13:51:20 -08001860
Dan Stoza412903f2017-04-27 13:42:17 -07001861 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001862 for (; i < list.size(); i++) {
1863 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001864
Robert Carr29abff82017-12-04 13:51:20 -08001865 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1866 continue;
1867 }
Dan Stoza412903f2017-04-27 13:42:17 -07001868 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001869 }
1870}
1871
1872/**
Robert Carrdb66e622017-04-10 16:55:57 -07001873 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001874 */
Dan Stoza412903f2017-04-27 13:42:17 -07001875void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1876 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001877 // See traverseInZOrder for documentation.
1878 bool skipRelativeZUsers = false;
1879 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001880
Robert Carr1f0a16a2016-10-24 16:27:39 -07001881 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001882 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001883 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001884
1885 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1886 continue;
1887 }
1888
chaviw301b1d82019-11-06 13:15:09 -08001889 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001890 break;
1891 }
Dan Stoza412903f2017-04-27 13:42:17 -07001892 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001893 }
Dan Stoza412903f2017-04-27 13:42:17 -07001894 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001895 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001896 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001897
1898 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1899 continue;
1900 }
1901
Dan Stoza412903f2017-04-27 13:42:17 -07001902 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001903 }
1904}
1905
Edgar Arriaga844fa672020-01-16 14:21:42 -08001906void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1907 visitor(this);
1908 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001909 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001910 for (const sp<Layer>& child : children) {
1911 child->traverse(state, visitor);
1912 }
1913}
1914
Vishnu Nair787aa782023-03-17 13:46:46 -07001915void Layer::traverseChildren(const LayerVector::Visitor& visitor) {
1916 for (const sp<Layer>& child : mDrawingChildren) {
1917 visitor(child.get());
1918 }
1919}
1920
chaviw4b129c22018-04-09 16:19:43 -07001921LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1922 const std::vector<Layer*>& layersInTree) {
1923 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1924 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07001925 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1926 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001927 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001928
chaviwfd462612018-05-31 16:11:27 -07001929 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07001930 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1931 sp<Layer> strongRelative = weakRelative.promote();
1932 // Only add relative layers that are also descendents of the top most parent of the tree.
1933 // If a relative layer is not a descendent, then it should be ignored.
1934 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
1935 traverse.add(strongRelative);
1936 }
1937 }
1938
1939 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07001940 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001941 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
1942 // descendent of the top most parent of the tree. If it's not a descendent, then just add
1943 // the child here since it won't be added later as a relative.
1944 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
1945 childState.zOrderRelativeOf.promote().get())) {
1946 continue;
1947 }
1948 traverse.add(child);
1949 }
1950
1951 return traverse;
1952}
1953
1954void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1955 LayerVector::StateSet stateSet,
1956 const LayerVector::Visitor& visitor) {
1957 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07001958
1959 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07001960 for (; i < list.size(); i++) {
1961 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08001962 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07001963 break;
1964 }
chaviw4b129c22018-04-09 16:19:43 -07001965 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001966 }
chaviw4b129c22018-04-09 16:19:43 -07001967
chaviwa76b2712017-09-20 12:02:26 -07001968 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07001969 for (; i < list.size(); i++) {
1970 const auto& relative = list[i];
1971 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001972 }
1973}
1974
chaviw4b129c22018-04-09 16:19:43 -07001975std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
1976 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1977 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1978
1979 std::vector<Layer*> layersInTree = {this};
1980 for (size_t i = 0; i < children.size(); i++) {
1981 const auto& child = children[i];
1982 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
1983 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
1984 }
1985
1986 return layersInTree;
1987}
1988
1989void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
1990 const LayerVector::Visitor& visitor) {
1991 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
1992 std::sort(layersInTree.begin(), layersInTree.end());
1993 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
1994}
1995
Peiyong Linefefaac2018-08-17 12:27:51 -07001996ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08001997 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001998}
1999
Garfield Tan2c1782c2022-02-16 15:25:05 -08002000bool Layer::isTransformValid() const {
2001 float transformDet = getTransform().det();
2002 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
2003}
2004
chaviw13fdc492017-06-27 12:40:18 -07002005half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002006 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002007
chaviw13fdc492017-06-27 12:40:18 -07002008 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2009 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002010}
Robert Carr6452f122017-03-21 10:41:29 -07002011
Vishnu Nair6213bd92020-05-08 17:42:25 -07002012ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07002013 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07002014 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2015 return fixedTransformHint;
2016 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002017 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07002018 if (!p) return fixedTransformHint;
2019 return p->getFixedTransformHint();
2020}
2021
chaviw13fdc492017-06-27 12:40:18 -07002022half4 Layer::getColor() const {
2023 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002024 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002025}
Robert Carr6452f122017-03-21 10:41:29 -07002026
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002027int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002028 if (getDrawingState().backgroundBlurRadius == 0) {
2029 return 0;
2030 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002031
Vishnu Nair29810f72022-07-01 16:38:41 +00002032 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002033 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2034 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002035}
2036
Galia Peychevae0acf382021-04-12 21:22:34 +02002037const std::vector<BlurRegion> Layer::getBlurRegions() const {
2038 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002039 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002040 for (auto& region : regionsCopy) {
2041 region.alpha = region.alpha * layerAlpha;
2042 }
2043 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002044}
2045
Vishnu Naire14c6b32022-08-06 04:20:15 +00002046RoundedCornerState Layer::getRoundedCornerState() const {
Leon Scroggins IIIc1dbfcb2022-03-21 16:48:10 -04002047 // Today's DPUs cannot do rounded corners. If RenderEngine cannot render
2048 // protected content, remove rounded corners from protected content so it
2049 // can be rendered by the DPU.
2050 if (isProtected() && !mFlinger->getRenderEngine().supportsProtectedContent()) {
2051 return {};
2052 }
2053
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002054 // Get parent settings
2055 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002056 const auto& parent = mDrawingParent.promote();
2057 if (parent != nullptr) {
2058 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002059 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002060 ui::Transform t = getActiveTransform(getDrawingState());
2061 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002062 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002063 parentSettings.radius.x *= t.getScaleX();
2064 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002065 }
2066 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002067
2068 // Get layer settings
2069 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002070 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002071 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002072 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002073
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002074 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002075 // If the parent and the layer have rounded corner settings, use the parent settings if the
2076 // parent crop is entirely inside the layer crop.
2077 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2078 if (parentSettings.cropRect.left > layerCropRect.left &&
2079 parentSettings.cropRect.top > layerCropRect.top &&
2080 parentSettings.cropRect.right < layerCropRect.right &&
2081 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2082 return parentSettings;
2083 } else {
2084 return layerSettings;
2085 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002086 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002087 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002088 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002089 return parentSettings;
2090 }
2091 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002092}
2093
Robert Carr88b85e12022-03-21 15:47:35 -07002094bool Layer::findInHierarchy(const sp<Layer>& l) {
2095 if (l == this) {
2096 return true;
2097 }
2098 for (auto& child : mDrawingChildren) {
2099 if (child->findInHierarchy(l)) {
2100 return true;
2101 }
2102 }
2103 return false;
2104}
2105
Robert Carr1f0a16a2016-10-24 16:27:39 -07002106void Layer::commitChildList() {
2107 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2108 const auto& child = mCurrentChildren[i];
2109 child->commitChildList();
2110 }
2111 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002112 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002113 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2114 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2115 if (zOrderRelativeOf == nullptr) return;
2116 if (findInHierarchy(zOrderRelativeOf)) {
2117 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2118 zOrderRelativeOf->mName.c_str());
2119 ALOGE("Severing rel Z loop, potentially dangerous");
2120 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002121 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002122 }
2123 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002124}
2125
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002126
chaviw3277faf2021-05-19 16:45:23 -05002127void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002128 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002129 mDrawingState.touchableRegionCrop =
2130 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002131 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002132 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002133 setTransactionFlags(eTransactionNeeded);
2134}
2135
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002136perfetto::protos::LayerProto* Layer::writeToProto(perfetto::protos::LayersProto& layersProto,
2137 uint32_t traceFlags) {
2138 perfetto::protos::LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002139 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002140 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2141
Vishnu Nair00b90132021-11-05 14:03:40 -07002142 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Vishnu Nair2f65e972023-04-04 16:36:28 +00002143 ui::LayerStack layerStack =
2144 (mSnapshot) ? mSnapshot->outputFilter.layerStack : ui::INVALID_LAYER_STACK;
2145 writeCompositionStateToProto(layerProto, layerStack);
Alec Mouri6b9e9912020-01-21 10:50:24 -08002146 }
2147
chaviw08f3cb22020-01-13 13:17:21 -08002148 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002149 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002150 }
chaviw6d89e2d2020-01-14 14:42:01 -08002151
2152 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002153}
2154
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002155void Layer::writeCompositionStateToProto(perfetto::protos::LayerProto* layerProto,
2156 ui::LayerStack layerStack) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002157 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002158 ftl::FakeGuard mainThreadGuard(kMainThreadContext);
Vishnu Nairea6ff812023-02-27 17:41:39 +00002159
2160 // Only populate for the primary display.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002161 if (const auto display = mFlinger->getDisplayFromLayerStack(layerStack)) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002162 const auto compositionType = getCompositionType(*display);
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002163 layerProto->set_hwc_composition_type(
2164 static_cast<perfetto::protos::HwcCompositionType>(compositionType));
Vishnu Nair2f65e972023-04-04 16:36:28 +00002165 LayerProtoHelper::writeToProto(getVisibleRegion(display),
Vishnu Nairea6ff812023-02-27 17:41:39 +00002166 [&]() { return layerProto->mutable_visible_region(); });
2167 }
2168}
2169
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002170void Layer::writeToProtoDrawingState(perfetto::protos::LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002171 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002172 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002173 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002174 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002175 [&]() { return layerInfo->mutable_active_buffer(); });
2176 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2177 layerInfo->mutable_buffer_transform());
2178 }
2179 layerInfo->set_invalidate(contentDirty);
2180 layerInfo->set_is_protected(isProtected());
2181 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2182 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002183 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002184 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002185 layerInfo->set_corner_radius(
2186 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002187 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2188 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2189 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2190 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2191 [&]() { return layerInfo->mutable_position(); });
2192 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002193 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2194 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002195
Vishnu Nair00b90132021-11-05 14:03:40 -07002196 if (hasColorTransform()) {
2197 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002198 }
2199
Vishnu Nair60db8c02020-04-02 11:55:16 -07002200 LayerProtoHelper::writeToProto(mSourceBounds,
2201 [&]() { return layerInfo->mutable_source_bounds(); });
2202 LayerProtoHelper::writeToProto(mScreenBounds,
2203 [&]() { return layerInfo->mutable_screen_bounds(); });
2204 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2205 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2206 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002207}
2208
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002209void Layer::writeToProtoCommonState(perfetto::protos::LayerProto* layerInfo,
2210 LayerVector::StateSet stateSet, uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002211 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2212 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002213 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002214
chaviw766c9c52021-02-10 17:36:47 -08002215 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002216
Vishnu Nair00b90132021-11-05 14:03:40 -07002217 layerInfo->set_id(sequence);
2218 layerInfo->set_name(getName().c_str());
2219 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002220
Vishnu Nair00b90132021-11-05 14:03:40 -07002221 for (const auto& child : children) {
2222 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002223 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002224
Vishnu Nair00b90132021-11-05 14:03:40 -07002225 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2226 sp<Layer> strongRelative = weakRelative.promote();
2227 if (strongRelative != nullptr) {
2228 layerInfo->add_relatives(strongRelative->sequence);
2229 }
2230 }
2231
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002232 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002233 [&]() { return layerInfo->mutable_transparent_region(); });
2234
2235 layerInfo->set_layer_stack(getLayerStack().id);
2236 layerInfo->set_z(state.z);
2237
2238 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2239 return layerInfo->mutable_requested_position();
2240 });
2241
Vishnu Nair00b90132021-11-05 14:03:40 -07002242 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2243
2244 layerInfo->set_is_opaque(isOpaque(state));
2245
2246 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2247 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2248 LayerProtoHelper::writeToProto(state.color,
2249 [&]() { return layerInfo->mutable_requested_color(); });
2250 layerInfo->set_flags(state.flags);
2251
2252 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2253 layerInfo->mutable_requested_transform());
2254
2255 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2256 if (parent != nullptr) {
2257 layerInfo->set_parent(parent->sequence);
Vishnu Nair00b90132021-11-05 14:03:40 -07002258 }
2259
2260 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2261 if (zOrderRelativeOf != nullptr) {
2262 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
Vishnu Nair00b90132021-11-05 14:03:40 -07002263 }
2264
2265 layerInfo->set_is_relative_of(state.isRelativeOf);
2266
2267 layerInfo->set_owner_uid(mOwnerUid);
2268
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002269 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002270 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002271 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002272 info = fillInputInfo(
2273 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002274 } else {
2275 info = state.inputInfo;
2276 }
2277
2278 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002279 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002280 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002281
Vishnu Nair00b90132021-11-05 14:03:40 -07002282 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002283 auto protoMap = layerInfo->mutable_metadata();
2284 for (const auto& entry : state.metadata.mMap) {
2285 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2286 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002287 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002288
2289 LayerProtoHelper::writeToProto(state.destinationFrame,
2290 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002291}
2292
Robert Carr2e102c92018-10-23 12:11:15 -07002293bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002294 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002295}
2296
Prabir Pradhan33da9462022-06-14 14:55:57 +00002297// Applies the given transform to the region, while protecting against overflows caused by any
2298// offsets. If applying the offset in the transform to any of the Rects in the region would result
2299// in an overflow, they are not added to the output Region.
2300static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2301 const std::string& debugWindowName) {
2302 // Round the translation using the same rounding strategy used by ui::Transform.
2303 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2304 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2305
2306 ui::Transform transformWithoutOffset = t;
2307 transformWithoutOffset.set(0.f, 0.f);
2308
2309 const Region transformed = transformWithoutOffset.transform(r);
2310
2311 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2312 Region ret;
2313 for (const auto& rect : transformed) {
2314 Rect newRect;
2315 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2316 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2317 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2318 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2319 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2320 debugWindowName.c_str());
2321 continue;
2322 }
2323 ret.orSelf(newRect);
2324 }
2325 return ret;
2326}
2327
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002328void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002329 auto [inputBounds, inputBoundsValid] = getInputBounds(/*fillParentBounds=*/false);
2330 if (!inputBoundsValid) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002331 info.touchableRegion.clear();
chaviw7e72caf2020-12-02 16:50:43 -08002332 }
2333
Chavi Weingarten7f019192023-08-08 20:39:01 +00002334 info.frame = getInputBoundsInDisplaySpace(inputBounds, screenToDisplay);
chaviw1ff3d1e2020-07-01 15:53:47 -07002335
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002336 ui::Transform inputToLayer;
Vishnu Nairfed7c122023-03-18 01:54:43 +00002337 inputToLayer.set(inputBounds.left, inputBounds.top);
2338 const ui::Transform layerToScreen = getInputTransform();
2339 const ui::Transform inputToDisplay = screenToDisplay * layerToScreen * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002340
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002341 // InputDispatcher expects a display-to-input transform.
2342 info.transform = inputToDisplay.inverse();
2343
2344 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002345 info.touchableRegion =
2346 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002347}
2348
chaviw3277faf2021-05-19 16:45:23 -05002349void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002350 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002351 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002352 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002353 }
2354 if (p != nullptr) {
2355 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2356 }
2357}
2358
Vishnu Naira066d902021-09-13 18:40:17 -07002359gui::DropInputMode Layer::getDropInputMode() const {
2360 gui::DropInputMode mode = mDrawingState.dropInputMode;
2361 if (mode == gui::DropInputMode::ALL) {
2362 return mode;
2363 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002364 sp<Layer> parent = mDrawingParent.promote();
2365 if (parent) {
2366 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002367 if (parentMode != gui::DropInputMode::NONE) {
2368 return parentMode;
2369 }
2370 }
2371 return mode;
2372}
2373
2374void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002375 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002376 return;
2377 }
2378
2379 // Check if we need to drop input unconditionally
2380 gui::DropInputMode dropInputMode = getDropInputMode();
2381 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002382 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002383 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2384 return;
2385 }
2386
2387 // Check if we need to check if the window is obscured by parent
2388 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2389 return;
2390 }
2391
2392 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002393 sp<Layer> parent = mDrawingParent.promote();
2394 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002395 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002396 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2397 static_cast<float>(getAlpha()));
2398 }
2399
2400 // Check if the parent has cropped the buffer
2401 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2402 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002403 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002404 return;
2405 }
2406
2407 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2408 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2409 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2410 // match then the layer has not been cropped by its parents.
2411 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2412 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2413
2414 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002415 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002416 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2417 getDebugName());
2418 } else {
2419 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2420 // input if the window is obscured. This check should be done in surfaceflinger but the
2421 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2422 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002423 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002424 }
2425}
2426
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002427WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002428 if (!hasInputInfo()) {
2429 mDrawingState.inputInfo.name = getName();
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002430 mDrawingState.inputInfo.ownerUid = gui::Uid{mOwnerUid};
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00002431 mDrawingState.inputInfo.ownerPid = gui::Pid{mOwnerPid};
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002432 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Linnan Li13bf76a2024-05-05 19:18:02 +08002433 mDrawingState.inputInfo.displayId = toLogicalDisplayId(getLayerStack());
chaviw7e72caf2020-12-02 16:50:43 -08002434 }
2435
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002436 const ui::Transform& displayTransform =
2437 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2438
chaviw3277faf2021-05-19 16:45:23 -05002439 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002440 info.id = sequence;
Linnan Li13bf76a2024-05-05 19:18:02 +08002441 info.displayId = toLogicalDisplayId(getLayerStack());
chaviw7e72caf2020-12-02 16:50:43 -08002442
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002443 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002444
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002445 if (displayArgs.transform == nullptr) {
2446 // Do not let the window receive touches if it is not associated with a valid display
2447 // transform. We still allow the window to receive keys and prevent ANRs.
2448 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2449 }
2450
Patrick Williams1caf3b72023-03-31 10:59:10 -05002451 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !isVisibleForInput());
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002452
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002453 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002454 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002455 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002456
Vishnu Nair16a938f2021-09-24 07:14:54 -07002457 // If the window will be blacked out on a display because the display does not have the secure
2458 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002459 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002460 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002461 }
2462
Vishnu Nairfed7c122023-03-18 01:54:43 +00002463 sp<Layer> cropLayer = mDrawingState.touchableRegionCrop.promote();
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002464 if (info.replaceTouchableRegionWithCrop) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002465 Rect inputBoundsInDisplaySpace;
2466 if (!cropLayer) {
2467 FloatRect inputBounds = getInputBounds(/*fillParentBounds=*/true).first;
2468 inputBoundsInDisplaySpace = getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2469 } else {
2470 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2471 inputBoundsInDisplaySpace =
2472 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2473 }
2474 info.touchableRegion = Region(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002475 } else if (cropLayer != nullptr) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002476 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2477 Rect inputBoundsInDisplaySpace =
2478 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2479 info.touchableRegion = info.touchableRegion.intersect(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002480 }
2481
Winson Chunga30f7c92021-06-29 15:42:56 -07002482 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2483 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002484 if (isTrustedOverlay()) {
2485 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2486 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002487
chaviwaf87b3e2019-10-01 16:59:28 -07002488 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2489 // touches from going outside the cloned area.
2490 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002491 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002492 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2493 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002494 info.touchableRegion = info.touchableRegion.intersect(rect);
2495 }
2496 }
2497
Vishnu Nair494a2e42023-11-10 17:21:19 -08002498 Rect bufferSize = getBufferSize(getDrawingState());
2499 info.contentSize = Size(bufferSize.width(), bufferSize.height());
2500
Robert Carr720e5062018-07-30 17:45:14 -07002501 return info;
2502}
2503
Vishnu Nairfed7c122023-03-18 01:54:43 +00002504Rect Layer::getInputBoundsInDisplaySpace(const FloatRect& inputBounds,
2505 const ui::Transform& screenToDisplay) {
2506 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2507 // frame and transform used for the layer, which determines the bounds and the coordinate space
2508 // within which the layer will receive input.
2509
2510 // Coordinate space definitions:
2511 // - display: The display device's coordinate space. Correlates to pixels on the display.
2512 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2513 // - layer: The coordinate space of this layer.
2514 // - input: The coordinate space in which this layer will receive input events. This could be
2515 // different than layer space if a surfaceInset is used, which changes the origin
2516 // of the input space.
2517
2518 // Crop the input bounds to ensure it is within the parent's bounds.
2519 const FloatRect croppedInputBounds = mBounds.intersect(inputBounds);
2520 const ui::Transform layerToScreen = getInputTransform();
2521 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
2522 return Rect{layerToDisplay.transform(croppedInputBounds)};
2523}
2524
chaviwaf87b3e2019-10-01 16:59:28 -07002525sp<Layer> Layer::getClonedRoot() {
2526 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002527 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002528 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002529 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002530 return nullptr;
2531 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002532 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002533}
2534
Robert Carredd13602020-04-13 17:24:34 -07002535bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002536 return mDrawingState.inputInfo.token != nullptr ||
2537 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002538}
2539
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002540compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002541 const DisplayDevice* display) const {
2542 if (!display) return nullptr;
Lloyd Pique30db6402023-06-26 18:56:51 +00002543 if (!mFlinger->mLayerLifecycleManagerEnabled) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00002544 return display->getCompositionDisplay()->getOutputLayerForLayer(
2545 getCompositionEngineLayerFE());
2546 }
2547 sp<LayerFE> layerFE;
2548 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
2549 for (auto& [p, layer] : mLayerFEs) {
2550 if (p == path) {
2551 layerFE = layer;
2552 }
2553 }
2554
2555 if (!layerFE) return nullptr;
2556 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002557}
2558
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002559compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
2560 const DisplayDevice* display, const frontend::LayerHierarchy::TraversalPath& path) const {
2561 if (!display) return nullptr;
Vishnu Naire9ee0002023-07-01 03:14:51 +00002562 if (!mFlinger->mLayerLifecycleManagerEnabled) {
2563 return display->getCompositionDisplay()->getOutputLayerForLayer(
2564 getCompositionEngineLayerFE());
2565 }
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002566 sp<LayerFE> layerFE;
2567 for (auto& [p, layer] : mLayerFEs) {
2568 if (p == path) {
2569 layerFE = layer;
2570 }
2571 }
2572
2573 if (!layerFE) return nullptr;
2574 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
2575}
2576
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002577Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2578 const auto outputLayer = findOutputLayerForDisplay(display);
2579 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002580}
2581
Patrick Williamsbb25f802022-08-30 23:02:34 +00002582void Layer::updateCloneBufferInfo() {
2583 if (!isClone() || !isClonedFromAlive()) {
2584 return;
2585 }
2586
2587 sp<Layer> clonedFrom = getClonedFrom();
2588 mBufferInfo = clonedFrom->mBufferInfo;
2589 mSidebandStream = clonedFrom->mSidebandStream;
2590 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2591 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2592 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2593
2594 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2595 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2596 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2597 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2598 // the cloned drawingState again.
2599 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2600 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2601 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2602 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2603
2604 cloneDrawingState(clonedFrom.get());
2605
2606 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2607 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2608 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2609 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002610}
chaviw74b03172019-08-19 11:09:03 -07002611
Vishnu Nair3be61902023-04-26 19:47:29 -07002612bool Layer::updateMirrorInfo(const std::deque<Layer*>& cloneRootsPendingUpdates) {
chaviw74b03172019-08-19 11:09:03 -07002613 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2614 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2615 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2616 // that case, we want to delete the reference to the clone since we want it to get
2617 // destroyed. The root, this layer, will still be around since the client can continue
2618 // to hold a reference, but no cloned layers will be displayed.
2619 mClonedChild = nullptr;
Vishnu Nair3be61902023-04-26 19:47:29 -07002620 return true;
chaviw74b03172019-08-19 11:09:03 -07002621 }
2622
2623 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2624 // If the real layer exists and is in current state, add the clone as a child of the root.
2625 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2626 // copied to drawingState for the root layer. So the clonedChild is always removed from
2627 // drawingState and then needs to be added back each traversal.
2628 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2629 addChildToDrawing(mClonedChild);
2630 }
2631
2632 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002633 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002634 mClonedChild->updateClonedRelatives(clonedLayersMap);
Vishnu Nair3be61902023-04-26 19:47:29 -07002635
2636 for (Layer* root : cloneRootsPendingUpdates) {
2637 if (clonedLayersMap.find(sp<Layer>::fromExisting(root)) != clonedLayersMap.end()) {
2638 return false;
2639 }
2640 }
2641 return true;
chaviw74b03172019-08-19 11:09:03 -07002642}
2643
2644void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2645 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2646 // to the clone. If the real layer is no longer alive, continue traversing the children
2647 // since we may be able to pull out other children that are still alive.
2648 if (isClonedFromAlive()) {
2649 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002650 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002651 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002652 }
2653
2654 // The clone layer may have children in drawingState since they may have been created and
2655 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2656 // that already exist, since we can just re-use them.
2657 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2658 // not updated in the regular traversal. They are skipped since the root will lose the
2659 // reference to them when it copies its currentChildren to drawing.
2660 for (sp<Layer>& child : mDrawingChildren) {
2661 child->updateClonedDrawingState(clonedLayersMap);
2662 }
2663}
2664
2665void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2666 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2667 mDrawingChildren.clear();
2668
2669 if (!isClonedFromAlive()) {
2670 return;
2671 }
2672
2673 sp<Layer> clonedFrom = getClonedFrom();
2674 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2675 if (child == mirrorRoot) {
2676 // This is to avoid cyclical mirroring.
2677 continue;
2678 }
2679 sp<Layer> clonedChild = clonedLayersMap[child];
2680 if (clonedChild == nullptr) {
Melody Hsu12ecd082024-04-17 19:03:13 +00002681 clonedChild = child->createClone();
chaviw74b03172019-08-19 11:09:03 -07002682 clonedLayersMap[child] = clonedChild;
2683 }
2684 addChildToDrawing(clonedChild);
2685 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2686 }
2687}
2688
chaviwaf87b3e2019-10-01 16:59:28 -07002689void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2690 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2691 if (cropLayer != nullptr) {
2692 if (clonedLayersMap.count(cropLayer) == 0) {
2693 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2694 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002695 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002696 } else {
2697 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2698 mDrawingState.touchableRegionCrop = clonedCropLayer;
2699 }
2700 }
2701 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2702 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002703 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002704}
2705
2706void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002707 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002708 mDrawingState.zOrderRelatives.clear();
2709
2710 if (!isClonedFromAlive()) {
2711 return;
2712 }
2713
chaviwaf87b3e2019-10-01 16:59:28 -07002714 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002715 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002716 const sp<Layer>& relative = relativeWeak.promote();
2717 if (clonedLayersMap.count(relative) > 0) {
2718 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002719 mDrawingState.zOrderRelatives.add(clonedRelative);
2720 }
2721 }
2722
2723 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2724 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2725 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2726 // still traverse the children, but the layer with the missing relativeOf will not be shown
2727 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002728 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2729 if (clonedLayersMap.count(relativeOf) > 0) {
2730 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002731 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2732 }
2733
chaviwaf87b3e2019-10-01 16:59:28 -07002734 updateClonedInputInfo(clonedLayersMap);
2735
chaviw74b03172019-08-19 11:09:03 -07002736 for (sp<Layer>& child : mDrawingChildren) {
2737 child->updateClonedRelatives(clonedLayersMap);
2738 }
2739}
2740
2741void Layer::addChildToDrawing(const sp<Layer>& layer) {
2742 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002743 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002744}
2745
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002746bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002747 const State& s(mDrawingState);
2748 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2749 return true;
2750 }
2751
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002752 sp<Layer> parent = mDrawingParent.promote();
2753 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002754}
2755
Robert Carr6a0382d2021-07-01 15:57:17 -07002756void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2757 mClonedChild = clonedChild;
2758 mHadClonedChild = true;
Vishnu Nair3be61902023-04-26 19:47:29 -07002759 mFlinger->mLayerMirrorRoots.push_back(this);
Robert Carr6a0382d2021-07-01 15:57:17 -07002760}
2761
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002762bool Layer::setDropInputMode(gui::DropInputMode mode) {
2763 if (mDrawingState.dropInputMode == mode) {
2764 return false;
2765 }
2766 mDrawingState.dropInputMode = mode;
2767 return true;
2768}
2769
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002770void Layer::cloneDrawingState(const Layer* from) {
2771 mDrawingState = from->mDrawingState;
2772 // Skip callback info since they are not applicable for cloned layers.
2773 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002774 // TODO (b/238781169) currently broken for mirror layers because we do not
2775 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002776 mDrawingState.callbackHandles = {};
2777}
2778
Patrick Williamsbb25f802022-08-30 23:02:34 +00002779void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2780 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08002781 const sp<Fence>& releaseFence) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002782 if (!listener) {
2783 return;
2784 }
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002785 SFTRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
liulijuneb489f62022-10-17 22:02:14 +08002786 uint32_t currentMaxAcquiredBufferCount =
2787 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002788 listener->onReleaseBuffer({buffer->getId(), framenumber},
2789 releaseFence ? releaseFence : Fence::NO_FENCE,
2790 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002791}
2792
Melody Hsu793f8362024-01-08 20:00:35 +00002793sp<CallbackHandle> Layer::findCallbackHandle() {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002794 // If we are displayed on multiple displays in a single composition cycle then we would
2795 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2796 // For example we can only use it if all the displays are client comp, and we need
2797 // to merge all the client comp fences. We could do this, but for now we just
2798 // disable the optimization when a layer is composed on multiple displays.
2799 if (mClearClientCompositionFenceOnLayerDisplayed) {
2800 mLastClientCompositionFence = nullptr;
2801 } else {
2802 mClearClientCompositionFenceOnLayerDisplayed = true;
2803 }
2804
2805 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2806 // buffer that was presented on this layer. The first transaction that came in this frame that
2807 // replaced the previous buffer on this layer needs this release fence, because the fence will
2808 // let the client know when that previous buffer is removed from the screen.
2809 //
2810 // Every other transaction on this layer does not need a release fence because no other
2811 // Transactions that were set on this layer this frame are going to have their preceding buffer
2812 // removed from the display this frame.
2813 //
2814 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2815 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2816 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2817 // the previous buffer will be released this frame. The third transaction also contains a
2818 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2819 // transaction will now no longer be presented so it is released immediately and the third
2820 // transaction doesn't need a previous release fence.
2821 sp<CallbackHandle> ch;
2822 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002823 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002824 ch = handle;
2825 break;
2826 }
2827 }
Melody Hsu793f8362024-01-08 20:00:35 +00002828 return ch;
2829}
2830
2831void Layer::prepareReleaseCallbacks(ftl::Future<FenceResult> futureFenceResult,
2832 ui::LayerStack layerStack) {
2833 sp<CallbackHandle> ch = findCallbackHandle();
2834
2835 if (ch != nullptr) {
2836 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2837 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2838 ch->name = mName;
2839 } else {
Melody Hsue4ef87f2024-03-26 23:54:45 +00002840 // If we didn't get a release callback yet (e.g. some scenarios when capturing
2841 // screenshots asynchronously) then make sure we don't drop the fence.
2842 // Older fences for the same layer stack can be dropped when a new fence arrives.
2843 // An assumption here is that RenderEngine performs work sequentially, so an
2844 // incoming fence will not fire before an existing fence.
2845 mAdditionalPreviousReleaseFences.emplace_or_replace(layerStack,
2846 std::move(futureFenceResult));
Melody Hsu793f8362024-01-08 20:00:35 +00002847 }
2848
2849 if (mBufferInfo.mBuffer) {
2850 mPreviouslyPresentedLayerStacks.push_back(layerStack);
2851 }
2852
2853 if (mDrawingState.frameNumber > 0) {
2854 mDrawingState.previousFrameNumber = mDrawingState.frameNumber;
2855 }
2856}
2857
2858void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult,
2859 ui::LayerStack layerStack,
2860 std::function<FenceResult(FenceResult)>&& continuation) {
2861 sp<CallbackHandle> ch = findCallbackHandle();
Alec Mouri9892aac2023-12-11 21:16:59 +00002862
2863 if (!FlagManager::getInstance().screenshot_fence_preservation() && continuation) {
2864 futureFenceResult = ftl::Future(futureFenceResult).then(std::move(continuation)).share();
2865 }
2866
Patrick Williamsbb25f802022-08-30 23:02:34 +00002867 if (ch != nullptr) {
2868 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
Melody Hsu793f8362024-01-08 20:00:35 +00002869 ch->previousSharedReleaseFences.emplace_back(std::move(futureFenceResult));
Patrick Williamsbb25f802022-08-30 23:02:34 +00002870 ch->name = mName;
Alec Mouri9892aac2023-12-11 21:16:59 +00002871 } else if (FlagManager::getInstance().screenshot_fence_preservation()) {
2872 // If we didn't get a release callback yet, e.g. some scenarios when capturing screenshots
2873 // asynchronously, then make sure we don't drop the fence.
Melody Hsu793f8362024-01-08 20:00:35 +00002874 mPreviousReleaseFenceAndContinuations.emplace_back(std::move(futureFenceResult),
2875 std::move(continuation));
Alec Mouri9892aac2023-12-11 21:16:59 +00002876 std::vector<FenceAndContinuation> mergedFences;
2877 sp<Fence> prevFence = nullptr;
2878 // For a layer that's frequently screenshotted, try to merge fences to make sure we don't
2879 // grow unbounded.
Melody Hsu793f8362024-01-08 20:00:35 +00002880 for (const auto& futureAndContinuation : mPreviousReleaseFenceAndContinuations) {
2881 auto result = futureAndContinuation.future.wait_for(0s);
Alec Mouri9892aac2023-12-11 21:16:59 +00002882 if (result != std::future_status::ready) {
Melody Hsu793f8362024-01-08 20:00:35 +00002883 mergedFences.emplace_back(futureAndContinuation);
Alec Mouri9892aac2023-12-11 21:16:59 +00002884 continue;
2885 }
2886
Melody Hsu793f8362024-01-08 20:00:35 +00002887 mergeFence(getDebugName(),
2888 futureAndContinuation.chain().get().value_or(Fence::NO_FENCE), prevFence);
Alec Mouri9892aac2023-12-11 21:16:59 +00002889 }
2890 if (prevFence != nullptr) {
2891 mergedFences.emplace_back(ftl::yield(FenceResult(std::move(prevFence))).share());
2892 }
2893
Melody Hsu793f8362024-01-08 20:00:35 +00002894 mPreviousReleaseFenceAndContinuations.swap(mergedFences);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002895 }
Alec Mouri9892aac2023-12-11 21:16:59 +00002896
Vishnu Nair316b7f42023-10-13 23:44:46 +00002897 if (mBufferInfo.mBuffer) {
2898 mPreviouslyPresentedLayerStacks.push_back(layerStack);
2899 }
Alec Mouri21d94322023-10-17 19:51:39 +00002900
2901 if (mDrawingState.frameNumber > 0) {
2902 mDrawingState.previousFrameNumber = mDrawingState.frameNumber;
2903 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002904}
2905
Patrick Williamsbb25f802022-08-30 23:02:34 +00002906void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2907 for (const auto& handle : mDrawingState.callbackHandles) {
Melody Hsu9af30702024-04-17 18:23:43 +00002908 handle->transformHint = mTransformHint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002909 handle->dequeueReadyTime = dequeueReadyTime;
2910 handle->currentMaxAcquiredBufferCount =
2911 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002912 SFTRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2913 handle->previousReleaseCallbackId.framenumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002914 }
2915
2916 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002917 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002918 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2919 break;
2920 }
2921 }
2922
Pascal Mütschardd56514e2024-05-24 17:37:13 +02002923 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002924 mDrawingState.callbackHandles = {};
2925}
2926
2927bool Layer::willPresentCurrentTransaction() const {
2928 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2929 return (getSidebandStreamChanged() || getAutoRefresh() ||
2930 (mDrawingState.modified &&
2931 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2932}
2933
2934bool Layer::setTransform(uint32_t transform) {
2935 if (mDrawingState.bufferTransform == transform) return false;
2936 mDrawingState.bufferTransform = transform;
2937 mDrawingState.modified = true;
2938 setTransactionFlags(eTransactionNeeded);
2939 return true;
2940}
2941
2942bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
2943 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
2944 mDrawingState.sequence++;
2945 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
2946 mDrawingState.modified = true;
2947 setTransactionFlags(eTransactionNeeded);
2948 return true;
2949}
2950
2951bool Layer::setBufferCrop(const Rect& bufferCrop) {
2952 if (mDrawingState.bufferCrop == bufferCrop) return false;
2953
2954 mDrawingState.sequence++;
2955 mDrawingState.bufferCrop = bufferCrop;
2956
2957 mDrawingState.modified = true;
2958 setTransactionFlags(eTransactionNeeded);
2959 return true;
2960}
2961
2962bool Layer::setDestinationFrame(const Rect& destinationFrame) {
2963 if (mDrawingState.destinationFrame == destinationFrame) return false;
2964
2965 mDrawingState.sequence++;
2966 mDrawingState.destinationFrame = destinationFrame;
2967
2968 mDrawingState.modified = true;
2969 setTransactionFlags(eTransactionNeeded);
2970 return true;
2971}
2972
2973// Translate destination frame into scale and position. If a destination frame is not set, use the
2974// provided scale and position
2975bool Layer::updateGeometry() {
2976 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
2977 mDrawingState.destinationFrame.isEmpty()) {
2978 // If destination frame is not set, use the requested transform set via
2979 // Layer::setPosition and Layer::setMatrix.
2980 return assignTransform(&mDrawingState.transform, mRequestedTransform);
2981 }
2982
2983 Rect destRect = mDrawingState.destinationFrame;
2984 int32_t destW = destRect.width();
2985 int32_t destH = destRect.height();
2986 if (destRect.left < 0) {
2987 destRect.left = 0;
2988 destRect.right = destW;
2989 }
2990 if (destRect.top < 0) {
2991 destRect.top = 0;
2992 destRect.bottom = destH;
2993 }
2994
2995 if (!mDrawingState.buffer) {
2996 ui::Transform t;
2997 t.set(destRect.left, destRect.top);
2998 return assignTransform(&mDrawingState.transform, t);
2999 }
3000
3001 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
3002 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
3003 // Undo any transformations on the buffer.
3004 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
3005 std::swap(bufferWidth, bufferHeight);
3006 }
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003007 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003008 if (mDrawingState.transformToDisplayInverse) {
3009 if (invTransform & ui::Transform::ROT_90) {
3010 std::swap(bufferWidth, bufferHeight);
3011 }
3012 }
3013
3014 float sx = destW / static_cast<float>(bufferWidth);
3015 float sy = destH / static_cast<float>(bufferHeight);
3016 ui::Transform t;
3017 t.set(sx, 0, 0, sy);
3018 t.set(destRect.left, destRect.top);
3019 return assignTransform(&mDrawingState.transform, t);
3020}
3021
3022bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
3023 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
3024 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
3025 return false;
3026 }
3027
3028 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
3029
3030 mDrawingState.sequence++;
3031 mDrawingState.modified = true;
3032 setTransactionFlags(eTransactionNeeded);
3033
3034 return true;
3035}
3036
3037bool Layer::setPosition(float x, float y) {
3038 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3039 return false;
3040 }
3041
3042 mRequestedTransform.set(x, y);
3043
3044 mDrawingState.sequence++;
3045 mDrawingState.modified = true;
3046 setTransactionFlags(eTransactionNeeded);
3047
3048 return true;
3049}
3050
Dorin Drimuse5374e52023-08-02 17:52:43 +00003051void Layer::releasePreviousBuffer() {
3052 mReleasePreviousBuffer = true;
3053 if (!mBufferInfo.mBuffer ||
3054 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3055 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3056 // If mDrawingState has a buffer, and we are about to update again
3057 // before swapping to drawing state, then the first buffer will be
3058 // dropped and we should decrement the pending buffer count and
3059 // call any release buffer callbacks if set.
3060 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3061 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3062 mDrawingState.acquireFence);
3063 decrementPendingBufferCount();
3064 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3065 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3066 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX, systemTime());
3067 mDrawingState.bufferSurfaceFrameTX.reset();
3068 }
3069 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3070 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3071 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3072 mLastClientCompositionFence);
3073 mLastClientCompositionFence = nullptr;
3074 }
3075}
3076
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003077void Layer::resetDrawingStateBufferInfo() {
3078 mDrawingState.producerId = 0;
3079 mDrawingState.frameNumber = 0;
Alec Mouri21d94322023-10-17 19:51:39 +00003080 mDrawingState.previousFrameNumber = 0;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003081 mDrawingState.releaseBufferListener = nullptr;
3082 mDrawingState.buffer = nullptr;
3083 mDrawingState.acquireFence = sp<Fence>::make(-1);
3084 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3085 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3086 mDrawingState.releaseBufferEndpoint = nullptr;
3087}
3088
Patrick Williamsbb25f802022-08-30 23:02:34 +00003089bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3090 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
Nergi Rahardi39f510f2024-05-23 15:16:54 +09003091 bool isAutoTimestamp, const FrameTimelineInfo& info) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003092 SFTRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003093
3094 const bool frameNumberChanged =
3095 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3096 const uint64_t frameNumber =
3097 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003098 SFTRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003099
3100 if (mDrawingState.buffer) {
Dorin Drimuse5374e52023-08-02 17:52:43 +00003101 releasePreviousBuffer();
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003102 } else if (buffer) {
Vishnu Nairc09c0232023-03-02 03:22:35 +00003103 // if we are latching a buffer for the first time then clear the mLastLatchTime since
3104 // we don't want to incorrectly classify a frame if we miss the desired present time.
3105 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003106 }
3107
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003108 mDrawingState.desiredPresentTime = desiredPresentTime;
3109 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3110 mDrawingState.latchedVsyncId = info.vsyncId;
Ady Abraham55269162023-05-09 11:26:06 -07003111 mDrawingState.useVsyncIdForRefreshRateSelection = info.useForRefreshRateSelection;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003112 mDrawingState.modified = true;
3113 if (!buffer) {
3114 resetDrawingStateBufferInfo();
3115 setTransactionFlags(eTransactionNeeded);
3116 mDrawingState.bufferSurfaceFrameTX = nullptr;
3117 setFrameTimelineVsyncForBufferlessTransaction(info, postTime);
3118 return true;
Dorin Drimuse5374e52023-08-02 17:52:43 +00003119 } else {
3120 // release sideband stream if it exists and a non null buffer is being set
3121 if (mDrawingState.sidebandStream != nullptr) {
Dorin Drimus66ed1c42023-09-27 13:10:16 +00003122 setSidebandStream(nullptr, info, postTime);
Dorin Drimuse5374e52023-08-02 17:52:43 +00003123 }
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003124 }
3125
Vishnu Naird1f74982023-06-15 20:16:51 -07003126 if ((mDrawingState.producerId > bufferData.producerId) ||
3127 ((mDrawingState.producerId == bufferData.producerId) &&
3128 (mDrawingState.frameNumber > frameNumber))) {
3129 ALOGE("Out of order buffers detected for %s producedId=%d frameNumber=%" PRIu64
3130 " -> producedId=%d frameNumber=%" PRIu64,
3131 getDebugName(), mDrawingState.producerId, mDrawingState.frameNumber,
3132 bufferData.producerId, frameNumber);
3133 TransactionTraceWriter::getInstance().invoke("out_of_order_buffers_", /*overwrite=*/false);
3134 }
3135
liulijuneb489f62022-10-17 22:02:14 +08003136 mDrawingState.producerId = bufferData.producerId;
Vishnu Nair63221212023-04-06 15:17:37 -07003137 mDrawingState.barrierProducerId =
3138 std::max(mDrawingState.producerId, mDrawingState.barrierProducerId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003139 mDrawingState.frameNumber = frameNumber;
Vishnu Nair63221212023-04-06 15:17:37 -07003140 mDrawingState.barrierFrameNumber =
3141 std::max(mDrawingState.frameNumber, mDrawingState.barrierFrameNumber);
3142
Patrick Williamsbb25f802022-08-30 23:02:34 +00003143 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3144 mDrawingState.buffer = std::move(buffer);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003145 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3146 ? bufferData.acquireFence
3147 : Fence::NO_FENCE;
3148 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3149 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3150 // We latched this buffer unsiganled, so we need to pass the acquire fence
3151 // on the callback instead of just the acquire time, since it's unknown at
3152 // this point.
3153 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3154 } else {
3155 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3156 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003157 setTransactionFlags(eTransactionNeeded);
3158
3159 const int32_t layerId = getSequence();
3160 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3161 mOwnerUid, postTime, getGameMode());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003162
Patrick Williamsbb25f802022-08-30 23:02:34 +00003163 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3164
Nergi Rahardi39f510f2024-05-23 15:16:54 +09003165 if (bufferData.dequeueTime > 0) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003166 const uint64_t bufferId = mDrawingState.buffer->getId();
3167 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
Nergi Rahardi39f510f2024-05-23 15:16:54 +09003168 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber,
3169 bufferData.dequeueTime,
Patrick Williamsbb25f802022-08-30 23:02:34 +00003170 FrameTracer::FrameEvent::DEQUEUE);
3171 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3172 FrameTracer::FrameEvent::QUEUE);
3173 }
3174
3175 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
Arthur Hungc70bee22023-06-02 01:35:52 +00003176
3177 // If the layer had been updated a TextureView, this would make sure the present time could be
3178 // same to TextureView update when it's a small dirty, and get the correct heuristic rate.
Jerry Chang36678002023-11-29 16:56:17 +00003179 if (mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +00003180 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
3181 mUsedVsyncIdForRefreshRateSelection = true;
3182 }
3183 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003184 return true;
3185}
3186
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003187void Layer::setDesiredPresentTime(nsecs_t desiredPresentTime, bool isAutoTimestamp) {
3188 mDrawingState.desiredPresentTime = desiredPresentTime;
3189 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3190}
3191
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003192void Layer::recordLayerHistoryBufferUpdate(const scheduler::LayerProps& layerProps, nsecs_t now) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003193 SFTRACE_CALL();
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003194 const nsecs_t presentTime = [&] {
Ady Abraham55269162023-05-09 11:26:06 -07003195 if (!mDrawingState.isAutoTimestamp) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003196 SFTRACE_FORMAT_INSTANT("desiredPresentTime");
Ady Abraham55269162023-05-09 11:26:06 -07003197 return mDrawingState.desiredPresentTime;
3198 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003199
Ady Abraham55269162023-05-09 11:26:06 -07003200 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
3201 const auto prediction =
3202 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3203 mDrawingState.latchedVsyncId);
3204 if (prediction.has_value()) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003205 SFTRACE_FORMAT_INSTANT("predictedPresentTime");
Arthur Hungc70bee22023-06-02 01:35:52 +00003206 mMaxTimeForUseVsyncId = prediction->presentTime +
3207 scheduler::LayerHistory::kMaxPeriodForHistory.count();
Ady Abraham55269162023-05-09 11:26:06 -07003208 return prediction->presentTime;
3209 }
3210 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003211
Jerry Chang36678002023-11-29 16:56:17 +00003212 if (!mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +00003213 return static_cast<nsecs_t>(0);
3214 }
3215
3216 // If the layer is not an application and didn't set an explicit rate or desiredPresentTime,
3217 // return "0" to tell the layer history that it will use the max refresh rate without
3218 // calculating the adaptive rate.
3219 if (mWindowType != WindowInfo::Type::APPLICATION &&
3220 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
3221 return static_cast<nsecs_t>(0);
3222 }
3223
3224 // Return the valid present time only when the layer potentially updated a TextureView so
3225 // LayerHistory could heuristically calculate the rate if the UI is continually updating.
3226 if (mUsedVsyncIdForRefreshRateSelection) {
3227 const auto prediction =
3228 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3229 mDrawingState.latchedVsyncId);
3230 if (prediction.has_value()) {
3231 if (mMaxTimeForUseVsyncId >= prediction->presentTime) {
3232 return prediction->presentTime;
3233 }
3234 mUsedVsyncIdForRefreshRateSelection = false;
3235 }
3236 }
3237
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003238 return static_cast<nsecs_t>(0);
3239 }();
Ady Abraham55269162023-05-09 11:26:06 -07003240
3241 if (ATRACE_ENABLED() && presentTime > 0) {
3242 const auto presentIn = TimePoint::fromNs(presentTime) - TimePoint::now();
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003243 SFTRACE_FORMAT_INSTANT("presentIn %s", to_string(presentIn).c_str());
Ady Abraham55269162023-05-09 11:26:06 -07003244 }
3245
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003246 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003247 scheduler::LayerHistory::LayerUpdateType::Buffer);
3248}
3249
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003250void Layer::recordLayerHistoryAnimationTx(const scheduler::LayerProps& layerProps, nsecs_t now) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003251 const nsecs_t presentTime =
3252 mDrawingState.isAutoTimestamp ? 0 : mDrawingState.desiredPresentTime;
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003253 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003254 scheduler::LayerHistory::LayerUpdateType::AnimationTX);
3255}
3256
Patrick Williamsbb25f802022-08-30 23:02:34 +00003257bool Layer::setDataspace(ui::Dataspace dataspace) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003258 if (mDrawingState.dataspace == dataspace) return false;
3259 mDrawingState.dataspace = dataspace;
3260 mDrawingState.modified = true;
3261 setTransactionFlags(eTransactionNeeded);
3262 return true;
3263}
3264
John Reck68796592023-01-25 13:47:12 -05003265bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
Sally Qi963049b2023-03-23 14:06:21 -07003266 if (mDrawingState.currentHdrSdrRatio == currentBufferRatio &&
3267 mDrawingState.desiredHdrSdrRatio == desiredRatio)
John Reck68796592023-01-25 13:47:12 -05003268 return false;
Sally Qi963049b2023-03-23 14:06:21 -07003269 mDrawingState.currentHdrSdrRatio = currentBufferRatio;
3270 mDrawingState.desiredHdrSdrRatio = desiredRatio;
John Reck68796592023-01-25 13:47:12 -05003271 mDrawingState.modified = true;
3272 setTransactionFlags(eTransactionNeeded);
3273 return true;
3274}
3275
Alec Mouri1b0d4e12024-02-12 22:27:19 +00003276bool Layer::setDesiredHdrHeadroom(float desiredRatio) {
3277 if (mDrawingState.desiredHdrSdrRatio == desiredRatio) return false;
3278 mDrawingState.desiredHdrSdrRatio = desiredRatio;
3279 mDrawingState.modified = true;
3280 setTransactionFlags(eTransactionNeeded);
3281 return true;
3282}
3283
Alec Mourif4af03e2023-02-11 00:25:24 +00003284bool Layer::setCachingHint(gui::CachingHint cachingHint) {
3285 if (mDrawingState.cachingHint == cachingHint) return false;
3286 mDrawingState.cachingHint = cachingHint;
3287 mDrawingState.modified = true;
3288 setTransactionFlags(eTransactionNeeded);
3289 return true;
3290}
3291
Patrick Williamsbb25f802022-08-30 23:02:34 +00003292bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3293 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3294 mDrawingState.hdrMetadata = hdrMetadata;
3295 mDrawingState.modified = true;
3296 setTransactionFlags(eTransactionNeeded);
3297 return true;
3298}
3299
3300bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Sally Qi2b1b4292023-03-14 16:47:39 +00003301 if (mDrawingState.surfaceDamageRegion.hasSameRects(surfaceDamage)) return false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003302 mDrawingState.surfaceDamageRegion = surfaceDamage;
3303 mDrawingState.modified = true;
3304 setTransactionFlags(eTransactionNeeded);
Arthur Hung69f95222023-10-04 07:39:02 +00003305 setIsSmallDirty(surfaceDamage, getTransform());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003306 return true;
3307}
3308
3309bool Layer::setApi(int32_t api) {
3310 if (mDrawingState.api == api) return false;
3311 mDrawingState.api = api;
3312 mDrawingState.modified = true;
3313 setTransactionFlags(eTransactionNeeded);
3314 return true;
3315}
3316
Dorin Drimuse5374e52023-08-02 17:52:43 +00003317bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream, const FrameTimelineInfo& info,
3318 nsecs_t postTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003319 if (mDrawingState.sidebandStream == sidebandStream) return false;
3320
3321 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3322 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3323 } else if (sidebandStream != nullptr) {
3324 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3325 }
3326
3327 mDrawingState.sidebandStream = sidebandStream;
3328 mDrawingState.modified = true;
Dorin Drimuse5374e52023-08-02 17:52:43 +00003329 if (sidebandStream != nullptr && mDrawingState.buffer != nullptr) {
3330 releasePreviousBuffer();
3331 resetDrawingStateBufferInfo();
3332 mDrawingState.bufferSurfaceFrameTX = nullptr;
3333 setFrameTimelineVsyncForBufferlessTransaction(info, postTime);
3334 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003335 setTransactionFlags(eTransactionNeeded);
3336 if (!mSidebandStreamChanged.exchange(true)) {
3337 // mSidebandStreamChanged was false
3338 mFlinger->onLayerUpdate();
3339 }
3340 return true;
3341}
3342
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003343bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3344 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003345 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3346 if (handles.empty()) {
3347 mReleasePreviousBuffer = false;
3348 return false;
3349 }
3350
Pascal Muetschard81cef292023-02-06 12:18:52 +01003351 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003352 for (const auto& handle : handles) {
3353 // If this transaction set a buffer on this layer, release its previous buffer
3354 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3355
3356 // If this layer will be presented in this frame
3357 if (willPresent) {
3358 // If this transaction set an acquire fence on this layer, set its acquire time
3359 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3360 handle->frameNumber = mDrawingState.frameNumber;
Alec Mouri21d94322023-10-17 19:51:39 +00003361 handle->previousFrameNumber = mDrawingState.previousFrameNumber;
Melody Hsu793f8362024-01-08 20:00:35 +00003362 if (FlagManager::getInstance().ce_fence_promise() &&
Alec Mouri9892aac2023-12-11 21:16:59 +00003363 mPreviousReleaseBufferEndpoint == handle->listener) {
Melody Hsue4ef87f2024-03-26 23:54:45 +00003364 // Add fence from previous screenshot now so that it can be dispatched to the
Alec Mouri9892aac2023-12-11 21:16:59 +00003365 // client.
Melody Hsue4ef87f2024-03-26 23:54:45 +00003366 for (auto& [_, future] : mAdditionalPreviousReleaseFences) {
3367 handle->previousReleaseFences.emplace_back(std::move(future));
Alec Mouri9892aac2023-12-11 21:16:59 +00003368 }
3369 mAdditionalPreviousReleaseFences.clear();
Melody Hsu793f8362024-01-08 20:00:35 +00003370 } else if (FlagManager::getInstance().screenshot_fence_preservation() &&
3371 mPreviousReleaseBufferEndpoint == handle->listener) {
3372 // Add fences from previous screenshots now so that they can be dispatched to the
3373 // client.
3374 for (const auto& futureAndContinution : mPreviousReleaseFenceAndContinuations) {
3375 handle->previousSharedReleaseFences.emplace_back(futureAndContinution.chain());
3376 }
3377 mPreviousReleaseFenceAndContinuations.clear();
Alec Mouri9892aac2023-12-11 21:16:59 +00003378 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003379 // Store so latched time and release fence can be set
3380 mDrawingState.callbackHandles.push_back(handle);
3381
3382 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01003383 // Queue this handle to be notified below.
3384 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003385 }
3386 }
3387
Pascal Muetschard81cef292023-02-06 12:18:52 +01003388 if (!remainingHandles.empty()) {
3389 // Notify the transaction completed threads these handles are done. These are only the
3390 // handles that were not added to the mDrawingState, which will be notified later.
Pascal Mütschardd56514e2024-05-24 17:37:13 +02003391 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles);
Pascal Muetschard81cef292023-02-06 12:18:52 +01003392 }
3393
Patrick Williamsbb25f802022-08-30 23:02:34 +00003394 mReleasePreviousBuffer = false;
3395 mCallbackHandleAcquireTimeOrFence = -1;
3396
3397 return willPresent;
3398}
3399
3400Rect Layer::getBufferSize(const State& /*s*/) const {
3401 // for buffer state layers we use the display frame size as the buffer size.
3402
3403 if (mBufferInfo.mBuffer == nullptr) {
3404 return Rect::INVALID_RECT;
3405 }
3406
3407 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3408 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3409
3410 // Undo any transformations on the buffer and return the result.
3411 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3412 std::swap(bufWidth, bufHeight);
3413 }
3414
3415 if (getTransformToDisplayInverse()) {
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003416 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003417 if (invTransform & ui::Transform::ROT_90) {
3418 std::swap(bufWidth, bufHeight);
3419 }
3420 }
3421
3422 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3423}
3424
3425FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3426 if (mBufferInfo.mBuffer == nullptr) {
3427 return parentBounds;
3428 }
3429
3430 return getBufferSize(getDrawingState()).toFloatRect();
3431}
3432
3433bool Layer::fenceHasSignaled() const {
3434 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3435 return true;
3436 }
3437
3438 const bool fenceSignaled =
3439 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3440 if (!fenceSignaled) {
3441 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3442 TimeStats::LatchSkipReason::LateAcquire);
3443 }
3444
3445 return fenceSignaled;
3446}
3447
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003448void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003449 for (const auto& handle : mDrawingState.callbackHandles) {
3450 handle->refreshStartTime = refreshStartTime;
3451 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003452}
3453
3454void Layer::setAutoRefresh(bool autoRefresh) {
3455 mDrawingState.autoRefresh = autoRefresh;
3456}
3457
3458bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3459 // 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 +00003460 auto* snapshot = editLayerSnapshot();
3461 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003462
3463 if (mSidebandStreamChanged.exchange(false)) {
3464 const State& s(getDrawingState());
3465 // mSidebandStreamChanged was true
3466 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003467 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003468 if (mSidebandStream != nullptr) {
3469 setTransactionFlags(eTransactionNeeded);
3470 mFlinger->setTransactionFlags(eTraversalNeeded);
3471 }
3472 recomputeVisibleRegions = true;
3473
3474 return true;
3475 }
3476 return false;
3477}
3478
3479bool Layer::hasFrameUpdate() const {
3480 const State& c(getDrawingState());
3481 return (mDrawingStateModified || mDrawingState.modified) &&
3482 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3483}
3484
Vishnu Naird47bcee2023-02-24 18:08:51 +00003485void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003486 const State& s(getDrawingState());
3487
3488 if (!s.buffer) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003489 if (bgColorOnly || mBufferInfo.mBuffer) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003490 for (auto& handle : mDrawingState.callbackHandles) {
3491 handle->latchTime = latchTime;
3492 }
3493 }
3494 return;
3495 }
3496
3497 for (auto& handle : mDrawingState.callbackHandles) {
3498 if (handle->frameNumber == mDrawingState.frameNumber) {
3499 handle->latchTime = latchTime;
3500 }
3501 }
3502
3503 const int32_t layerId = getSequence();
3504 const uint64_t bufferId = mDrawingState.buffer->getId();
3505 const uint64_t frameNumber = mDrawingState.frameNumber;
3506 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3507 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3508 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3509
3510 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3511 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3512 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3513 FrameTracer::FrameEvent::LATCH);
3514
3515 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3516 if (bufferSurfaceFrame != nullptr &&
3517 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3518 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3519 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3520 // are processing the next state.
3521 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3522 mDrawingState.acquireFenceTime->getSignalTime(),
3523 latchTime);
3524 mDrawingState.bufferSurfaceFrameTX.reset();
3525 }
3526
3527 std::deque<sp<CallbackHandle>> remainingHandles;
3528 mFlinger->getTransactionCallbackInvoker()
3529 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3530 mDrawingState.callbackHandles = remainingHandles;
3531
3532 mDrawingStateModified = false;
3533}
3534
3535void Layer::gatherBufferInfo() {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003536 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3537 mPreviousReleaseBufferEndpoint = mBufferInfo.mReleaseBufferEndpoint;
3538 if (!mDrawingState.buffer) {
3539 mBufferInfo = {};
3540 return;
3541 }
3542
3543 if ((!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer))) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003544 decrementPendingBufferCount();
3545 }
3546
Patrick Williamsbb25f802022-08-30 23:02:34 +00003547 mBufferInfo.mBuffer = mDrawingState.buffer;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003548 mBufferInfo.mReleaseBufferEndpoint = mDrawingState.releaseBufferEndpoint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003549 mBufferInfo.mFence = mDrawingState.acquireFence;
3550 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3551 mBufferInfo.mPixelFormat =
3552 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3553 mBufferInfo.mFrameLatencyNeeded = true;
3554 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3555 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3556 mBufferInfo.mFence = mDrawingState.acquireFence;
3557 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3558 auto lastDataspace = mBufferInfo.mDataspace;
3559 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
Alec Mouri74c7ae12023-03-26 02:57:47 +00003560 if (mBufferInfo.mBuffer != nullptr) {
3561 auto& mapper = GraphicBufferMapper::get();
3562 // TODO: We should measure if it's faster to do a blind write if we're on newer api levels
3563 // and don't need to possibly remaps buffers.
3564 ui::Dataspace dataspace = ui::Dataspace::UNKNOWN;
3565 status_t err = OK;
3566 {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003567 SFTRACE_NAME("getDataspace");
Alec Mouri74c7ae12023-03-26 02:57:47 +00003568 err = mapper.getDataspace(mBufferInfo.mBuffer->getBuffer()->handle, &dataspace);
3569 }
3570 if (err != OK || dataspace != mBufferInfo.mDataspace) {
3571 {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003572 SFTRACE_NAME("setDataspace");
Alec Mouri74c7ae12023-03-26 02:57:47 +00003573 err = mapper.setDataspace(mBufferInfo.mBuffer->getBuffer()->handle,
3574 static_cast<ui::Dataspace>(mBufferInfo.mDataspace));
3575 }
3576
3577 // Some GPU drivers may cache gralloc metadata which means before we composite we need
3578 // to upsert RenderEngine's caches. Put in a special workaround to be backwards
3579 // compatible with old vendors, with a ticking clock.
3580 static const int32_t kVendorVersion =
Alec Mouri8a06fb72023-11-16 22:07:13 +00003581 base::GetIntProperty("ro.board.api_level", __ANDROID_API_FUTURE__);
Alec Mouri74c7ae12023-03-26 02:57:47 +00003582 if (const auto format =
3583 static_cast<aidl::android::hardware::graphics::common::PixelFormat>(
3584 mBufferInfo.mBuffer->getPixelFormat());
3585 err == OK && kVendorVersion < __ANDROID_API_U__ &&
3586 (format ==
3587 aidl::android::hardware::graphics::common::PixelFormat::
3588 IMPLEMENTATION_DEFINED ||
3589 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_420_888 ||
3590 format == aidl::android::hardware::graphics::common::PixelFormat::YV12 ||
3591 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_P010)) {
3592 mBufferInfo.mBuffer->remapBuffer();
3593 }
3594 }
3595 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003596 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003597 mFlinger->mHdrLayerInfoChanged = true;
3598 }
Sally Qi963049b2023-03-23 14:06:21 -07003599 if (mBufferInfo.mDesiredHdrSdrRatio != mDrawingState.desiredHdrSdrRatio) {
3600 mBufferInfo.mDesiredHdrSdrRatio = mDrawingState.desiredHdrSdrRatio;
John Reck68796592023-01-25 13:47:12 -05003601 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003602 }
3603 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3604 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3605 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3606 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3607 mBufferInfo.mApi = mDrawingState.api;
3608 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003609}
3610
3611Rect Layer::computeBufferCrop(const State& s) {
3612 if (s.buffer && !s.bufferCrop.isEmpty()) {
3613 Rect bufferCrop;
3614 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3615 return bufferCrop;
3616 } else if (s.buffer) {
3617 return s.buffer->getBounds();
3618 } else {
3619 return s.bufferCrop;
3620 }
3621}
3622
Melody Hsu12ecd082024-04-17 19:03:13 +00003623sp<Layer> Layer::createClone() {
Kean Mariotti4ba343c2023-04-19 13:31:02 +00003624 surfaceflinger::LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0,
3625 LayerMetadata());
Patrick Williams83f36b22022-09-14 17:57:35 +00003626 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003627 return layer;
3628}
3629
Patrick Williamsbb25f802022-08-30 23:02:34 +00003630void Layer::decrementPendingBufferCount() {
3631 int32_t pendingBuffers = --mPendingBufferTransactions;
3632 tracePendingBufferCount(pendingBuffers);
3633}
3634
3635void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003636 SFTRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003637}
3638
3639/*
3640 * We don't want to send the layer's transform to input, but rather the
3641 * parent's transform. This is because Layer's transform is
3642 * information about how the buffer is placed on screen. The parent's
3643 * transform makes more sense to send since it's information about how the
3644 * layer is placed on screen. This transform is used by input to determine
3645 * how to go from screen space back to window space.
3646 */
3647ui::Transform Layer::getInputTransform() const {
3648 if (!hasBufferOrSidebandStream()) {
3649 return getTransform();
3650 }
3651 sp<Layer> parent = mDrawingParent.promote();
3652 if (parent == nullptr) {
3653 return ui::Transform();
3654 }
3655
3656 return parent->getTransform();
3657}
3658
3659/**
Vishnu Nairfed7c122023-03-18 01:54:43 +00003660 * Returns the bounds used to fill the input frame and the touchable region.
3661 *
Patrick Williamsbb25f802022-08-30 23:02:34 +00003662 * Similar to getInputTransform, we need to update the bounds to include the transform.
3663 * This is because bounds don't include the buffer transform, where the input assumes
3664 * that's already included.
3665 */
Vishnu Nairfed7c122023-03-18 01:54:43 +00003666std::pair<FloatRect, bool> Layer::getInputBounds(bool fillParentBounds) const {
3667 Rect croppedBufferSize = getCroppedBufferSize(getDrawingState());
3668 FloatRect inputBounds = croppedBufferSize.toFloatRect();
3669 if (hasBufferOrSidebandStream() && croppedBufferSize.isValid() &&
3670 mDrawingState.transform.getType() != ui::Transform::IDENTITY) {
3671 inputBounds = mDrawingState.transform.transform(inputBounds);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003672 }
3673
Vishnu Nairfed7c122023-03-18 01:54:43 +00003674 bool inputBoundsValid = croppedBufferSize.isValid();
3675 if (!inputBoundsValid) {
3676 /**
3677 * Input bounds are based on the layer crop or buffer size. But if we are using
3678 * the layer bounds as the input bounds (replaceTouchableRegionWithCrop flag) then
3679 * we can use the parent bounds as the input bounds if the layer does not have buffer
3680 * or a crop. We want to unify this logic but because of compat reasons we cannot always
3681 * use the parent bounds. A layer without a buffer can get input. So when a window is
3682 * initially added, its touchable region can fill its parent layer bounds and that can
3683 * have negative consequences.
3684 */
3685 inputBounds = fillParentBounds ? mBounds : FloatRect{};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003686 }
Vishnu Nairfed7c122023-03-18 01:54:43 +00003687
3688 // Clamp surface inset to the input bounds.
3689 const float inset = static_cast<float>(mDrawingState.inputInfo.surfaceInset);
3690 const float xSurfaceInset = std::clamp(inset, 0.f, inputBounds.getWidth() / 2.f);
3691 const float ySurfaceInset = std::clamp(inset, 0.f, inputBounds.getHeight() / 2.f);
3692
3693 // Apply the insets to the input bounds.
3694 inputBounds.left += xSurfaceInset;
3695 inputBounds.top += ySurfaceInset;
3696 inputBounds.right -= xSurfaceInset;
3697 inputBounds.bottom -= ySurfaceInset;
3698
3699 return {inputBounds, inputBoundsValid};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003700}
3701
Ady Abraham005398b2023-06-05 13:59:41 -07003702bool Layer::isSimpleBufferUpdate(const layer_state_t& s) const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003703 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3704
3705 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3706 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3707 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
Ady Abrahambb1ad762024-03-27 18:31:28 -07003708 layer_state_t::eLayerStackChanged | layer_state_t::eReparent |
3709 (FlagManager::getInstance().latch_unsignaled_with_auto_refresh_changed()
3710 ? 0
3711 : layer_state_t::eAutoRefreshChanged);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003712
Patrick Williamsbb25f802022-08-30 23:02:34 +00003713 if ((s.what & requiredFlags) != requiredFlags) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003714 SFTRACE_FORMAT_INSTANT("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3715 (s.what | requiredFlags) & ~s.what);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003716 return false;
3717 }
3718
3719 if (s.what & deniedFlags) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003720 SFTRACE_FORMAT_INSTANT("%s: false [has denied flags 0x%" PRIx64 "]", __func__,
3721 s.what & deniedFlags);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003722 return false;
3723 }
3724
Patrick Williamsbb25f802022-08-30 23:02:34 +00003725 if (s.what & layer_state_t::ePositionChanged) {
3726 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003727 SFTRACE_FORMAT_INSTANT("%s: false [ePositionChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003728 return false;
3729 }
3730 }
3731
3732 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003733 if (mDrawingState.color.a != s.color.a) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003734 SFTRACE_FORMAT_INSTANT("%s: false [eAlphaChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003735 return false;
3736 }
3737 }
3738
3739 if (s.what & layer_state_t::eColorTransformChanged) {
3740 if (mDrawingState.colorTransform != s.colorTransform) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003741 SFTRACE_FORMAT_INSTANT("%s: false [eColorTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003742 return false;
3743 }
3744 }
3745
3746 if (s.what & layer_state_t::eBackgroundColorChanged) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003747 if (mDrawingState.bgColorLayer || s.bgColor.a != 0) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003748 SFTRACE_FORMAT_INSTANT("%s: false [eBackgroundColorChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003749 return false;
3750 }
3751 }
3752
3753 if (s.what & layer_state_t::eMatrixChanged) {
3754 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3755 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3756 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3757 mRequestedTransform.dsdy() != s.matrix.dsdy) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003758 SFTRACE_FORMAT_INSTANT("%s: false [eMatrixChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003759 return false;
3760 }
3761 }
3762
3763 if (s.what & layer_state_t::eCornerRadiusChanged) {
3764 if (mDrawingState.cornerRadius != s.cornerRadius) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003765 SFTRACE_FORMAT_INSTANT("%s: false [eCornerRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003766 return false;
3767 }
3768 }
3769
3770 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3771 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003772 SFTRACE_FORMAT_INSTANT("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003773 return false;
3774 }
3775 }
3776
Vishnu Nairbbceb462022-10-10 04:52:13 +00003777 if (s.what & layer_state_t::eBufferTransformChanged) {
3778 if (mDrawingState.bufferTransform != s.bufferTransform) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003779 SFTRACE_FORMAT_INSTANT("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003780 return false;
3781 }
3782 }
3783
3784 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3785 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003786 SFTRACE_FORMAT_INSTANT("%s: false [eTransformToDisplayInverseChanged changed]",
3787 __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003788 return false;
3789 }
3790 }
3791
3792 if (s.what & layer_state_t::eCropChanged) {
3793 if (mDrawingState.crop != s.crop) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003794 SFTRACE_FORMAT_INSTANT("%s: false [eCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003795 return false;
3796 }
3797 }
3798
3799 if (s.what & layer_state_t::eDataspaceChanged) {
3800 if (mDrawingState.dataspace != s.dataspace) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003801 SFTRACE_FORMAT_INSTANT("%s: false [eDataspaceChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003802 return false;
3803 }
3804 }
3805
3806 if (s.what & layer_state_t::eHdrMetadataChanged) {
3807 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003808 SFTRACE_FORMAT_INSTANT("%s: false [eHdrMetadataChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003809 return false;
3810 }
3811 }
3812
3813 if (s.what & layer_state_t::eSidebandStreamChanged) {
3814 if (mDrawingState.sidebandStream != s.sidebandStream) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003815 SFTRACE_FORMAT_INSTANT("%s: false [eSidebandStreamChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003816 return false;
3817 }
3818 }
3819
3820 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3821 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003822 SFTRACE_FORMAT_INSTANT("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003823 return false;
3824 }
3825 }
3826
3827 if (s.what & layer_state_t::eShadowRadiusChanged) {
3828 if (mDrawingState.shadowRadius != s.shadowRadius) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003829 SFTRACE_FORMAT_INSTANT("%s: false [eShadowRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003830 return false;
3831 }
3832 }
3833
3834 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3835 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003836 SFTRACE_FORMAT_INSTANT("%s: false [eFixedTransformHintChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003837 return false;
3838 }
3839 }
3840
3841 if (s.what & layer_state_t::eTrustedOverlayChanged) {
Vishnu Nair9e0017e2024-05-22 19:02:44 +00003842 if (mDrawingState.isTrustedOverlay != (s.trustedOverlay == gui::TrustedOverlay::ENABLED)) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003843 SFTRACE_FORMAT_INSTANT("%s: false [eTrustedOverlayChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003844 return false;
3845 }
3846 }
3847
3848 if (s.what & layer_state_t::eStretchChanged) {
3849 StretchEffect temp = s.stretchEffect;
3850 temp.sanitize();
3851 if (mDrawingState.stretchEffect != temp) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003852 SFTRACE_FORMAT_INSTANT("%s: false [eStretchChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003853 return false;
3854 }
3855 }
3856
3857 if (s.what & layer_state_t::eBufferCropChanged) {
3858 if (mDrawingState.bufferCrop != s.bufferCrop) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003859 SFTRACE_FORMAT_INSTANT("%s: false [eBufferCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003860 return false;
3861 }
3862 }
3863
3864 if (s.what & layer_state_t::eDestinationFrameChanged) {
3865 if (mDrawingState.destinationFrame != s.destinationFrame) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003866 SFTRACE_FORMAT_INSTANT("%s: false [eDestinationFrameChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003867 return false;
3868 }
3869 }
3870
3871 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3872 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003873 SFTRACE_FORMAT_INSTANT("%s: false [eDimmingEnabledChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003874 return false;
3875 }
3876 }
3877
John Reck68796592023-01-25 13:47:12 -05003878 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
Sally Qi963049b2023-03-23 14:06:21 -07003879 if (mDrawingState.currentHdrSdrRatio != s.currentHdrSdrRatio ||
3880 mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003881 SFTRACE_FORMAT_INSTANT("%s: false [eExtendedRangeBrightnessChanged changed]", __func__);
John Reck68796592023-01-25 13:47:12 -05003882 return false;
3883 }
3884 }
3885
Alec Mouri1b0d4e12024-02-12 22:27:19 +00003886 if (s.what & layer_state_t::eDesiredHdrHeadroomChanged) {
3887 if (mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003888 SFTRACE_FORMAT_INSTANT("%s: false [eDesiredHdrHeadroomChanged changed]", __func__);
Alec Mouri1b0d4e12024-02-12 22:27:19 +00003889 return false;
3890 }
3891 }
3892
Patrick Williamsbb25f802022-08-30 23:02:34 +00003893 return true;
3894}
3895
Vishnu Naire14c6b32022-08-06 04:20:15 +00003896sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003897 // 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 +00003898 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003899}
3900
Vishnu Naire14c6b32022-08-06 04:20:15 +00003901const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003902 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003903}
3904
Vishnu Naire14c6b32022-08-06 04:20:15 +00003905LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003906 return mSnapshot.get();
3907}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003908
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003909std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
3910 return std::move(mSnapshot);
3911}
3912
3913void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
3914 mSnapshot = std::move(snapshot);
3915}
3916
Patrick Williamsbb25f802022-08-30 23:02:34 +00003917const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003918 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003919}
3920
Patrick Williams7584c6a2022-10-29 02:10:58 +00003921sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Lloyd Pique70ddc672024-04-30 18:20:40 -07003922 auto result = mFlinger->getFactory().createLayerFE(mName, this);
Patrick Williams7584c6a2022-10-29 02:10:58 +00003923 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3924 return result;
3925}
3926
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003927sp<LayerFE> Layer::getCompositionEngineLayerFE(
3928 const frontend::LayerHierarchy::TraversalPath& path) {
3929 for (auto& [p, layerFE] : mLayerFEs) {
3930 if (p == path) {
3931 return layerFE;
3932 }
3933 }
Lloyd Pique70ddc672024-04-30 18:20:40 -07003934 auto layerFE = mFlinger->getFactory().createLayerFE(mName, this);
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003935 mLayerFEs.emplace_back(path, layerFE);
3936 return layerFE;
3937}
3938
Patrick Williamsbb25f802022-08-30 23:02:34 +00003939void Layer::useSurfaceDamage() {
3940 if (mFlinger->mForceFullDamage) {
3941 surfaceDamageRegion = Region::INVALID_REGION;
3942 } else {
3943 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3944 }
3945}
3946
3947void Layer::useEmptyDamage() {
3948 surfaceDamageRegion.clear();
3949}
3950
3951bool Layer::isOpaque(const Layer::State& s) const {
3952 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3953 // layer's opaque flag.
3954 if (!hasSomethingToDraw()) {
3955 return false;
3956 }
3957
3958 // if the layer has the opaque flag, then we're always opaque
3959 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3960 return true;
3961 }
3962
3963 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003964 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003965 return true;
3966 }
3967
3968 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3969 return fillsColor() && getAlpha() == 1.0_hf;
3970}
3971
3972bool Layer::canReceiveInput() const {
3973 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3974}
3975
3976bool Layer::isVisible() const {
3977 if (!hasSomethingToDraw()) {
3978 return false;
3979 }
3980
3981 if (isHiddenByPolicy()) {
3982 return false;
3983 }
3984
3985 return getAlpha() > 0.0f || hasBlur();
3986}
3987
Leon Scroggins III5b581492023-10-31 14:29:41 -04003988void Layer::onCompositionPresented(const DisplayDevice* display,
3989 const std::shared_ptr<FenceTime>& glDoneFence,
3990 const std::shared_ptr<FenceTime>& presentFence,
3991 const CompositorTiming& compositorTiming) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003992 // mFrameLatencyNeeded is true when a new frame was latched for the
3993 // composition.
3994 if (!mBufferInfo.mFrameLatencyNeeded) return;
3995
3996 for (const auto& handle : mDrawingState.callbackHandles) {
3997 handle->gpuCompositionDoneFence = glDoneFence;
3998 handle->compositorTiming = compositorTiming;
3999 }
4000
4001 // Update mFrameTracker.
4002 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
4003 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
4004
4005 const int32_t layerId = getSequence();
4006 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
4007
4008 const auto outputLayer = findOutputLayerForDisplay(display);
4009 if (outputLayer && outputLayer->requiresClientComposition()) {
4010 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
4011 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
4012 clientCompositionTimestamp,
4013 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
4014 // Update the SurfaceFrames in the drawing state
4015 if (mDrawingState.bufferSurfaceFrameTX) {
4016 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
4017 }
4018 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
4019 surfaceFrame->setGpuComposition();
4020 }
4021 }
4022
4023 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
4024 if (frameReadyFence->isValid()) {
4025 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
4026 } else {
4027 // There was no fence for this frame, so assume that it was ready
4028 // to be presented at the desired present time.
4029 mFrameTracker.setFrameReadyTime(desiredPresentTime);
4030 }
4031
4032 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08004033 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004034 const std::optional<Fps> renderRate =
4035 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
4036
Alec Mouri7c1d8b52023-08-29 20:14:46 +00004037 const auto vote = frameRateToSetFrameRateVotePayload(getFrameRateForLayerTree());
Patrick Williamsbb25f802022-08-30 23:02:34 +00004038 const auto gameMode = getGameMode();
4039
4040 if (presentFence->isValid()) {
4041 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
4042 refreshRate, renderRate, vote, gameMode);
4043 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
4044 presentFence,
4045 FrameTracer::FrameEvent::PRESENT_FENCE);
4046 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
4047 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
4048 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04004049 // The HWC doesn't support present fences, so use the present timestamp instead.
4050 const nsecs_t presentTimestamp =
4051 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
4052
4053 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
4054 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
4055 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
4056
Patrick Williamsbb25f802022-08-30 23:02:34 +00004057 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
4058 refreshRate, renderRate, vote, gameMode);
4059 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
4060 mCurrentFrameNumber, actualPresentTime,
4061 FrameTracer::FrameEvent::PRESENT_FENCE);
4062 mFrameTracker.setActualPresentTime(actualPresentTime);
4063 }
4064 }
4065
4066 mFrameTracker.advanceFrame();
4067 mBufferInfo.mFrameLatencyNeeded = false;
4068}
4069
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004070bool Layer::willReleaseBufferOnLatch() const {
4071 return !mDrawingState.buffer && mBufferInfo.mBuffer;
4072}
4073
Patrick Williamsbb25f802022-08-30 23:02:34 +00004074bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00004075 const bool bgColorOnly = mDrawingState.bgColorLayer != nullptr;
4076 return latchBufferImpl(recomputeVisibleRegions, latchTime, bgColorOnly);
4077}
4078
4079bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00004080 SFTRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
4081 getDrawingState().frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00004082
4083 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
4084
4085 if (refreshRequired) {
4086 return refreshRequired;
4087 }
4088
4089 // If the head buffer's acquire fence hasn't signaled yet, return and
4090 // try again later
4091 if (!fenceHasSignaled()) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00004092 SFTRACE_NAME("!fenceHasSignaled()");
Patrick Williamsbb25f802022-08-30 23:02:34 +00004093 mFlinger->onLayerUpdate();
4094 return false;
4095 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00004096 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00004097
4098 // Capture the old state of the layer for comparisons later
4099 BufferInfo oldBufferInfo = mBufferInfo;
4100 const bool oldOpacity = isOpaque(mDrawingState);
4101 mPreviousFrameNumber = mCurrentFrameNumber;
4102 mCurrentFrameNumber = mDrawingState.frameNumber;
4103 gatherBufferInfo();
4104
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004105 if (mBufferInfo.mBuffer) {
4106 // We latched a buffer that will be presented soon. Clear the previously presented layer
4107 // stack list.
4108 mPreviouslyPresentedLayerStacks.clear();
4109 }
4110
4111 if (mDrawingState.buffer == nullptr) {
4112 const bool bufferReleased = oldBufferInfo.mBuffer != nullptr;
4113 recomputeVisibleRegions = bufferReleased;
4114 return bufferReleased;
4115 }
4116
Patrick Williamsbb25f802022-08-30 23:02:34 +00004117 if (oldBufferInfo.mBuffer == nullptr) {
4118 // the first time we receive a buffer, we need to trigger a
4119 // geometry invalidation.
4120 recomputeVisibleRegions = true;
4121 }
4122
4123 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
4124 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
4125 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
4126 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
4127 recomputeVisibleRegions = true;
4128 }
4129
4130 if (oldBufferInfo.mBuffer != nullptr) {
4131 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
4132 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
4133 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
4134 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
4135 recomputeVisibleRegions = true;
4136 }
4137 }
4138
4139 if (oldOpacity != isOpaque(mDrawingState)) {
4140 recomputeVisibleRegions = true;
4141 }
4142
4143 return true;
4144}
4145
4146bool Layer::hasReadyFrame() const {
4147 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
4148}
4149
4150bool Layer::isProtected() const {
4151 return (mBufferInfo.mBuffer != nullptr) &&
4152 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
4153}
4154
Patrick Williamsbb25f802022-08-30 23:02:34 +00004155void Layer::latchAndReleaseBuffer() {
4156 if (hasReadyFrame()) {
4157 bool ignored = false;
4158 latchBuffer(ignored, systemTime());
4159 }
4160 releasePendingBuffer(systemTime());
4161}
4162
4163PixelFormat Layer::getPixelFormat() const {
4164 return mBufferInfo.mPixelFormat;
4165}
4166
4167bool Layer::getTransformToDisplayInverse() const {
4168 return mBufferInfo.mTransformToDisplayInverse;
4169}
4170
4171Rect Layer::getBufferCrop() const {
4172 // this is the crop rectangle that applies to the buffer
4173 // itself (as opposed to the window)
4174 if (!mBufferInfo.mCrop.isEmpty()) {
4175 // if the buffer crop is defined, we use that
4176 return mBufferInfo.mCrop;
4177 } else if (mBufferInfo.mBuffer != nullptr) {
4178 // otherwise we use the whole buffer
4179 return mBufferInfo.mBuffer->getBounds();
4180 } else {
4181 // if we don't have a buffer yet, we use an empty/invalid crop
4182 return Rect();
4183 }
4184}
4185
4186uint32_t Layer::getBufferTransform() const {
4187 return mBufferInfo.mTransform;
4188}
4189
4190ui::Dataspace Layer::getDataSpace() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004191 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
4192}
4193
Alec Mouri89f5d4e2023-10-20 17:12:49 +00004194bool Layer::isFrontBuffered() const {
4195 if (mBufferInfo.mBuffer == nullptr) {
4196 return false;
4197 }
4198
4199 return mBufferInfo.mBuffer->getUsage() & AHARDWAREBUFFER_USAGE_FRONT_BUFFER;
4200}
4201
Patrick Williamsbb25f802022-08-30 23:02:34 +00004202ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
4203 ui::Dataspace updatedDataspace = dataspace;
4204 // translate legacy dataspaces to modern dataspaces
4205 switch (dataspace) {
Alec Mouri74c7ae12023-03-26 02:57:47 +00004206 // Treat unknown dataspaces as V0_sRGB
4207 case ui::Dataspace::UNKNOWN:
Patrick Williamsbb25f802022-08-30 23:02:34 +00004208 case ui::Dataspace::SRGB:
4209 updatedDataspace = ui::Dataspace::V0_SRGB;
4210 break;
4211 case ui::Dataspace::SRGB_LINEAR:
4212 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
4213 break;
4214 case ui::Dataspace::JFIF:
4215 updatedDataspace = ui::Dataspace::V0_JFIF;
4216 break;
4217 case ui::Dataspace::BT601_625:
4218 updatedDataspace = ui::Dataspace::V0_BT601_625;
4219 break;
4220 case ui::Dataspace::BT601_525:
4221 updatedDataspace = ui::Dataspace::V0_BT601_525;
4222 break;
4223 case ui::Dataspace::BT709:
4224 updatedDataspace = ui::Dataspace::V0_BT709;
4225 break;
4226 default:
4227 break;
4228 }
4229
4230 return updatedDataspace;
4231}
4232
4233sp<GraphicBuffer> Layer::getBuffer() const {
4234 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4235}
4236
Vishnu Nairb76d99a2023-03-19 18:22:31 -07004237void Layer::setTransformHintLegacy(ui::Transform::RotationFlags displayTransformHint) {
4238 mTransformHintLegacy = getFixedTransformHint();
4239 if (mTransformHintLegacy == ui::Transform::ROT_INVALID) {
4240 mTransformHintLegacy = displayTransformHint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004241 }
4242}
4243
4244const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4245 return mBufferInfo.mBuffer;
4246}
4247
4248bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00004249 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004250 return false;
4251 }
4252
4253 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00004254 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004255 mDrawingState.modified = true;
4256 setTransactionFlags(eTransactionNeeded);
4257 return true;
4258}
4259
4260bool Layer::fillsColor() const {
4261 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4262 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4263}
4264
4265bool Layer::hasBlur() const {
4266 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4267}
4268
Vishnu Nairba354102022-08-01 00:14:18 +00004269void Layer::updateSnapshot(bool updateGeometry) {
4270 if (!getCompositionEngineLayerFE()) {
4271 return;
4272 }
4273
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004274 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004275 if (updateGeometry) {
4276 prepareBasicGeometryCompositionState();
4277 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004278 snapshot->roundedCorner = getRoundedCornerState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004279 snapshot->transformedBounds = mScreenBounds;
4280 if (mEffectiveShadowRadius > 0.f) {
4281 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4282
4283 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4284 // it if transparent regions are present. This may not be necessary since shadows are
4285 // typically cast by layers without transparent regions.
4286 snapshot->shadowSettings.boundaries = mBounds;
4287
4288 const float casterAlpha = snapshot->alpha;
4289 const bool casterIsOpaque =
4290 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4291
4292 // If the casting layer is translucent, we need to fill in the shadow underneath the
4293 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4294 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4295 snapshot->shadowSettings.ambientColor *= casterAlpha;
4296 snapshot->shadowSettings.spotColor *= casterAlpha;
4297 }
4298 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004299 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004300 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004301 snapshot->layerOpaqueFlagSet =
4302 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004303 sp<Layer> p = mDrawingParent.promote();
4304 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004305 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004306 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004307 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004308 }
4309 snapshot->bufferSize = getBufferSize(mDrawingState);
4310 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004311 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00004312 preparePerFrameCompositionState();
4313}
4314
Vishnu Naire14c6b32022-08-06 04:20:15 +00004315void Layer::updateChildrenSnapshots(bool updateGeometry) {
4316 for (const sp<Layer>& child : mDrawingChildren) {
4317 child->updateSnapshot(updateGeometry);
4318 child->updateChildrenSnapshots(updateGeometry);
4319 }
4320}
4321
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004322void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4323 mSnapshot->layerMetadata = parentMetadata;
4324 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4325 for (const sp<Layer>& child : mDrawingChildren) {
4326 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4327 }
4328}
4329
4330void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4331 std::unordered_set<Layer*>& visited) {
4332 if (visited.find(this) != visited.end()) {
4333 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4334 return;
4335 }
4336 visited.insert(this);
4337
4338 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4339
4340 if (mDrawingState.zOrderRelatives.empty()) {
4341 return;
4342 }
4343 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4344 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4345 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4346 sp<Layer> relative = weakRelative.promote();
4347 if (!relative) {
4348 continue;
4349 }
4350 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4351 }
4352}
4353
Chavi Weingarten328a8312023-01-26 21:17:52 +00004354bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00004355 TrustedPresentationListener const& listener) {
4356 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4357 mTrustedPresentationListener = listener;
4358 mTrustedPresentationThresholds = thresholds;
4359 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4360 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4361 mFlinger->mNumTrustedPresentationListeners++;
4362 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4363 mFlinger->mNumTrustedPresentationListeners--;
4364 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00004365
4366 // Reset trusted presentation states to ensure we start the time again.
4367 mEnteredTrustedPresentationStateTime = -1;
4368 mLastReportedTrustedPresentationState = false;
4369 mLastComputedTrustedPresentationState = false;
4370
4371 // If there's a new trusted presentation listener, the code needs to go through the composite
4372 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
4373 // we're already in the requested state.
4374 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00004375}
4376
Vishnu Naira156f482023-02-22 00:23:38 +00004377void Layer::updateLastLatchTime(nsecs_t latchTime) {
4378 mLastLatchTime = latchTime;
4379}
4380
Arthur Hung69f95222023-10-04 07:39:02 +00004381void Layer::setIsSmallDirty(const Region& damageRegion,
4382 const ui::Transform& layerToDisplayTransform) {
4383 mSmallDirty = false;
Jerry Chang36678002023-11-29 16:56:17 +00004384 if (!mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +00004385 return;
4386 }
4387
4388 if (mWindowType != WindowInfo::Type::APPLICATION &&
4389 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
4390 return;
4391 }
Arthur Hung69f95222023-10-04 07:39:02 +00004392
4393 Rect bounds = damageRegion.getBounds();
Arthur Hungc70bee22023-06-02 01:35:52 +00004394 if (!bounds.isValid()) {
4395 return;
4396 }
4397
Arthur Hung69f95222023-10-04 07:39:02 +00004398 // Transform to screen space.
4399 bounds = layerToDisplayTransform.transform(bounds);
4400
Arthur Hungc70bee22023-06-02 01:35:52 +00004401 // If the damage region is a small dirty, this could give the hint for the layer history that
4402 // it could suppress the heuristic rate when calculating.
Tony Huangf3621102023-09-04 17:14:22 +08004403 mSmallDirty = mFlinger->mScheduler->isSmallDirtyArea(mOwnerAppId,
Tony Huang9ac5e6e2023-08-24 09:01:44 +00004404 bounds.getWidth() * bounds.getHeight());
Arthur Hungc70bee22023-06-02 01:35:52 +00004405}
4406
Arthur Hung69f95222023-10-04 07:39:02 +00004407void Layer::setIsSmallDirty(frontend::LayerSnapshot* snapshot) {
4408 setIsSmallDirty(snapshot->surfaceDamage, snapshot->localTransform);
4409 snapshot->isSmallDirty = mSmallDirty;
4410}
4411
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004412} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004413
4414#if defined(__gl_h_)
4415#error "don't include gl/gl.h in this file"
4416#endif
4417
4418#if defined(__gl2_h_)
4419#error "don't include gl2/gl2.h in this file"
4420#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004421
4422// TODO(b/129481165): remove the #pragma below and fix conversion issues
4423#pragma clang diagnostic pop // ignored "-Wconversion"