blob: 636f7bdabf24b5609609cc394c62fb63f9a10bcc [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;
Vishnu Nair5c61a012024-08-05 21:14:39 -0700319 mFlinger->mScheduler->registerLayer(this, FrameRateCompatibility::Default);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700320 }
chaviw61626f22018-11-15 16:26:27 -0800321
322 for (const auto& child : mCurrentChildren) {
323 child->addToCurrentState();
324 }
325}
326
Mathias Agopian13127d82013-03-05 17:47:11 -0800327// ---------------------------------------------------------------------------
328// set-up
329// ---------------------------------------------------------------------------
330
chaviw13fdc492017-06-27 12:40:18 -0700331bool Layer::getPremultipledAlpha() const {
332 return mPremultipliedAlpha;
333}
334
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700335sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800336 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700337 if (mGetHandleCalled) {
338 ALOGE("Get handle called twice" );
339 return nullptr;
340 }
341 mGetHandleCalled = true;
Vishnu Nair787aa782023-03-17 13:46:46 -0700342 mHandleAlive = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000343 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800344}
345
346// ---------------------------------------------------------------------------
347// h/w composer set-up
348// ---------------------------------------------------------------------------
349
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700350static Rect reduce(const Rect& win, const Region& exclude) {
351 if (CC_LIKELY(exclude.isEmpty())) {
352 return win;
353 }
354 if (exclude.isRect()) {
355 return win.reduce(exclude.getBounds());
356 }
357 return Region(win).subtract(exclude).getBounds();
358}
359
Dan Stoza80d61162017-12-20 15:57:52 -0800360static FloatRect reduce(const FloatRect& win, const Region& exclude) {
361 if (CC_LIKELY(exclude.isEmpty())) {
362 return win;
363 }
364 // Convert through Rect (by rounding) for lack of FloatRegion
365 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
366}
367
Vishnu Nair4351ad52019-02-11 14:13:02 -0800368Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800369 if (!reduceTransparentRegion) {
370 return Rect{mScreenBounds};
371 }
372
373 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800374 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800375 // Transform to screen space.
376 bounds = t.transform(bounds);
377 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700378}
379
Vishnu Nair4351ad52019-02-11 14:13:02 -0800380FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000381 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800382 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700383}
384
Vishnu Nairf0c28512019-02-08 12:40:28 -0800385FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
386 // Subtract the transparent region and snap to the bounds.
387 return reduce(mBounds, activeTransparentRegion);
388}
389
Chavi Weingarten076acac2023-01-19 17:20:43 +0000390// No early returns.
Vishnu Nair781d7252023-01-30 18:16:01 +0000391void Layer::updateTrustedPresentationState(const DisplayDevice* display,
392 const frontend::LayerSnapshot* snapshot,
393 int64_t time_in_ms, bool leaveState) {
Chavi Weingarten076acac2023-01-19 17:20:43 +0000394 if (!hasTrustedPresentationListener()) {
395 return;
396 }
397 const bool lastState = mLastComputedTrustedPresentationState;
398 mLastComputedTrustedPresentationState = false;
399
400 if (!leaveState) {
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000401 const auto outputLayer = findOutputLayerForDisplay(display, snapshot->path);
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000402 if (outputLayer != nullptr) {
403 if (outputLayer->getState().coveredRegionExcludingDisplayOverlays) {
404 Region coveredRegion =
405 *outputLayer->getState().coveredRegionExcludingDisplayOverlays;
406 mLastComputedTrustedPresentationState =
407 computeTrustedPresentationState(snapshot->geomLayerBounds,
408 snapshot->sourceBounds(), coveredRegion,
409 snapshot->transformedBounds,
410 snapshot->alpha,
411 snapshot->geomLayerTransform,
412 mTrustedPresentationThresholds);
413 } else {
414 ALOGE("CoveredRegionExcludingDisplayOverlays was not set for %s. Don't compute "
415 "TrustedPresentationState",
416 getDebugName());
417 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000418 }
419 }
420 const bool newState = mLastComputedTrustedPresentationState;
421 if (lastState && !newState) {
422 // We were in the trusted presentation state, but now we left it,
423 // emit the callback if needed
424 if (mLastReportedTrustedPresentationState) {
425 mLastReportedTrustedPresentationState = false;
426 mTrustedPresentationListener.invoke(false);
427 }
428 // Reset the timer
429 mEnteredTrustedPresentationStateTime = -1;
430 } else if (!lastState && newState) {
431 // We were not in the trusted presentation state, but we entered it, begin the timer
432 // and make sure this gets called at least once more!
433 mEnteredTrustedPresentationStateTime = time_in_ms;
434 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
435 }
436
437 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
438 if (!mLastReportedTrustedPresentationState && newState &&
439 (time_in_ms - mEnteredTrustedPresentationStateTime >
440 mTrustedPresentationThresholds.stabilityRequirementMs)) {
441 mLastReportedTrustedPresentationState = true;
442 mTrustedPresentationListener.invoke(true);
443 }
444}
445
446/**
447 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
448 * of how the parameters and thresholds are interpreted. The general spirit is
449 * to produce an upper bound on the amount of the buffer which was presented.
450 */
451bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
452 const Region& coveredRegion,
453 const FloatRect& screenBounds, float alpha,
454 const ui::Transform& effectiveTransform,
455 const TrustedPresentationThresholds& thresholds) {
456 if (alpha < thresholds.minAlpha) {
457 return false;
458 }
459 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
460 return false;
461 }
462 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
463 return false;
464 }
465
466 const float sx = effectiveTransform.dsdx();
467 const float sy = effectiveTransform.dsdy();
468 float fractionRendered = std::min(sx * sy, 1.0f);
469
470 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
471 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
472 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
473
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000474 Region tJunctionFreeRegion = Region::createTJunctionFreeRegion(coveredRegion);
475 // Compute the size of all the rects since they may be disconnected.
476 float coveredSize = 0;
477 for (auto rect = tJunctionFreeRegion.begin(); rect < tJunctionFreeRegion.end(); rect++) {
478 float size = rect->width() * rect->height();
479 coveredSize += size;
480 }
481
482 fractionRendered *= (1 - (coveredSize / (screenBounds.getWidth() * screenBounds.getHeight())));
Chavi Weingarten076acac2023-01-19 17:20:43 +0000483
484 if (fractionRendered < thresholds.minFractionRendered) {
485 return false;
486 }
487
488 return true;
489}
490
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700491void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
492 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800493 const State& s(getDrawingState());
494
495 // Calculate effective layer transform
496 mEffectiveTransform = parentTransform * getActiveTransform(s);
497
Garfield Tan2c1782c2022-02-16 15:25:05 -0800498 if (CC_UNLIKELY(!isTransformValid())) {
499 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
500 getDebugName());
501 return;
502 }
503
Vishnu Nair4351ad52019-02-11 14:13:02 -0800504 // Transform parent bounds to layer space
505 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
506
Vishnu Nairc652ff82019-03-15 12:48:54 -0700507 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800508 mSourceBounds = computeSourceBounds(parentBounds);
509
510 // Calculate bounds by croping diplay frame with layer crop and parent bounds
511 FloatRect bounds = mSourceBounds;
512 const Rect layerCrop = getCrop(s);
513 if (!layerCrop.isEmpty()) {
514 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
515 }
516 bounds = bounds.intersect(parentBounds);
517
518 mBounds = bounds;
519 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700520
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700521 // Use the layer's own shadow radius if set. Otherwise get the radius from
522 // parent.
523 if (s.shadowRadius > 0.f) {
524 mEffectiveShadowRadius = s.shadowRadius;
525 } else {
526 mEffectiveShadowRadius = parentShadowRadius;
527 }
528
529 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
530 // don't pass it to its children.
531 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
532
Vishnu Nair4351ad52019-02-11 14:13:02 -0800533 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700534 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800535 }
Vishnu Nairba354102022-08-01 00:14:18 +0000536
537 if (mPotentialCursor) {
538 prepareCursorCompositionState();
539 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800540}
541
Vishnu Nair60356342018-11-13 13:00:45 -0800542Rect Layer::getCroppedBufferSize(const State& s) const {
543 Rect size = getBufferSize(s);
544 Rect crop = getCrop(s);
545 if (!crop.isEmpty() && size.isValid()) {
546 size.intersect(crop, &size);
547 } else if (!crop.isEmpty()) {
548 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700549 }
Vishnu Nair60356342018-11-13 13:00:45 -0800550 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800551}
552
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700553void Layer::setupRoundedCornersCropCoordinates(Rect win,
554 const FloatRect& roundedCornersCrop) const {
555 // Translate win by the rounded corners rect coordinates, to have all values in
556 // layer coordinate space.
557 win.left -= roundedCornersCrop.left;
558 win.right -= roundedCornersCrop.left;
559 win.top -= roundedCornersCrop.top;
560 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700561}
562
Lloyd Piquede196652020-01-22 17:29:58 -0800563void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800564 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800565 const auto alpha = static_cast<float>(getAlpha());
566 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700567 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800568
569 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
570 if (!opaque || alpha != 1.0f) {
571 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
572 : Hwc2::IComposerClient::BlendMode::COVERAGE;
573 }
574
Alec Mourif4af03e2023-02-11 00:25:24 +0000575 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000576 auto* snapshot = editLayerSnapshot();
577 snapshot->outputFilter = getOutputFilter();
578 snapshot->isVisible = isVisible();
579 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
Vishnu Naird9e4f462023-10-06 04:05:45 +0000580 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800581
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000582 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800583 contentDirty = false;
584
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000585 snapshot->geomLayerBounds = mBounds;
586 snapshot->geomLayerTransform = getTransform();
587 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
588 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000589 snapshot->localTransform = getActiveTransform(drawingState);
590 snapshot->localTransformInverse = snapshot->localTransform.inverse();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000591 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
592 snapshot->alpha = alpha;
Vishnu Nairc6384702023-07-31 12:22:20 -0700593 snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
594 snapshot->blurRegions = getBlurRegions();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000595 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800596}
597
Lloyd Piquede196652020-01-22 17:29:58 -0800598void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800599 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000600 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700601
Alec Mourif4af03e2023-02-11 00:25:24 +0000602 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000603 snapshot->geomBufferSize = getBufferSize(drawingState);
604 snapshot->geomContentCrop = getBufferCrop();
605 snapshot->geomCrop = getCrop(drawingState);
606 snapshot->geomBufferTransform = getBufferTransform();
607 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
608 snapshot->geomUsesSourceCrop = usesSourceCrop();
609 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800610
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000611 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800612 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
613 for (const auto& [key, mandatory] : supportedMetadata) {
614 const auto& genericLayerMetadataCompatibilityMap =
615 mFlinger->getGenericLayerMetadataKeyMap();
616 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
617 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
618 continue;
619 }
620 const uint32_t id = compatIter->second;
621
622 auto it = drawingState.metadata.mMap.find(id);
623 if (it == std::end(drawingState.metadata.mMap)) {
624 continue;
625 }
626
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000627 snapshot->metadata.emplace(key,
628 compositionengine::GenericLayerMetadataEntry{mandatory,
629 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800630 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800631}
David Sodmanba340492018-08-05 21:51:33 -0700632
Lloyd Piquede196652020-01-22 17:29:58 -0800633void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800634 const auto& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000635 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000636 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800637
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000638 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800639
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000640 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
641 snapshot->dataspace = getDataSpace();
642 snapshot->colorTransform = getColorTransform();
643 snapshot->colorTransformIsIdentity = !hasColorTransform();
644 snapshot->surfaceDamage = surfaceDamageRegion;
645 snapshot->hasProtectedContent = isProtected();
646 snapshot->dimmingEnabled = isDimmingEnabled();
Sally Qi963049b2023-03-23 14:06:21 -0700647 snapshot->currentHdrSdrRatio = getCurrentHdrSdrRatio();
648 snapshot->desiredHdrSdrRatio = getDesiredHdrSdrRatio();
Alec Mourif4af03e2023-02-11 00:25:24 +0000649 snapshot->cachingHint = getCachingHint();
Lloyd Pique688abd42019-02-15 15:42:24 -0800650
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700651 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700652
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000653 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800654
655 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400656 // Rounded corners no longer force client composition, since we may use a
657 // hole punch so that the layer will appear to have rounded corners.
Alec Mouri994761f2023-08-04 21:50:55 +0000658 if (drawShadows() || snapshot->stretchEffect.hasEffect()) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000659 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800660 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700661 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairc6384702023-07-31 12:22:20 -0700662 snapshot->blurRegions = getBlurRegions();
663 snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400664
665 // Layer framerate is used in caching decisions.
666 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
667 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000668 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000669
670 if (hasBufferOrSidebandStream()) {
671 preparePerFrameBufferCompositionState();
672 } else {
673 preparePerFrameEffectsCompositionState();
674 }
675}
676
677void Layer::preparePerFrameBufferCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000678 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000679 auto* snapshot = editLayerSnapshot();
Alec Mourif4af03e2023-02-11 00:25:24 +0000680 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000681 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
682 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000683 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
684 return;
685 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000686 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000687 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
ramindanib2158ee2023-02-13 20:29:59 -0800688 } else if ((mDrawingState.flags & layer_state_t::eLayerIsRefreshRateIndicator) != 0) {
689 snapshot->compositionType =
690 aidl::android::hardware::graphics::composer3::Composition::REFRESH_RATE_INDICATOR;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000691 } else {
692 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000693 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
694 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000695 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
696 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
697 }
698
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000699 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000700 snapshot->acquireFence = mBufferInfo.mFence;
701 snapshot->frameNumber = mBufferInfo.mFrameNumber;
702 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000703}
704
705void Layer::preparePerFrameEffectsCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000706 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000707 auto* snapshot = editLayerSnapshot();
708 snapshot->color = getColor();
709 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000710 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800711}
712
Lloyd Piquede196652020-01-22 17:29:58 -0800713void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800714 const State& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000715 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000716 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800717
718 // Apply the layer's transform, followed by the display's global transform
719 // Here we're guaranteed that the layer's transform preserves rects
720 Rect win = getCroppedBufferSize(drawingState);
721 // Subtract the transparent region and snap to the bounds
722 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
723 Rect frame(getTransform().transform(bounds));
724
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000725 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800726}
727
Lloyd Piquea83776c2019-01-29 18:42:32 -0800728const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700729 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800730}
731
Mathias Agopian13127d82013-03-05 17:47:11 -0800732// ---------------------------------------------------------------------------
733// drawing...
734// ---------------------------------------------------------------------------
735
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500736aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
737 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700738 const auto outputLayer = findOutputLayerForDisplay(&display);
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000739 return getCompositionType(outputLayer);
740}
741
742aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
743 const compositionengine::OutputLayer* outputLayer) const {
Alec Mouri6b9e9912020-01-21 10:50:24 -0800744 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500745 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800746 }
747 if (outputLayer->getState().hwc) {
748 return (*outputLayer->getState().hwc).hwcCompositionType;
749 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500750 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800751 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800752}
753
Mathias Agopian13127d82013-03-05 17:47:11 -0800754// ----------------------------------------------------------------------------
755// local state
756// ----------------------------------------------------------------------------
757
David Sodman41fdfc92017-11-06 16:09:56 -0800758bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800759 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700760 if (s.flags & layer_state_t::eLayerSecure) {
761 return true;
762 }
763
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000764 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700765 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700766}
767
Mathias Agopian13127d82013-03-05 17:47:11 -0800768// ----------------------------------------------------------------------------
769// transaction
770// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800771
Vishnu Naira156f482023-02-22 00:23:38 +0000772uint32_t Layer::doTransaction(uint32_t flags) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000773 SFTRACE_CALL();
Marissa Wall61c58622018-07-18 10:12:20 -0700774
Robert Carr0758e5d2021-03-11 22:15:04 -0800775 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700776 mDrawingStateModified = mDrawingState.modified;
777 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700778
Alec Mourib416efd2018-09-06 21:01:59 +0000779 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700780
Robert Carr6a160312021-05-17 12:08:20 -0700781 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800782 // invalidate and recompute the visible regions if needed
783 flags |= Layer::eVisibleRegion;
784 }
785
Robert Carr6a160312021-05-17 12:08:20 -0700786 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800787 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000788 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800789 flags |= eVisibleRegion;
790 this->contentDirty = true;
791
792 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700793 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800794 }
795
Arthur Hung9ed43392022-05-27 06:31:57 +0000796 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
797 mFlinger->mUpdateInputInfo = true;
798 }
799
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700800 commitTransaction();
Robert Carra1257842020-01-31 13:48:28 -0800801
Mathias Agopian13127d82013-03-05 17:47:11 -0800802 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800803}
804
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700805void Layer::commitTransaction() {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000806 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
807 // bufferSurfaceFrameTX will be presented in latchBuffer.
808 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
809 if (surfaceFrame->getPresentState() != PresentState::Presented) {
810 // With applyPendingStates, we could end up having presented surfaceframes from previous
811 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800812 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000813 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
814 }
815 }
Robert Carr6a160312021-05-17 12:08:20 -0700816 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700817}
818
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700819uint32_t Layer::clearTransactionFlags(uint32_t mask) {
820 const auto flags = mTransactionFlags & mask;
821 mTransactionFlags &= ~mask;
822 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800823}
824
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700825void Layer::setTransactionFlags(uint32_t mask) {
826 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800827}
828
Robert Carr1f0a16a2016-10-24 16:27:39 -0700829bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
830 ssize_t idx = mCurrentChildren.indexOf(childLayer);
831 if (idx < 0) {
832 return false;
833 }
834 if (childLayer->setLayer(z)) {
835 mCurrentChildren.removeAt(idx);
836 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800837 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700838 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800839 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700840}
841
Robert Carr503c7042017-09-27 15:06:08 -0700842bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
843 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
844 ssize_t idx = mCurrentChildren.indexOf(childLayer);
845 if (idx < 0) {
846 return false;
847 }
848 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
849 mCurrentChildren.removeAt(idx);
850 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800851 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700852 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800853 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700854}
855
Robert Carrae060832016-11-28 10:51:00 -0800856bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700857 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
858 mDrawingState.sequence++;
859 mDrawingState.z = z;
860 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700861
Robert Carra70e91c2021-06-11 13:59:52 -0700862 mFlinger->mSomeChildrenChanged = true;
863
Robert Carrdb66e622017-04-10 16:55:57 -0700864 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700865 if (mDrawingState.zOrderRelativeOf != nullptr) {
866 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700867 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700868 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700869 }
chaviw606e5cf2019-03-01 10:12:10 -0800870 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700871 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800872 setTransactionFlags(eTransactionNeeded);
873 return true;
874}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700875
Robert Carrdb66e622017-04-10 16:55:57 -0700876void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700877 mDrawingState.zOrderRelatives.remove(relative);
878 mDrawingState.sequence++;
879 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700880 setTransactionFlags(eTransactionNeeded);
881}
882
883void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700884 mDrawingState.zOrderRelatives.add(relative);
885 mDrawingState.modified = true;
886 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700887 setTransactionFlags(eTransactionNeeded);
888}
889
chaviw606e5cf2019-03-01 10:12:10 -0800890void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700891 mDrawingState.zOrderRelativeOf = relativeOf;
892 mDrawingState.sequence++;
893 mDrawingState.modified = true;
894 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700895
chaviw606e5cf2019-03-01 10:12:10 -0800896 setTransactionFlags(eTransactionNeeded);
897}
898
Robert Carr503d2bd2017-12-04 15:49:47 -0800899bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000900 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700901 if (relative == nullptr) {
902 return false;
903 }
904
Robert Carr6a160312021-05-17 12:08:20 -0700905 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
906 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800907 return false;
908 }
909
Robert Carr88b85e12022-03-21 15:47:35 -0700910 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
911 (relative->mDrawingState.zOrderRelativeOf == this)) {
912 ALOGE("Detected relative layer loop between %s and %s",
913 mName.c_str(), relative->mName.c_str());
914 ALOGE("Ignoring new call to set relative layer");
915 return false;
916 }
917
Robert Carra70e91c2021-06-11 13:59:52 -0700918 mFlinger->mSomeChildrenChanged = true;
919
Robert Carr6a160312021-05-17 12:08:20 -0700920 mDrawingState.sequence++;
921 mDrawingState.modified = true;
922 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700923
Robert Carr6a160312021-05-17 12:08:20 -0700924 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700925 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700926 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700927 }
chaviw606e5cf2019-03-01 10:12:10 -0800928 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700929 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700930
931 setTransactionFlags(eTransactionNeeded);
932
933 return true;
934}
935
Winson Chunga30f7c92021-06-29 15:42:56 -0700936bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
937 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
938 mDrawingState.isTrustedOverlay = isTrustedOverlay;
939 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000940 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700941 setTransactionFlags(eTransactionNeeded);
942 return true;
943}
944
945bool Layer::isTrustedOverlay() const {
946 if (getDrawingState().isTrustedOverlay) {
947 return true;
948 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000949 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700950 return (p != nullptr) && p->isTrustedOverlay();
951}
952
Dan Stoza9e56aa02015-11-02 13:00:03 -0800953bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700954 if (mDrawingState.color.a == alpha) return false;
955 mDrawingState.sequence++;
956 mDrawingState.color.a = alpha;
957 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800958 setTransactionFlags(eTransactionNeeded);
959 return true;
960}
chaviw13fdc492017-06-27 12:40:18 -0700961
Valerie Haudd0b7572019-01-29 14:59:27 -0800962bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700963 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700964 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800965 }
Robert Carr6a160312021-05-17 12:08:20 -0700966 mDrawingState.sequence++;
967 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -0800968 setTransactionFlags(eTransactionNeeded);
969
Robert Carr6a160312021-05-17 12:08:20 -0700970 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -0800971 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -0800972 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700973 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -0700974 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Kean Mariotti4ba343c2023-04-19 13:31:02 +0000975 surfaceflinger::LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
976 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -0700977
Valerie Haudd0b7572019-01-29 14:59:27 -0800978 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -0700979 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -0800980 mFlinger->mLayersAdded = true;
981 // set up SF to handle added color layer
982 if (isRemovedFromCurrentState()) {
Josh Gao194ff392022-09-08 16:19:29 -0700983 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -0700984 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -0800985 }
986 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -0700987 } else if (mDrawingState.bgColorLayer && alpha == 0) {
Josh Gao194ff392022-09-08 16:19:29 -0700988 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -0700989 mDrawingState.bgColorLayer->reparent(nullptr);
990 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -0800991 return true;
992 }
993
Robert Carr6a160312021-05-17 12:08:20 -0700994 mDrawingState.bgColorLayer->setColor(color);
995 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
996 mDrawingState.bgColorLayer->setAlpha(alpha);
997 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -0800998
chaviw13fdc492017-06-27 12:40:18 -0700999 return true;
1000}
1001
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001002bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001003 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001004
Robert Carr6a160312021-05-17 12:08:20 -07001005 mDrawingState.sequence++;
1006 mDrawingState.cornerRadius = cornerRadius;
1007 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001008 setTransactionFlags(eTransactionNeeded);
1009 return true;
1010}
1011
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001012bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001013 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001014 // If we start or stop drawing blur then the layer's visibility state may change so increment
1015 // the magic sequence number.
1016 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1017 mDrawingState.sequence++;
1018 }
Robert Carr6a160312021-05-17 12:08:20 -07001019 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1020 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001021 setTransactionFlags(eTransactionNeeded);
1022 return true;
1023}
Marissa Wall61c58622018-07-18 10:12:20 -07001024
Mathias Agopian13127d82013-03-05 17:47:11 -08001025bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001026 mDrawingState.sequence++;
1027 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001028 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001029 setTransactionFlags(eTransactionNeeded);
1030 return true;
1031}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001032
Lucas Dupinc3800b82020-10-02 16:24:48 -07001033bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001034 // If we start or stop drawing blur then the layer's visibility state may change so increment
1035 // the magic sequence number.
1036 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1037 mDrawingState.sequence++;
1038 }
Robert Carr6a160312021-05-17 12:08:20 -07001039 mDrawingState.blurRegions = blurRegions;
1040 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001041 setTransactionFlags(eTransactionNeeded);
1042 return true;
1043}
1044
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001045bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001046 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1047 if (mDrawingState.flags == newFlags) return false;
1048 mDrawingState.sequence++;
1049 mDrawingState.flags = newFlags;
1050 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001051 setTransactionFlags(eTransactionNeeded);
1052 return true;
1053}
Robert Carr99e27f02016-06-16 15:18:02 -07001054
chaviw25714502021-02-11 10:01:08 -08001055bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001056 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001057 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001058 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001059
Robert Carr6a160312021-05-17 12:08:20 -07001060 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001061 setTransactionFlags(eTransactionNeeded);
1062 return true;
1063}
Robert Carr8d5227b2017-03-16 15:41:03 -07001064
Evan Roskyef876c92019-01-25 17:46:06 -08001065bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001066 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1067 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001068 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001069 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001070}
1071
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001072bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001073 if (mDrawingState.layerStack == layerStack) return false;
1074 mDrawingState.sequence++;
1075 mDrawingState.layerStack = layerStack;
1076 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001077 setTransactionFlags(eTransactionNeeded);
1078 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001079}
1080
Peiyong Linc502cb72019-03-01 15:00:23 -08001081bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001082 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001083 return false;
1084 }
Robert Carr6a160312021-05-17 12:08:20 -07001085 mDrawingState.sequence++;
1086 mDrawingState.colorSpaceAgnostic = agnostic;
1087 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001088 setTransactionFlags(eTransactionNeeded);
1089 return true;
1090}
1091
Sally Qi81d95e62022-03-21 19:41:33 -07001092bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1093 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1094
1095 mDrawingState.sequence++;
1096 mDrawingState.dimmingEnabled = dimmingEnabled;
1097 mDrawingState.modified = true;
1098 setTransactionFlags(eTransactionNeeded);
1099 return true;
1100}
1101
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001102bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1103 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1104};
1105
Vishnu Nair73908d12022-10-24 21:46:42 -07001106ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1107 bool useDrawing = state == LayerVector::StateSet::Drawing;
1108 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1109 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001110 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001111 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001112 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001113}
1114
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001115bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001116 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001117 return false;
1118 }
1119
Robert Carr6a160312021-05-17 12:08:20 -07001120 mDrawingState.sequence++;
1121 mDrawingState.shadowRadius = shadowRadius;
1122 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001123 setTransactionFlags(eTransactionNeeded);
1124 return true;
1125}
1126
Vishnu Nair6213bd92020-05-08 17:42:25 -07001127bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001128 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001129 return false;
1130 }
1131
Robert Carr6a160312021-05-17 12:08:20 -07001132 mDrawingState.sequence++;
1133 mDrawingState.fixedTransformHint = fixedTransformHint;
1134 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001135 setTransactionFlags(eTransactionNeeded);
1136 return true;
1137}
1138
John Reckcdb4ed72021-02-04 13:39:33 -05001139bool Layer::setStretchEffect(const StretchEffect& effect) {
1140 StretchEffect temp = effect;
1141 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001142 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001143 return false;
1144 }
Robert Carr6a160312021-05-17 12:08:20 -07001145 mDrawingState.sequence++;
1146 mDrawingState.stretchEffect = temp;
1147 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001148 setTransactionFlags(eTransactionNeeded);
1149 return true;
1150}
1151
John Reckc00c6692021-02-16 11:37:33 -05001152StretchEffect Layer::getStretchEffect() const {
1153 if (mDrawingState.stretchEffect.hasEffect()) {
1154 return mDrawingState.stretchEffect;
1155 }
1156
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001157 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001158 if (parent != nullptr) {
1159 auto effect = parent->getStretchEffect();
1160 if (effect.hasEffect()) {
1161 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1162 return effect;
1163 }
1164 }
1165 return StretchEffect{};
1166}
1167
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001168void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
Vishnu Nair39a74a92024-07-29 19:01:50 +00001169 nsecs_t postTime, gui::GameMode gameMode) {
Robert Carr6a160312021-05-17 12:08:20 -07001170 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001171
1172 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1173 // there are two transactions with the same token, the first one without a buffer and the
1174 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1175 // in that case.
Robert Carr6a160312021-05-17 12:08:20 -07001176 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1177 if (it != mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001178 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001179 mDrawingState.bufferSurfaceFrameTX = it->second;
1180 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1181 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1182 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001183 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001184 mDrawingState.bufferSurfaceFrameTX =
Vishnu Nair39a74a92024-07-29 19:01:50 +00001185 createSurfaceFrameForBuffer(info, postTime, mTransactionName, gameMode);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001186 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001187
Vishnu Nair39a74a92024-07-29 19:01:50 +00001188 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName, gameMode);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001189}
1190
1191void Layer::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
Vishnu Nair39a74a92024-07-29 19:01:50 +00001192 nsecs_t postTime,
1193 gui::GameMode gameMode) {
Robert Carr6a160312021-05-17 12:08:20 -07001194 mDrawingState.frameTimelineInfo = info;
1195 mDrawingState.postTime = postTime;
1196 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001197 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001198
Robert Carr6a160312021-05-17 12:08:20 -07001199 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001200 bufferSurfaceFrameTX != nullptr) {
1201 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1202 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1203 // being used for BufferSurfaceFrame, don't create a new one.
1204 return;
1205 }
1206 }
1207 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1208 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1209 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001210 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1211 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Vishnu Nair39a74a92024-07-29 19:01:50 +00001212 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime, gameMode);
Robert Carr6a160312021-05-17 12:08:20 -07001213 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001214 } else {
1215 if (it->second->getPresentState() == PresentState::Presented) {
1216 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1217 // have been from previous vsync.
Vishnu Nair39a74a92024-07-29 19:01:50 +00001218 it->second = createSurfaceFrameForTransaction(info, postTime, gameMode);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001219 }
1220 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001221
Vishnu Nair39a74a92024-07-29 19:01:50 +00001222 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName, gameMode);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001223}
1224
1225void Layer::addSurfaceFrameDroppedForBuffer(
Ady Abraham5a3e3562023-06-07 10:32:08 -07001226 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t dropTime) {
1227 surfaceFrame->setDropTime(dropTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001228 surfaceFrame->setPresentState(PresentState::Dropped);
1229 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1230}
1231
1232void Layer::addSurfaceFramePresentedForBuffer(
1233 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1234 nsecs_t currentLatchTime) {
1235 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1236 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1237 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +00001238 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001239}
1240
1241std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
Vishnu Nair39a74a92024-07-29 19:01:50 +00001242 const FrameTimelineInfo& info, nsecs_t postTime, gui::GameMode gameMode) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001243 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001244 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1245 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001246 mTransactionName,
Vishnu Nair39a74a92024-07-29 19:01:50 +00001247 /*isBuffer*/ false, gameMode);
Rachel Leeed511ef2021-10-11 15:09:51 -07001248 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001249 // For Transactions, the post time is considered to be both queue and acquire fence time.
1250 surfaceFrame->setActualQueueTime(postTime);
1251 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001252 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1253 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001254 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001255 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001256 return surfaceFrame;
1257}
1258
1259std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
Vishnu Nair39a74a92024-07-29 19:01:50 +00001260 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName,
1261 gui::GameMode gameMode) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001262 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001263 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001264 getSequence(), mName, debugName,
Vishnu Nair39a74a92024-07-29 19:01:50 +00001265 /*isBuffer*/ true, gameMode);
Rachel Leeed511ef2021-10-11 15:09:51 -07001266 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001267 // For buffers, acquire fence time will set during latch.
1268 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001269 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1270 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001271 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001272 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001273 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001274}
1275
Ady Abraham5a3e3562023-06-07 10:32:08 -07001276void Layer::setFrameTimelineVsyncForSkippedFrames(const FrameTimelineInfo& info, nsecs_t postTime,
Vishnu Nair39a74a92024-07-29 19:01:50 +00001277 std::string debugName, gui::GameMode gameMode) {
Ady Abraham5a3e3562023-06-07 10:32:08 -07001278 if (info.skippedFrameVsyncId == FrameTimelineInfo::INVALID_VSYNC_ID) {
1279 return;
1280 }
1281
1282 FrameTimelineInfo skippedFrameTimelineInfo = info;
1283 skippedFrameTimelineInfo.vsyncId = info.skippedFrameVsyncId;
1284
1285 auto surfaceFrame =
1286 mFlinger->mFrameTimeline->createSurfaceFrameForToken(skippedFrameTimelineInfo,
1287 mOwnerPid, mOwnerUid,
1288 getSequence(), mName, debugName,
Vishnu Nair39a74a92024-07-29 19:01:50 +00001289 /*isBuffer*/ false, gameMode);
Ady Abraham5a3e3562023-06-07 10:32:08 -07001290 surfaceFrame->setActualStartTime(skippedFrameTimelineInfo.skippedFrameStartTimeNanos);
1291 // For Transactions, the post time is considered to be both queue and acquire fence time.
1292 surfaceFrame->setActualQueueTime(postTime);
1293 surfaceFrame->setAcquireFenceTime(postTime);
1294 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1295 if (fps) {
1296 surfaceFrame->setRenderRate(*fps);
1297 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001298 addSurfaceFrameDroppedForBuffer(surfaceFrame, postTime);
1299}
1300
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001301bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps,
1302 nsecs_t now) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001303 if (mDrawingState.frameRateForLayerTree == frameRate) {
1304 return false;
1305 }
1306
1307 mDrawingState.frameRateForLayerTree = frameRate;
1308 mFlinger->mScheduler
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001309 ->recordLayerHistory(sequence, layerProps, now, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001310 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001311 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001312}
1313
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001314Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1315 return getDrawingState().frameRateForLayerTree;
1316}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001317
Robert Carr1f0a16a2016-10-24 16:27:39 -07001318bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001319 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001320 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001321 if (parent != nullptr && parent->isHiddenByPolicy()) {
1322 return true;
1323 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001324 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1325 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1326 if (zOrderRelativeOf != nullptr) {
1327 if (zOrderRelativeOf->isHiddenByPolicy()) {
1328 return true;
1329 }
1330 }
1331 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001332 if (CC_UNLIKELY(!isTransformValid())) {
1333 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1334 return true;
1335 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001336 return s.flags & layer_state_t::eLayerHidden;
1337}
1338
David Sodman41fdfc92017-11-06 16:09:56 -08001339uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001340 // TODO: should we do something special if mSecure is set?
1341 if (mProtectedByApp) {
1342 // need a hardware-protected path to external video sink
1343 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001344 }
Riley Andrews03414a12014-07-01 14:22:59 -07001345 if (mPotentialCursor) {
1346 usage |= GraphicBuffer::USAGE_CURSOR;
1347 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001348 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001349 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001350}
1351
Mathias Agopian13127d82013-03-05 17:47:11 -08001352// ----------------------------------------------------------------------------
1353// debugging
1354// ----------------------------------------------------------------------------
1355
Yiwei Zhang5434a782018-12-05 18:06:32 -08001356void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001357 result.append(kDumpTableRowLength, '-');
1358 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001359 result.append(" Layer name\n");
1360 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001361 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001362 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001363 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001364 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001365 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001366 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1367 result.append(kDumpTableRowLength, '-');
1368 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001369}
1370
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001371void Layer::miniDump(std::string& result, const frontend::LayerSnapshot& snapshot,
1372 const DisplayDevice& display) const {
1373 const auto outputLayer = findOutputLayerForDisplay(&display, snapshot.path);
1374 if (!outputLayer) {
1375 return;
1376 }
1377
1378 StringAppendF(&result, " %s\n", snapshot.debugName.c_str());
1379 StringAppendF(&result, " %10zu | ", snapshot.globalZ);
1380 StringAppendF(&result, " %10d | ",
1381 snapshot.layerMetadata.getInt32(gui::METADATA_WINDOW_TYPE, 0));
1382 StringAppendF(&result, "%10s | ", toString(getCompositionType(outputLayer)).c_str());
1383 const auto& outputLayerState = outputLayer->getState();
1384 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1385 const Rect& frame = outputLayerState.displayFrame;
1386 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
1387 const FloatRect& crop = outputLayerState.sourceCrop;
1388 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
1389 crop.bottom);
1390 const auto frameRate = snapshot.frameRate;
Ady Abraham77d406d2023-11-22 15:00:23 -08001391 std::string frameRateStr;
1392 if (frameRate.vote.rate.isValid()) {
1393 StringAppendF(&frameRateStr, "%.2f", frameRate.vote.rate.getValue());
1394 }
Rachel Leece6e0042023-06-27 11:22:54 -07001395 if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
Ady Abraham77d406d2023-11-22 15:00:23 -08001396 StringAppendF(&result, "%6s %15s %17s", frameRateStr.c_str(),
Rachel Leece6e0042023-06-27 11:22:54 -07001397 ftl::enum_string(frameRate.vote.type).c_str(),
1398 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Ady Abraham77d406d2023-11-22 15:00:23 -08001399 } else if (frameRate.category != FrameRateCategory::Default) {
1400 StringAppendF(&result, "%6s %15s %17s", frameRateStr.c_str(),
1401 (std::string("Cat::") + ftl::enum_string(frameRate.category)).c_str(),
1402 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001403 } else {
1404 result.append(41, ' ');
1405 }
1406
1407 const auto focused = isLayerFocusedBasedOnPriority(snapshot.frameRateSelectionPriority);
1408 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1409
1410 result.append(kDumpTableRowLength, '-');
1411 result.append("\n");
1412}
1413
Yiwei Zhang5434a782018-12-05 18:06:32 -08001414void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001415 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001416}
1417
Svetoslavd85084b2014-03-20 10:28:31 -07001418void Layer::clearFrameStats() {
1419 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001420}
1421
Jamie Gennis6547ff42013-07-16 20:12:42 -07001422void Layer::logFrameStats() {
1423 mFrameTracker.logAndResetStats(mName);
1424}
1425
Svetoslavd85084b2014-03-20 10:28:31 -07001426void Layer::getFrameStats(FrameStats* outStats) const {
1427 mFrameTracker.getStats(outStats);
1428}
1429
Vishnu Nair76554eb2022-12-09 03:38:36 +00001430void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1431 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
Vishnu Nair3be61902023-04-26 19:47:29 -07001432 StringAppendF(&result, "Layer %s%s pid:%d uid:%d%s\n", getName().c_str(), hasBuffer.c_str(),
1433 mOwnerPid, mOwnerUid, isHandleAlive() ? " handleAlive" : "");
Vishnu Nair0f085c62019-08-30 08:49:12 -07001434}
1435
Brian Anderson5ea5e592016-12-01 16:54:33 -08001436void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001437 const int32_t layerId = getSequence();
1438 mFlinger->mTimeStats->onDestroy(layerId);
1439 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001440}
1441
Vishnu Nair787aa782023-03-17 13:46:46 -07001442size_t Layer::getDescendantCount() const {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001443 size_t count = 0;
Vishnu Nair787aa782023-03-17 13:46:46 -07001444 for (const sp<Layer>& child : mDrawingChildren) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001445 count += 1 + child->getChildrenCount();
1446 }
1447 return count;
1448}
1449
Robert Carr1f0a16a2016-10-24 16:27:39 -07001450void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001451 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001452 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001453
Robert Carr1f0a16a2016-10-24 16:27:39 -07001454 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001455 layer->setParent(sp<Layer>::fromExisting(this));
Robert Carr1f0a16a2016-10-24 16:27:39 -07001456}
1457
1458ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001459 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001460 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001461
Robert Carr1323c952019-01-28 18:13:27 -08001462 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001463 const auto removeResult = mCurrentChildren.remove(layer);
1464
Ady Abraham60e42ea2020-03-09 19:17:31 -07001465 return removeResult;
1466}
1467
Robert Carr15eae092018-03-23 13:43:53 -07001468void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001469 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001470 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001471 const float parentShadowRadius =
1472 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001473 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001474 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001475 }
1476}
1477
chaviwf1961f72017-09-18 16:41:07 -07001478bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001479 sp<Layer> newParent;
1480 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001481 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001482 if (newParent == nullptr) {
1483 ALOGE("Unable to promote Layer handle");
1484 return false;
1485 }
1486 if (newParent == this) {
1487 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1488 return false;
1489 }
1490 }
1491
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001492 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001493 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001494 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001495 }
1496
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001497 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001498 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001499 if (!newParent->isRemovedFromCurrentState()) {
1500 addToCurrentState();
1501 } else {
1502 onRemovedFromCurrentState();
1503 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001504 } else {
1505 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001506 }
1507
chaviw06178942017-07-27 10:25:59 -07001508 return true;
1509}
1510
Peiyong Lind3788632018-09-18 16:01:31 -07001511bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001512 static const mat4 identityMatrix = mat4();
1513
Robert Carr6a160312021-05-17 12:08:20 -07001514 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001515 return false;
1516 }
Robert Carr6a160312021-05-17 12:08:20 -07001517 ++mDrawingState.sequence;
1518 mDrawingState.colorTransform = matrix;
1519 mDrawingState.hasColorTransform = matrix != identityMatrix;
1520 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001521 setTransactionFlags(eTransactionNeeded);
1522 return true;
1523}
1524
chaviwf66724d2018-11-28 16:35:21 -08001525mat4 Layer::getColorTransform() const {
1526 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001527 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001528 colorTransform = parent->getColorTransform() * colorTransform;
1529 }
1530 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001531}
1532
1533bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001534 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001535 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001536 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1537 }
1538 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001539}
1540
Chia-I Wu11481472018-05-04 10:43:19 -07001541bool Layer::isLegacyDataSpace() const {
1542 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001543 return !(getDataSpace() &
1544 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1545 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001546}
1547
Robert Carr1f0a16a2016-10-24 16:27:39 -07001548void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001549 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001550}
1551
Robert Carr6a160312021-05-17 12:08:20 -07001552int32_t Layer::getZ(LayerVector::StateSet) const {
1553 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001554}
1555
Robert Carr1c5481e2019-07-01 14:42:27 -07001556bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001557 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001558 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001559 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001560}
1561
David Sodman41fdfc92017-11-06 16:09:56 -08001562__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001563 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001564 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1565 "makeTraversalList received invalid stateSet");
1566 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1567 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001568 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001569
Robert Carr29abff82017-12-04 13:51:20 -08001570 if (state.zOrderRelatives.size() == 0) {
1571 *outSkipRelativeZUsers = true;
1572 return children;
1573 }
1574
chaviwfd462612018-05-31 16:11:27 -07001575 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001576 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001577 sp<Layer> strongRelative = weakRelative.promote();
1578 if (strongRelative != nullptr) {
1579 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001580 }
1581 }
1582
Dan Stoza412903f2017-04-27 13:42:17 -07001583 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001584 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001585 continue;
1586 }
Robert Carrdb66e622017-04-10 16:55:57 -07001587 traverse.add(child);
1588 }
1589
1590 return traverse;
1591}
1592
Robert Carr1f0a16a2016-10-24 16:27:39 -07001593/**
Robert Carrdb66e622017-04-10 16:55:57 -07001594 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001595 */
Dan Stoza412903f2017-04-27 13:42:17 -07001596void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001597 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1598 // produce a new list for traversing, including our relatives, and not including our children
1599 // who are relatives of another surface. In the case that there are no relative Z,
1600 // makeTraversalList returns our children directly to avoid significant overhead.
1601 // However in this case we need to take the responsibility for filtering children which
1602 // are relatives of another surface here.
1603 bool skipRelativeZUsers = false;
1604 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001605
Robert Carr1f0a16a2016-10-24 16:27:39 -07001606 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001607 for (; i < list.size(); i++) {
1608 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001609 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1610 continue;
1611 }
1612
chaviw301b1d82019-11-06 13:15:09 -08001613 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001614 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001615 }
Dan Stoza412903f2017-04-27 13:42:17 -07001616 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001617 }
Robert Carr29abff82017-12-04 13:51:20 -08001618
Dan Stoza412903f2017-04-27 13:42:17 -07001619 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001620 for (; i < list.size(); i++) {
1621 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001622
Robert Carr29abff82017-12-04 13:51:20 -08001623 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1624 continue;
1625 }
Dan Stoza412903f2017-04-27 13:42:17 -07001626 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001627 }
1628}
1629
1630/**
Robert Carrdb66e622017-04-10 16:55:57 -07001631 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001632 */
Dan Stoza412903f2017-04-27 13:42:17 -07001633void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1634 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001635 // See traverseInZOrder for documentation.
1636 bool skipRelativeZUsers = false;
1637 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001638
Robert Carr1f0a16a2016-10-24 16:27:39 -07001639 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001640 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001641 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001642
1643 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1644 continue;
1645 }
1646
chaviw301b1d82019-11-06 13:15:09 -08001647 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001648 break;
1649 }
Dan Stoza412903f2017-04-27 13:42:17 -07001650 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001651 }
Dan Stoza412903f2017-04-27 13:42:17 -07001652 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001653 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001654 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001655
1656 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1657 continue;
1658 }
1659
Dan Stoza412903f2017-04-27 13:42:17 -07001660 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001661 }
1662}
1663
Edgar Arriaga844fa672020-01-16 14:21:42 -08001664void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1665 visitor(this);
1666 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001667 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001668 for (const sp<Layer>& child : children) {
1669 child->traverse(state, visitor);
1670 }
1671}
1672
Vishnu Nair787aa782023-03-17 13:46:46 -07001673void Layer::traverseChildren(const LayerVector::Visitor& visitor) {
1674 for (const sp<Layer>& child : mDrawingChildren) {
1675 visitor(child.get());
1676 }
1677}
1678
chaviw4b129c22018-04-09 16:19:43 -07001679LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
1680 const std::vector<Layer*>& layersInTree) {
1681 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1682 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07001683 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1684 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001685 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001686
chaviwfd462612018-05-31 16:11:27 -07001687 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07001688 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1689 sp<Layer> strongRelative = weakRelative.promote();
1690 // Only add relative layers that are also descendents of the top most parent of the tree.
1691 // If a relative layer is not a descendent, then it should be ignored.
1692 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
1693 traverse.add(strongRelative);
1694 }
1695 }
1696
1697 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07001698 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07001699 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
1700 // descendent of the top most parent of the tree. If it's not a descendent, then just add
1701 // the child here since it won't be added later as a relative.
1702 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
1703 childState.zOrderRelativeOf.promote().get())) {
1704 continue;
1705 }
1706 traverse.add(child);
1707 }
1708
1709 return traverse;
1710}
1711
1712void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
1713 LayerVector::StateSet stateSet,
1714 const LayerVector::Visitor& visitor) {
1715 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07001716
1717 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07001718 for (; i < list.size(); i++) {
1719 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08001720 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07001721 break;
1722 }
chaviw4b129c22018-04-09 16:19:43 -07001723 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001724 }
chaviw4b129c22018-04-09 16:19:43 -07001725
chaviwa76b2712017-09-20 12:02:26 -07001726 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07001727 for (; i < list.size(); i++) {
1728 const auto& relative = list[i];
1729 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07001730 }
1731}
1732
chaviw4b129c22018-04-09 16:19:43 -07001733std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
1734 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1735 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
1736
1737 std::vector<Layer*> layersInTree = {this};
1738 for (size_t i = 0; i < children.size(); i++) {
1739 const auto& child = children[i];
1740 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
1741 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
1742 }
1743
1744 return layersInTree;
1745}
1746
1747void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
1748 const LayerVector::Visitor& visitor) {
1749 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
1750 std::sort(layersInTree.begin(), layersInTree.end());
1751 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
1752}
1753
Peiyong Linefefaac2018-08-17 12:27:51 -07001754ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08001755 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001756}
1757
Garfield Tan2c1782c2022-02-16 15:25:05 -08001758bool Layer::isTransformValid() const {
1759 float transformDet = getTransform().det();
1760 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
1761}
1762
chaviw13fdc492017-06-27 12:40:18 -07001763half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001764 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001765
chaviw13fdc492017-06-27 12:40:18 -07001766 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1767 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07001768}
Robert Carr6452f122017-03-21 10:41:29 -07001769
Vishnu Nair6213bd92020-05-08 17:42:25 -07001770ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07001771 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001772 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
1773 return fixedTransformHint;
1774 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001775 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07001776 if (!p) return fixedTransformHint;
1777 return p->getFixedTransformHint();
1778}
1779
chaviw13fdc492017-06-27 12:40:18 -07001780half4 Layer::getColor() const {
1781 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001782 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07001783}
Robert Carr6452f122017-03-21 10:41:29 -07001784
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001785int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00001786 if (getDrawingState().backgroundBlurRadius == 0) {
1787 return 0;
1788 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01001789
Vishnu Nair29810f72022-07-01 16:38:41 +00001790 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01001791 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
1792 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001793}
1794
Galia Peychevae0acf382021-04-12 21:22:34 +02001795const std::vector<BlurRegion> Layer::getBlurRegions() const {
1796 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02001797 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02001798 for (auto& region : regionsCopy) {
1799 region.alpha = region.alpha * layerAlpha;
1800 }
1801 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001802}
1803
Vishnu Naire14c6b32022-08-06 04:20:15 +00001804RoundedCornerState Layer::getRoundedCornerState() const {
Leon Scroggins IIIc1dbfcb2022-03-21 16:48:10 -04001805 // Today's DPUs cannot do rounded corners. If RenderEngine cannot render
1806 // protected content, remove rounded corners from protected content so it
1807 // can be rendered by the DPU.
1808 if (isProtected() && !mFlinger->getRenderEngine().supportsProtectedContent()) {
1809 return {};
1810 }
1811
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001812 // Get parent settings
1813 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001814 const auto& parent = mDrawingParent.promote();
1815 if (parent != nullptr) {
1816 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001817 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001818 ui::Transform t = getActiveTransform(getDrawingState());
1819 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001820 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001821 parentSettings.radius.x *= t.getScaleX();
1822 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001823 }
1824 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001825
1826 // Get layer settings
1827 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001828 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001829 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001830 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001831
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001832 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001833 // If the parent and the layer have rounded corner settings, use the parent settings if the
1834 // parent crop is entirely inside the layer crop.
1835 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
1836 if (parentSettings.cropRect.left > layerCropRect.left &&
1837 parentSettings.cropRect.top > layerCropRect.top &&
1838 parentSettings.cropRect.right < layerCropRect.right &&
1839 parentSettings.cropRect.bottom < layerCropRect.bottom) {
1840 return parentSettings;
1841 } else {
1842 return layerSettings;
1843 }
Vishnu Nairb1845592021-10-07 12:17:57 -07001844 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001845 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001846 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07001847 return parentSettings;
1848 }
1849 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001850}
1851
Robert Carr88b85e12022-03-21 15:47:35 -07001852bool Layer::findInHierarchy(const sp<Layer>& l) {
1853 if (l == this) {
1854 return true;
1855 }
1856 for (auto& child : mDrawingChildren) {
1857 if (child->findInHierarchy(l)) {
1858 return true;
1859 }
1860 }
1861 return false;
1862}
1863
Robert Carr1f0a16a2016-10-24 16:27:39 -07001864void Layer::commitChildList() {
1865 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
1866 const auto& child = mCurrentChildren[i];
1867 child->commitChildList();
1868 }
1869 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07001870 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07001871 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
1872 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1873 if (zOrderRelativeOf == nullptr) return;
1874 if (findInHierarchy(zOrderRelativeOf)) {
1875 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
1876 zOrderRelativeOf->mName.c_str());
1877 ALOGE("Severing rel Z loop, potentially dangerous");
1878 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07001879 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07001880 }
1881 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001882}
1883
Vishnu Nair6fabeec2019-03-12 13:42:49 -07001884
chaviw3277faf2021-05-19 16:45:23 -05001885void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07001886 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00001887 mDrawingState.touchableRegionCrop =
1888 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07001889 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00001890 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07001891 setTransactionFlags(eTransactionNeeded);
1892}
1893
Kean Mariotti4ba343c2023-04-19 13:31:02 +00001894perfetto::protos::LayerProto* Layer::writeToProto(perfetto::protos::LayersProto& layersProto,
1895 uint32_t traceFlags) {
1896 perfetto::protos::LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08001897 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08001898 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
1899
Vishnu Nair00b90132021-11-05 14:03:40 -07001900 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Vishnu Nair2f65e972023-04-04 16:36:28 +00001901 ui::LayerStack layerStack =
1902 (mSnapshot) ? mSnapshot->outputFilter.layerStack : ui::INVALID_LAYER_STACK;
1903 writeCompositionStateToProto(layerProto, layerStack);
Alec Mouri6b9e9912020-01-21 10:50:24 -08001904 }
1905
chaviw08f3cb22020-01-13 13:17:21 -08001906 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08001907 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08001908 }
chaviw6d89e2d2020-01-14 14:42:01 -08001909
1910 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08001911}
1912
Kean Mariotti4ba343c2023-04-19 13:31:02 +00001913void Layer::writeCompositionStateToProto(perfetto::protos::LayerProto* layerProto,
1914 ui::LayerStack layerStack) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00001915 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
Vishnu Nair2f65e972023-04-04 16:36:28 +00001916 ftl::FakeGuard mainThreadGuard(kMainThreadContext);
Vishnu Nairea6ff812023-02-27 17:41:39 +00001917
1918 // Only populate for the primary display.
Vishnu Nair2f65e972023-04-04 16:36:28 +00001919 if (const auto display = mFlinger->getDisplayFromLayerStack(layerStack)) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00001920 const auto compositionType = getCompositionType(*display);
Kean Mariotti4ba343c2023-04-19 13:31:02 +00001921 layerProto->set_hwc_composition_type(
1922 static_cast<perfetto::protos::HwcCompositionType>(compositionType));
Vishnu Nair2f65e972023-04-04 16:36:28 +00001923 LayerProtoHelper::writeToProto(getVisibleRegion(display),
Vishnu Nairea6ff812023-02-27 17:41:39 +00001924 [&]() { return layerProto->mutable_visible_region(); });
1925 }
1926}
1927
Kean Mariotti4ba343c2023-04-19 13:31:02 +00001928void Layer::writeToProtoDrawingState(perfetto::protos::LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07001929 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08001930 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07001931 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08001932 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07001933 [&]() { return layerInfo->mutable_active_buffer(); });
1934 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
1935 layerInfo->mutable_buffer_transform());
1936 }
1937 layerInfo->set_invalidate(contentDirty);
1938 layerInfo->set_is_protected(isProtected());
1939 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
1940 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07001941 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07001942 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001943 layerInfo->set_corner_radius(
1944 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07001945 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
1946 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
1947 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
1948 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
1949 [&]() { return layerInfo->mutable_position(); });
1950 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07001951 LayerProtoHelper::writeToProto(surfaceDamageRegion,
1952 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07001953
Vishnu Nair00b90132021-11-05 14:03:40 -07001954 if (hasColorTransform()) {
1955 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07001956 }
1957
Vishnu Nair60db8c02020-04-02 11:55:16 -07001958 LayerProtoHelper::writeToProto(mSourceBounds,
1959 [&]() { return layerInfo->mutable_source_bounds(); });
1960 LayerProtoHelper::writeToProto(mScreenBounds,
1961 [&]() { return layerInfo->mutable_screen_bounds(); });
1962 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
1963 [&]() { return layerInfo->mutable_corner_radius_crop(); });
1964 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07001965}
1966
Kean Mariotti4ba343c2023-04-19 13:31:02 +00001967void Layer::writeToProtoCommonState(perfetto::protos::LayerProto* layerInfo,
1968 LayerVector::StateSet stateSet, uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07001969 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1970 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001971 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07001972
chaviw766c9c52021-02-10 17:36:47 -08001973 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07001974
Vishnu Nair00b90132021-11-05 14:03:40 -07001975 layerInfo->set_id(sequence);
1976 layerInfo->set_name(getName().c_str());
1977 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07001978
Vishnu Nair00b90132021-11-05 14:03:40 -07001979 for (const auto& child : children) {
1980 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07001981 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001982
Vishnu Nair00b90132021-11-05 14:03:40 -07001983 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
1984 sp<Layer> strongRelative = weakRelative.promote();
1985 if (strongRelative != nullptr) {
1986 layerInfo->add_relatives(strongRelative->sequence);
1987 }
1988 }
1989
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001990 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07001991 [&]() { return layerInfo->mutable_transparent_region(); });
1992
1993 layerInfo->set_layer_stack(getLayerStack().id);
1994 layerInfo->set_z(state.z);
1995
1996 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
1997 return layerInfo->mutable_requested_position();
1998 });
1999
Vishnu Nair00b90132021-11-05 14:03:40 -07002000 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2001
2002 layerInfo->set_is_opaque(isOpaque(state));
2003
2004 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2005 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2006 LayerProtoHelper::writeToProto(state.color,
2007 [&]() { return layerInfo->mutable_requested_color(); });
2008 layerInfo->set_flags(state.flags);
2009
2010 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2011 layerInfo->mutable_requested_transform());
2012
2013 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2014 if (parent != nullptr) {
2015 layerInfo->set_parent(parent->sequence);
Vishnu Nair00b90132021-11-05 14:03:40 -07002016 }
2017
2018 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2019 if (zOrderRelativeOf != nullptr) {
2020 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
Vishnu Nair00b90132021-11-05 14:03:40 -07002021 }
2022
2023 layerInfo->set_is_relative_of(state.isRelativeOf);
2024
2025 layerInfo->set_owner_uid(mOwnerUid);
2026
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002027 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002028 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002029 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002030 info = fillInputInfo(
2031 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002032 } else {
2033 info = state.inputInfo;
2034 }
2035
2036 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002037 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002038 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002039
Vishnu Nair00b90132021-11-05 14:03:40 -07002040 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002041 auto protoMap = layerInfo->mutable_metadata();
2042 for (const auto& entry : state.metadata.mMap) {
2043 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2044 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002045 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002046
2047 LayerProtoHelper::writeToProto(state.destinationFrame,
2048 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002049}
2050
Robert Carr2e102c92018-10-23 12:11:15 -07002051bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002052 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002053}
2054
Prabir Pradhan33da9462022-06-14 14:55:57 +00002055// Applies the given transform to the region, while protecting against overflows caused by any
2056// offsets. If applying the offset in the transform to any of the Rects in the region would result
2057// in an overflow, they are not added to the output Region.
2058static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2059 const std::string& debugWindowName) {
2060 // Round the translation using the same rounding strategy used by ui::Transform.
2061 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2062 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2063
2064 ui::Transform transformWithoutOffset = t;
2065 transformWithoutOffset.set(0.f, 0.f);
2066
2067 const Region transformed = transformWithoutOffset.transform(r);
2068
2069 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2070 Region ret;
2071 for (const auto& rect : transformed) {
2072 Rect newRect;
2073 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2074 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2075 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2076 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2077 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2078 debugWindowName.c_str());
2079 continue;
2080 }
2081 ret.orSelf(newRect);
2082 }
2083 return ret;
2084}
2085
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002086void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002087 auto [inputBounds, inputBoundsValid] = getInputBounds(/*fillParentBounds=*/false);
2088 if (!inputBoundsValid) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002089 info.touchableRegion.clear();
chaviw7e72caf2020-12-02 16:50:43 -08002090 }
2091
Chavi Weingarten7f019192023-08-08 20:39:01 +00002092 info.frame = getInputBoundsInDisplaySpace(inputBounds, screenToDisplay);
chaviw1ff3d1e2020-07-01 15:53:47 -07002093
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002094 ui::Transform inputToLayer;
Vishnu Nairfed7c122023-03-18 01:54:43 +00002095 inputToLayer.set(inputBounds.left, inputBounds.top);
2096 const ui::Transform layerToScreen = getInputTransform();
2097 const ui::Transform inputToDisplay = screenToDisplay * layerToScreen * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002098
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002099 // InputDispatcher expects a display-to-input transform.
2100 info.transform = inputToDisplay.inverse();
2101
2102 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002103 info.touchableRegion =
2104 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002105}
2106
chaviw3277faf2021-05-19 16:45:23 -05002107void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002108 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002109 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002110 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002111 }
2112 if (p != nullptr) {
2113 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2114 }
2115}
2116
Vishnu Naira066d902021-09-13 18:40:17 -07002117gui::DropInputMode Layer::getDropInputMode() const {
2118 gui::DropInputMode mode = mDrawingState.dropInputMode;
2119 if (mode == gui::DropInputMode::ALL) {
2120 return mode;
2121 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002122 sp<Layer> parent = mDrawingParent.promote();
2123 if (parent) {
2124 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002125 if (parentMode != gui::DropInputMode::NONE) {
2126 return parentMode;
2127 }
2128 }
2129 return mode;
2130}
2131
2132void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002133 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002134 return;
2135 }
2136
2137 // Check if we need to drop input unconditionally
2138 gui::DropInputMode dropInputMode = getDropInputMode();
2139 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002140 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002141 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2142 return;
2143 }
2144
2145 // Check if we need to check if the window is obscured by parent
2146 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2147 return;
2148 }
2149
2150 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002151 sp<Layer> parent = mDrawingParent.promote();
2152 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002153 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002154 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2155 static_cast<float>(getAlpha()));
2156 }
2157
2158 // Check if the parent has cropped the buffer
2159 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2160 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002161 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002162 return;
2163 }
2164
2165 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2166 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2167 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2168 // match then the layer has not been cropped by its parents.
2169 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2170 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2171
2172 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002173 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002174 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2175 getDebugName());
2176 } else {
2177 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2178 // input if the window is obscured. This check should be done in surfaceflinger but the
2179 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2180 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002181 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002182 }
2183}
2184
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002185WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002186 if (!hasInputInfo()) {
2187 mDrawingState.inputInfo.name = getName();
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002188 mDrawingState.inputInfo.ownerUid = gui::Uid{mOwnerUid};
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00002189 mDrawingState.inputInfo.ownerPid = gui::Pid{mOwnerPid};
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002190 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Linnan Li13bf76a2024-05-05 19:18:02 +08002191 mDrawingState.inputInfo.displayId = toLogicalDisplayId(getLayerStack());
chaviw7e72caf2020-12-02 16:50:43 -08002192 }
2193
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002194 const ui::Transform& displayTransform =
2195 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2196
chaviw3277faf2021-05-19 16:45:23 -05002197 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002198 info.id = sequence;
Linnan Li13bf76a2024-05-05 19:18:02 +08002199 info.displayId = toLogicalDisplayId(getLayerStack());
chaviw7e72caf2020-12-02 16:50:43 -08002200
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002201 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002202
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002203 if (displayArgs.transform == nullptr) {
2204 // Do not let the window receive touches if it is not associated with a valid display
2205 // transform. We still allow the window to receive keys and prevent ANRs.
2206 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2207 }
2208
Patrick Williams1caf3b72023-03-31 10:59:10 -05002209 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !isVisibleForInput());
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002210
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002211 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002212 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002213 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002214
Vishnu Nair16a938f2021-09-24 07:14:54 -07002215 // If the window will be blacked out on a display because the display does not have the secure
2216 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002217 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002218 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002219 }
2220
Vishnu Nairfed7c122023-03-18 01:54:43 +00002221 sp<Layer> cropLayer = mDrawingState.touchableRegionCrop.promote();
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002222 if (info.replaceTouchableRegionWithCrop) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002223 Rect inputBoundsInDisplaySpace;
2224 if (!cropLayer) {
2225 FloatRect inputBounds = getInputBounds(/*fillParentBounds=*/true).first;
2226 inputBoundsInDisplaySpace = getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2227 } else {
2228 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2229 inputBoundsInDisplaySpace =
2230 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2231 }
2232 info.touchableRegion = Region(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002233 } else if (cropLayer != nullptr) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002234 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2235 Rect inputBoundsInDisplaySpace =
2236 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2237 info.touchableRegion = info.touchableRegion.intersect(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002238 }
2239
Winson Chunga30f7c92021-06-29 15:42:56 -07002240 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2241 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002242 if (isTrustedOverlay()) {
2243 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2244 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002245
chaviwaf87b3e2019-10-01 16:59:28 -07002246 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2247 // touches from going outside the cloned area.
2248 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002249 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002250 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2251 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002252 info.touchableRegion = info.touchableRegion.intersect(rect);
2253 }
2254 }
2255
Vishnu Nair494a2e42023-11-10 17:21:19 -08002256 Rect bufferSize = getBufferSize(getDrawingState());
2257 info.contentSize = Size(bufferSize.width(), bufferSize.height());
2258
Robert Carr720e5062018-07-30 17:45:14 -07002259 return info;
2260}
2261
Vishnu Nairfed7c122023-03-18 01:54:43 +00002262Rect Layer::getInputBoundsInDisplaySpace(const FloatRect& inputBounds,
2263 const ui::Transform& screenToDisplay) {
2264 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2265 // frame and transform used for the layer, which determines the bounds and the coordinate space
2266 // within which the layer will receive input.
2267
2268 // Coordinate space definitions:
2269 // - display: The display device's coordinate space. Correlates to pixels on the display.
2270 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2271 // - layer: The coordinate space of this layer.
2272 // - input: The coordinate space in which this layer will receive input events. This could be
2273 // different than layer space if a surfaceInset is used, which changes the origin
2274 // of the input space.
2275
2276 // Crop the input bounds to ensure it is within the parent's bounds.
2277 const FloatRect croppedInputBounds = mBounds.intersect(inputBounds);
2278 const ui::Transform layerToScreen = getInputTransform();
2279 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
2280 return Rect{layerToDisplay.transform(croppedInputBounds)};
2281}
2282
chaviwaf87b3e2019-10-01 16:59:28 -07002283sp<Layer> Layer::getClonedRoot() {
2284 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002285 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002286 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002287 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002288 return nullptr;
2289 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002290 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002291}
2292
Robert Carredd13602020-04-13 17:24:34 -07002293bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002294 return mDrawingState.inputInfo.token != nullptr ||
2295 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002296}
2297
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002298compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002299 const DisplayDevice* display) const {
2300 if (!display) return nullptr;
Vishnu Naird47bcee2023-02-24 18:08:51 +00002301 sp<LayerFE> layerFE;
2302 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
2303 for (auto& [p, layer] : mLayerFEs) {
2304 if (p == path) {
2305 layerFE = layer;
2306 }
2307 }
2308
2309 if (!layerFE) return nullptr;
2310 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002311}
2312
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002313compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
2314 const DisplayDevice* display, const frontend::LayerHierarchy::TraversalPath& path) const {
2315 if (!display) return nullptr;
2316 sp<LayerFE> layerFE;
2317 for (auto& [p, layer] : mLayerFEs) {
2318 if (p == path) {
2319 layerFE = layer;
2320 }
2321 }
2322
2323 if (!layerFE) return nullptr;
2324 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
2325}
2326
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002327Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2328 const auto outputLayer = findOutputLayerForDisplay(display);
2329 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002330}
2331
Patrick Williamsbb25f802022-08-30 23:02:34 +00002332void Layer::updateCloneBufferInfo() {
2333 if (!isClone() || !isClonedFromAlive()) {
2334 return;
2335 }
2336
2337 sp<Layer> clonedFrom = getClonedFrom();
2338 mBufferInfo = clonedFrom->mBufferInfo;
2339 mSidebandStream = clonedFrom->mSidebandStream;
2340 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2341 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2342 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2343
2344 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2345 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2346 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2347 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2348 // the cloned drawingState again.
2349 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2350 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2351 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2352 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2353
2354 cloneDrawingState(clonedFrom.get());
2355
2356 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2357 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2358 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2359 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002360}
chaviw74b03172019-08-19 11:09:03 -07002361
Vishnu Nair3be61902023-04-26 19:47:29 -07002362bool Layer::updateMirrorInfo(const std::deque<Layer*>& cloneRootsPendingUpdates) {
chaviw74b03172019-08-19 11:09:03 -07002363 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2364 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2365 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2366 // that case, we want to delete the reference to the clone since we want it to get
2367 // destroyed. The root, this layer, will still be around since the client can continue
2368 // to hold a reference, but no cloned layers will be displayed.
2369 mClonedChild = nullptr;
Vishnu Nair3be61902023-04-26 19:47:29 -07002370 return true;
chaviw74b03172019-08-19 11:09:03 -07002371 }
2372
2373 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2374 // If the real layer exists and is in current state, add the clone as a child of the root.
2375 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2376 // copied to drawingState for the root layer. So the clonedChild is always removed from
2377 // drawingState and then needs to be added back each traversal.
2378 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2379 addChildToDrawing(mClonedChild);
2380 }
2381
2382 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002383 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002384 mClonedChild->updateClonedRelatives(clonedLayersMap);
Vishnu Nair3be61902023-04-26 19:47:29 -07002385
2386 for (Layer* root : cloneRootsPendingUpdates) {
2387 if (clonedLayersMap.find(sp<Layer>::fromExisting(root)) != clonedLayersMap.end()) {
2388 return false;
2389 }
2390 }
2391 return true;
chaviw74b03172019-08-19 11:09:03 -07002392}
2393
2394void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2395 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2396 // to the clone. If the real layer is no longer alive, continue traversing the children
2397 // since we may be able to pull out other children that are still alive.
2398 if (isClonedFromAlive()) {
2399 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002400 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002401 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002402 }
2403
2404 // The clone layer may have children in drawingState since they may have been created and
2405 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2406 // that already exist, since we can just re-use them.
2407 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2408 // not updated in the regular traversal. They are skipped since the root will lose the
2409 // reference to them when it copies its currentChildren to drawing.
2410 for (sp<Layer>& child : mDrawingChildren) {
2411 child->updateClonedDrawingState(clonedLayersMap);
2412 }
2413}
2414
2415void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2416 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2417 mDrawingChildren.clear();
2418
2419 if (!isClonedFromAlive()) {
2420 return;
2421 }
2422
2423 sp<Layer> clonedFrom = getClonedFrom();
2424 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2425 if (child == mirrorRoot) {
2426 // This is to avoid cyclical mirroring.
2427 continue;
2428 }
2429 sp<Layer> clonedChild = clonedLayersMap[child];
2430 if (clonedChild == nullptr) {
Melody Hsu12ecd082024-04-17 19:03:13 +00002431 clonedChild = child->createClone();
chaviw74b03172019-08-19 11:09:03 -07002432 clonedLayersMap[child] = clonedChild;
2433 }
2434 addChildToDrawing(clonedChild);
2435 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2436 }
2437}
2438
chaviwaf87b3e2019-10-01 16:59:28 -07002439void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2440 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2441 if (cropLayer != nullptr) {
2442 if (clonedLayersMap.count(cropLayer) == 0) {
2443 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2444 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002445 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002446 } else {
2447 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2448 mDrawingState.touchableRegionCrop = clonedCropLayer;
2449 }
2450 }
2451 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2452 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002453 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002454}
2455
2456void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002457 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002458 mDrawingState.zOrderRelatives.clear();
2459
2460 if (!isClonedFromAlive()) {
2461 return;
2462 }
2463
chaviwaf87b3e2019-10-01 16:59:28 -07002464 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002465 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002466 const sp<Layer>& relative = relativeWeak.promote();
2467 if (clonedLayersMap.count(relative) > 0) {
2468 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002469 mDrawingState.zOrderRelatives.add(clonedRelative);
2470 }
2471 }
2472
2473 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2474 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2475 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2476 // still traverse the children, but the layer with the missing relativeOf will not be shown
2477 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002478 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2479 if (clonedLayersMap.count(relativeOf) > 0) {
2480 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002481 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2482 }
2483
chaviwaf87b3e2019-10-01 16:59:28 -07002484 updateClonedInputInfo(clonedLayersMap);
2485
chaviw74b03172019-08-19 11:09:03 -07002486 for (sp<Layer>& child : mDrawingChildren) {
2487 child->updateClonedRelatives(clonedLayersMap);
2488 }
2489}
2490
2491void Layer::addChildToDrawing(const sp<Layer>& layer) {
2492 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002493 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002494}
2495
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002496bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002497 const State& s(mDrawingState);
2498 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2499 return true;
2500 }
2501
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002502 sp<Layer> parent = mDrawingParent.promote();
2503 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002504}
2505
Robert Carr6a0382d2021-07-01 15:57:17 -07002506void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2507 mClonedChild = clonedChild;
2508 mHadClonedChild = true;
Vishnu Nair3be61902023-04-26 19:47:29 -07002509 mFlinger->mLayerMirrorRoots.push_back(this);
Robert Carr6a0382d2021-07-01 15:57:17 -07002510}
2511
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002512bool Layer::setDropInputMode(gui::DropInputMode mode) {
2513 if (mDrawingState.dropInputMode == mode) {
2514 return false;
2515 }
2516 mDrawingState.dropInputMode = mode;
2517 return true;
2518}
2519
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002520void Layer::cloneDrawingState(const Layer* from) {
2521 mDrawingState = from->mDrawingState;
2522 // Skip callback info since they are not applicable for cloned layers.
2523 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002524 // TODO (b/238781169) currently broken for mirror layers because we do not
2525 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002526 mDrawingState.callbackHandles = {};
2527}
2528
Patrick Williamsbb25f802022-08-30 23:02:34 +00002529void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2530 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08002531 const sp<Fence>& releaseFence) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002532 if (!listener) {
2533 return;
2534 }
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002535 SFTRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
liulijuneb489f62022-10-17 22:02:14 +08002536 uint32_t currentMaxAcquiredBufferCount =
2537 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Patrick Williams4b9507d2024-07-25 09:55:52 -05002538 listener->onReleaseBuffer({buffer->getId(), framenumber},
2539 releaseFence ? releaseFence : Fence::NO_FENCE,
2540 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002541}
2542
Melody Hsu793f8362024-01-08 20:00:35 +00002543sp<CallbackHandle> Layer::findCallbackHandle() {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002544 // If we are displayed on multiple displays in a single composition cycle then we would
2545 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2546 // For example we can only use it if all the displays are client comp, and we need
2547 // to merge all the client comp fences. We could do this, but for now we just
2548 // disable the optimization when a layer is composed on multiple displays.
2549 if (mClearClientCompositionFenceOnLayerDisplayed) {
2550 mLastClientCompositionFence = nullptr;
2551 } else {
2552 mClearClientCompositionFenceOnLayerDisplayed = true;
2553 }
2554
2555 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2556 // buffer that was presented on this layer. The first transaction that came in this frame that
2557 // replaced the previous buffer on this layer needs this release fence, because the fence will
2558 // let the client know when that previous buffer is removed from the screen.
2559 //
2560 // Every other transaction on this layer does not need a release fence because no other
2561 // Transactions that were set on this layer this frame are going to have their preceding buffer
2562 // removed from the display this frame.
2563 //
2564 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2565 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2566 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2567 // the previous buffer will be released this frame. The third transaction also contains a
2568 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2569 // transaction will now no longer be presented so it is released immediately and the third
2570 // transaction doesn't need a previous release fence.
2571 sp<CallbackHandle> ch;
2572 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002573 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002574 ch = handle;
2575 break;
2576 }
2577 }
Melody Hsu793f8362024-01-08 20:00:35 +00002578 return ch;
2579}
2580
2581void Layer::prepareReleaseCallbacks(ftl::Future<FenceResult> futureFenceResult,
2582 ui::LayerStack layerStack) {
2583 sp<CallbackHandle> ch = findCallbackHandle();
2584
2585 if (ch != nullptr) {
2586 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2587 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2588 ch->name = mName;
2589 } else {
Melody Hsue4ef87f2024-03-26 23:54:45 +00002590 // If we didn't get a release callback yet (e.g. some scenarios when capturing
2591 // screenshots asynchronously) then make sure we don't drop the fence.
2592 // Older fences for the same layer stack can be dropped when a new fence arrives.
2593 // An assumption here is that RenderEngine performs work sequentially, so an
2594 // incoming fence will not fire before an existing fence.
2595 mAdditionalPreviousReleaseFences.emplace_or_replace(layerStack,
2596 std::move(futureFenceResult));
Melody Hsu793f8362024-01-08 20:00:35 +00002597 }
2598
2599 if (mBufferInfo.mBuffer) {
2600 mPreviouslyPresentedLayerStacks.push_back(layerStack);
2601 }
2602
2603 if (mDrawingState.frameNumber > 0) {
2604 mDrawingState.previousFrameNumber = mDrawingState.frameNumber;
2605 }
2606}
2607
2608void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult,
2609 ui::LayerStack layerStack,
2610 std::function<FenceResult(FenceResult)>&& continuation) {
2611 sp<CallbackHandle> ch = findCallbackHandle();
Alec Mouri9892aac2023-12-11 21:16:59 +00002612
2613 if (!FlagManager::getInstance().screenshot_fence_preservation() && continuation) {
2614 futureFenceResult = ftl::Future(futureFenceResult).then(std::move(continuation)).share();
2615 }
2616
Patrick Williamsbb25f802022-08-30 23:02:34 +00002617 if (ch != nullptr) {
2618 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
Melody Hsu793f8362024-01-08 20:00:35 +00002619 ch->previousSharedReleaseFences.emplace_back(std::move(futureFenceResult));
Patrick Williamsbb25f802022-08-30 23:02:34 +00002620 ch->name = mName;
Alec Mouri9892aac2023-12-11 21:16:59 +00002621 } else if (FlagManager::getInstance().screenshot_fence_preservation()) {
2622 // If we didn't get a release callback yet, e.g. some scenarios when capturing screenshots
2623 // asynchronously, then make sure we don't drop the fence.
Melody Hsu793f8362024-01-08 20:00:35 +00002624 mPreviousReleaseFenceAndContinuations.emplace_back(std::move(futureFenceResult),
2625 std::move(continuation));
Alec Mouri9892aac2023-12-11 21:16:59 +00002626 std::vector<FenceAndContinuation> mergedFences;
2627 sp<Fence> prevFence = nullptr;
2628 // For a layer that's frequently screenshotted, try to merge fences to make sure we don't
2629 // grow unbounded.
Melody Hsu793f8362024-01-08 20:00:35 +00002630 for (const auto& futureAndContinuation : mPreviousReleaseFenceAndContinuations) {
2631 auto result = futureAndContinuation.future.wait_for(0s);
Alec Mouri9892aac2023-12-11 21:16:59 +00002632 if (result != std::future_status::ready) {
Melody Hsu793f8362024-01-08 20:00:35 +00002633 mergedFences.emplace_back(futureAndContinuation);
Alec Mouri9892aac2023-12-11 21:16:59 +00002634 continue;
2635 }
2636
Melody Hsu793f8362024-01-08 20:00:35 +00002637 mergeFence(getDebugName(),
2638 futureAndContinuation.chain().get().value_or(Fence::NO_FENCE), prevFence);
Alec Mouri9892aac2023-12-11 21:16:59 +00002639 }
2640 if (prevFence != nullptr) {
2641 mergedFences.emplace_back(ftl::yield(FenceResult(std::move(prevFence))).share());
2642 }
2643
Melody Hsu793f8362024-01-08 20:00:35 +00002644 mPreviousReleaseFenceAndContinuations.swap(mergedFences);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002645 }
Alec Mouri9892aac2023-12-11 21:16:59 +00002646
Vishnu Nair316b7f42023-10-13 23:44:46 +00002647 if (mBufferInfo.mBuffer) {
2648 mPreviouslyPresentedLayerStacks.push_back(layerStack);
2649 }
Alec Mouri21d94322023-10-17 19:51:39 +00002650
2651 if (mDrawingState.frameNumber > 0) {
2652 mDrawingState.previousFrameNumber = mDrawingState.frameNumber;
2653 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002654}
2655
Patrick Williamsbb25f802022-08-30 23:02:34 +00002656void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2657 for (const auto& handle : mDrawingState.callbackHandles) {
Melody Hsu9af30702024-04-17 18:23:43 +00002658 handle->transformHint = mTransformHint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002659 handle->dequeueReadyTime = dequeueReadyTime;
2660 handle->currentMaxAcquiredBufferCount =
2661 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002662 SFTRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
2663 handle->previousReleaseCallbackId.framenumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002664 }
2665
2666 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002667 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002668 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2669 break;
2670 }
2671 }
2672
Pascal Mütschardd56514e2024-05-24 17:37:13 +02002673 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002674 mDrawingState.callbackHandles = {};
2675}
2676
2677bool Layer::willPresentCurrentTransaction() const {
2678 // Returns true if the most recent Transaction applied to CurrentState will be presented.
2679 return (getSidebandStreamChanged() || getAutoRefresh() ||
2680 (mDrawingState.modified &&
2681 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
2682}
2683
2684bool Layer::setTransform(uint32_t transform) {
2685 if (mDrawingState.bufferTransform == transform) return false;
2686 mDrawingState.bufferTransform = transform;
2687 mDrawingState.modified = true;
2688 setTransactionFlags(eTransactionNeeded);
2689 return true;
2690}
2691
2692bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
2693 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
2694 mDrawingState.sequence++;
2695 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
2696 mDrawingState.modified = true;
2697 setTransactionFlags(eTransactionNeeded);
2698 return true;
2699}
2700
2701bool Layer::setBufferCrop(const Rect& bufferCrop) {
2702 if (mDrawingState.bufferCrop == bufferCrop) return false;
2703
2704 mDrawingState.sequence++;
2705 mDrawingState.bufferCrop = bufferCrop;
2706
2707 mDrawingState.modified = true;
2708 setTransactionFlags(eTransactionNeeded);
2709 return true;
2710}
2711
2712bool Layer::setDestinationFrame(const Rect& destinationFrame) {
2713 if (mDrawingState.destinationFrame == destinationFrame) return false;
2714
2715 mDrawingState.sequence++;
2716 mDrawingState.destinationFrame = destinationFrame;
2717
2718 mDrawingState.modified = true;
2719 setTransactionFlags(eTransactionNeeded);
2720 return true;
2721}
2722
2723// Translate destination frame into scale and position. If a destination frame is not set, use the
2724// provided scale and position
2725bool Layer::updateGeometry() {
2726 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
2727 mDrawingState.destinationFrame.isEmpty()) {
2728 // If destination frame is not set, use the requested transform set via
2729 // Layer::setPosition and Layer::setMatrix.
2730 return assignTransform(&mDrawingState.transform, mRequestedTransform);
2731 }
2732
2733 Rect destRect = mDrawingState.destinationFrame;
2734 int32_t destW = destRect.width();
2735 int32_t destH = destRect.height();
2736 if (destRect.left < 0) {
2737 destRect.left = 0;
2738 destRect.right = destW;
2739 }
2740 if (destRect.top < 0) {
2741 destRect.top = 0;
2742 destRect.bottom = destH;
2743 }
2744
2745 if (!mDrawingState.buffer) {
2746 ui::Transform t;
2747 t.set(destRect.left, destRect.top);
2748 return assignTransform(&mDrawingState.transform, t);
2749 }
2750
2751 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
2752 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
2753 // Undo any transformations on the buffer.
2754 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
2755 std::swap(bufferWidth, bufferHeight);
2756 }
Leon Scroggins III85d4b222023-05-09 13:58:18 -04002757 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00002758 if (mDrawingState.transformToDisplayInverse) {
2759 if (invTransform & ui::Transform::ROT_90) {
2760 std::swap(bufferWidth, bufferHeight);
2761 }
2762 }
2763
2764 float sx = destW / static_cast<float>(bufferWidth);
2765 float sy = destH / static_cast<float>(bufferHeight);
2766 ui::Transform t;
2767 t.set(sx, 0, 0, sy);
2768 t.set(destRect.left, destRect.top);
2769 return assignTransform(&mDrawingState.transform, t);
2770}
2771
2772bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
2773 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
2774 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
2775 return false;
2776 }
2777
2778 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
2779
2780 mDrawingState.sequence++;
2781 mDrawingState.modified = true;
2782 setTransactionFlags(eTransactionNeeded);
2783
2784 return true;
2785}
2786
2787bool Layer::setPosition(float x, float y) {
2788 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
2789 return false;
2790 }
2791
2792 mRequestedTransform.set(x, y);
2793
2794 mDrawingState.sequence++;
2795 mDrawingState.modified = true;
2796 setTransactionFlags(eTransactionNeeded);
2797
2798 return true;
2799}
2800
Dorin Drimuse5374e52023-08-02 17:52:43 +00002801void Layer::releasePreviousBuffer() {
2802 mReleasePreviousBuffer = true;
2803 if (!mBufferInfo.mBuffer ||
2804 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
2805 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
2806 // If mDrawingState has a buffer, and we are about to update again
2807 // before swapping to drawing state, then the first buffer will be
2808 // dropped and we should decrement the pending buffer count and
2809 // call any release buffer callbacks if set.
2810 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
2811 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
2812 mDrawingState.acquireFence);
Dominic Lemire95c4ecc2024-07-09 12:06:18 -07002813 const int32_t layerId = getSequence();
2814 mFlinger->mTimeStats->removeTimeRecord(layerId, mDrawingState.frameNumber);
Dorin Drimuse5374e52023-08-02 17:52:43 +00002815 decrementPendingBufferCount();
2816 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
2817 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
2818 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX, systemTime());
2819 mDrawingState.bufferSurfaceFrameTX.reset();
2820 }
2821 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
2822 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
2823 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
2824 mLastClientCompositionFence);
2825 mLastClientCompositionFence = nullptr;
2826 }
2827}
2828
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002829void Layer::resetDrawingStateBufferInfo() {
2830 mDrawingState.producerId = 0;
2831 mDrawingState.frameNumber = 0;
Alec Mouri21d94322023-10-17 19:51:39 +00002832 mDrawingState.previousFrameNumber = 0;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002833 mDrawingState.releaseBufferListener = nullptr;
2834 mDrawingState.buffer = nullptr;
2835 mDrawingState.acquireFence = sp<Fence>::make(-1);
2836 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
2837 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
2838 mDrawingState.releaseBufferEndpoint = nullptr;
2839}
2840
Patrick Williamsbb25f802022-08-30 23:02:34 +00002841bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
2842 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
Vishnu Nair39a74a92024-07-29 19:01:50 +00002843 bool isAutoTimestamp, const FrameTimelineInfo& info, gui::GameMode gameMode) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002844 SFTRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00002845
2846 const bool frameNumberChanged =
2847 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
2848 const uint64_t frameNumber =
2849 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002850 SFTRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002851
2852 if (mDrawingState.buffer) {
Dorin Drimuse5374e52023-08-02 17:52:43 +00002853 releasePreviousBuffer();
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002854 } else if (buffer) {
Vishnu Nairc09c0232023-03-02 03:22:35 +00002855 // if we are latching a buffer for the first time then clear the mLastLatchTime since
2856 // we don't want to incorrectly classify a frame if we miss the desired present time.
2857 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002858 }
2859
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002860 mDrawingState.desiredPresentTime = desiredPresentTime;
2861 mDrawingState.isAutoTimestamp = isAutoTimestamp;
2862 mDrawingState.latchedVsyncId = info.vsyncId;
Ady Abraham55269162023-05-09 11:26:06 -07002863 mDrawingState.useVsyncIdForRefreshRateSelection = info.useForRefreshRateSelection;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002864 mDrawingState.modified = true;
2865 if (!buffer) {
2866 resetDrawingStateBufferInfo();
2867 setTransactionFlags(eTransactionNeeded);
2868 mDrawingState.bufferSurfaceFrameTX = nullptr;
Vishnu Nair39a74a92024-07-29 19:01:50 +00002869 setFrameTimelineVsyncForBufferlessTransaction(info, postTime, gameMode);
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002870 return true;
Dorin Drimuse5374e52023-08-02 17:52:43 +00002871 } else {
2872 // release sideband stream if it exists and a non null buffer is being set
2873 if (mDrawingState.sidebandStream != nullptr) {
Vishnu Nair39a74a92024-07-29 19:01:50 +00002874 setSidebandStream(nullptr, info, postTime, gameMode);
Dorin Drimuse5374e52023-08-02 17:52:43 +00002875 }
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002876 }
2877
Vishnu Naird1f74982023-06-15 20:16:51 -07002878 if ((mDrawingState.producerId > bufferData.producerId) ||
2879 ((mDrawingState.producerId == bufferData.producerId) &&
2880 (mDrawingState.frameNumber > frameNumber))) {
2881 ALOGE("Out of order buffers detected for %s producedId=%d frameNumber=%" PRIu64
2882 " -> producedId=%d frameNumber=%" PRIu64,
2883 getDebugName(), mDrawingState.producerId, mDrawingState.frameNumber,
2884 bufferData.producerId, frameNumber);
2885 TransactionTraceWriter::getInstance().invoke("out_of_order_buffers_", /*overwrite=*/false);
2886 }
2887
liulijuneb489f62022-10-17 22:02:14 +08002888 mDrawingState.producerId = bufferData.producerId;
Vishnu Nair63221212023-04-06 15:17:37 -07002889 mDrawingState.barrierProducerId =
2890 std::max(mDrawingState.producerId, mDrawingState.barrierProducerId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002891 mDrawingState.frameNumber = frameNumber;
Vishnu Nair63221212023-04-06 15:17:37 -07002892 mDrawingState.barrierFrameNumber =
2893 std::max(mDrawingState.frameNumber, mDrawingState.barrierFrameNumber);
2894
Patrick Williamsbb25f802022-08-30 23:02:34 +00002895 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
2896 mDrawingState.buffer = std::move(buffer);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002897 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
2898 ? bufferData.acquireFence
2899 : Fence::NO_FENCE;
2900 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
2901 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
2902 // We latched this buffer unsiganled, so we need to pass the acquire fence
2903 // on the callback instead of just the acquire time, since it's unknown at
2904 // this point.
2905 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
2906 } else {
2907 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
2908 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002909 setTransactionFlags(eTransactionNeeded);
2910
2911 const int32_t layerId = getSequence();
2912 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
Vishnu Nair39a74a92024-07-29 19:01:50 +00002913 mOwnerUid, postTime, gameMode);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002914
Vishnu Nair39a74a92024-07-29 19:01:50 +00002915 setFrameTimelineVsyncForBufferTransaction(info, postTime, gameMode);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002916
Nergi Rahardi39f510f2024-05-23 15:16:54 +09002917 if (bufferData.dequeueTime > 0) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002918 const uint64_t bufferId = mDrawingState.buffer->getId();
2919 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
Nergi Rahardi39f510f2024-05-23 15:16:54 +09002920 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber,
2921 bufferData.dequeueTime,
Patrick Williamsbb25f802022-08-30 23:02:34 +00002922 FrameTracer::FrameEvent::DEQUEUE);
2923 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
2924 FrameTracer::FrameEvent::QUEUE);
2925 }
2926
2927 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
Arthur Hungc70bee22023-06-02 01:35:52 +00002928
2929 // If the layer had been updated a TextureView, this would make sure the present time could be
2930 // same to TextureView update when it's a small dirty, and get the correct heuristic rate.
Jerry Chang36678002023-11-29 16:56:17 +00002931 if (mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +00002932 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
2933 mUsedVsyncIdForRefreshRateSelection = true;
2934 }
2935 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00002936 return true;
2937}
2938
Vishnu Nairef68d6d2023-02-28 06:18:27 +00002939void Layer::setDesiredPresentTime(nsecs_t desiredPresentTime, bool isAutoTimestamp) {
2940 mDrawingState.desiredPresentTime = desiredPresentTime;
2941 mDrawingState.isAutoTimestamp = isAutoTimestamp;
2942}
2943
Vishnu Nair47b7bb42023-09-29 16:27:33 -07002944void Layer::recordLayerHistoryBufferUpdate(const scheduler::LayerProps& layerProps, nsecs_t now) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002945 SFTRACE_CALL();
Vishnu Nairef68d6d2023-02-28 06:18:27 +00002946 const nsecs_t presentTime = [&] {
Ady Abraham55269162023-05-09 11:26:06 -07002947 if (!mDrawingState.isAutoTimestamp) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002948 SFTRACE_FORMAT_INSTANT("desiredPresentTime");
Ady Abraham55269162023-05-09 11:26:06 -07002949 return mDrawingState.desiredPresentTime;
2950 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00002951
Ady Abraham55269162023-05-09 11:26:06 -07002952 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
2953 const auto prediction =
2954 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
2955 mDrawingState.latchedVsyncId);
2956 if (prediction.has_value()) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002957 SFTRACE_FORMAT_INSTANT("predictedPresentTime");
Arthur Hungc70bee22023-06-02 01:35:52 +00002958 mMaxTimeForUseVsyncId = prediction->presentTime +
2959 scheduler::LayerHistory::kMaxPeriodForHistory.count();
Ady Abraham55269162023-05-09 11:26:06 -07002960 return prediction->presentTime;
2961 }
2962 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00002963
Jerry Chang36678002023-11-29 16:56:17 +00002964 if (!mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +00002965 return static_cast<nsecs_t>(0);
2966 }
2967
2968 // If the layer is not an application and didn't set an explicit rate or desiredPresentTime,
2969 // return "0" to tell the layer history that it will use the max refresh rate without
2970 // calculating the adaptive rate.
2971 if (mWindowType != WindowInfo::Type::APPLICATION &&
2972 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
2973 return static_cast<nsecs_t>(0);
2974 }
2975
2976 // Return the valid present time only when the layer potentially updated a TextureView so
2977 // LayerHistory could heuristically calculate the rate if the UI is continually updating.
2978 if (mUsedVsyncIdForRefreshRateSelection) {
2979 const auto prediction =
2980 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
2981 mDrawingState.latchedVsyncId);
2982 if (prediction.has_value()) {
2983 if (mMaxTimeForUseVsyncId >= prediction->presentTime) {
2984 return prediction->presentTime;
2985 }
2986 mUsedVsyncIdForRefreshRateSelection = false;
2987 }
2988 }
2989
Vishnu Nairef68d6d2023-02-28 06:18:27 +00002990 return static_cast<nsecs_t>(0);
2991 }();
Ady Abraham55269162023-05-09 11:26:06 -07002992
Vishnu Nair2665ca92024-07-09 22:08:15 +00002993 if (SFTRACE_ENABLED() && presentTime > 0) {
Ady Abraham55269162023-05-09 11:26:06 -07002994 const auto presentIn = TimePoint::fromNs(presentTime) - TimePoint::now();
Vishnu Nairbe0ad902024-06-27 23:38:43 +00002995 SFTRACE_FORMAT_INSTANT("presentIn %s", to_string(presentIn).c_str());
Ady Abraham55269162023-05-09 11:26:06 -07002996 }
2997
Vishnu Nair47b7bb42023-09-29 16:27:33 -07002998 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00002999 scheduler::LayerHistory::LayerUpdateType::Buffer);
3000}
3001
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003002void Layer::recordLayerHistoryAnimationTx(const scheduler::LayerProps& layerProps, nsecs_t now) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003003 const nsecs_t presentTime =
3004 mDrawingState.isAutoTimestamp ? 0 : mDrawingState.desiredPresentTime;
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003005 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003006 scheduler::LayerHistory::LayerUpdateType::AnimationTX);
3007}
3008
Patrick Williamsbb25f802022-08-30 23:02:34 +00003009bool Layer::setDataspace(ui::Dataspace dataspace) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003010 if (mDrawingState.dataspace == dataspace) return false;
3011 mDrawingState.dataspace = dataspace;
3012 mDrawingState.modified = true;
3013 setTransactionFlags(eTransactionNeeded);
3014 return true;
3015}
3016
John Reck68796592023-01-25 13:47:12 -05003017bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
Sally Qi963049b2023-03-23 14:06:21 -07003018 if (mDrawingState.currentHdrSdrRatio == currentBufferRatio &&
3019 mDrawingState.desiredHdrSdrRatio == desiredRatio)
John Reck68796592023-01-25 13:47:12 -05003020 return false;
Sally Qi963049b2023-03-23 14:06:21 -07003021 mDrawingState.currentHdrSdrRatio = currentBufferRatio;
3022 mDrawingState.desiredHdrSdrRatio = desiredRatio;
John Reck68796592023-01-25 13:47:12 -05003023 mDrawingState.modified = true;
3024 setTransactionFlags(eTransactionNeeded);
3025 return true;
3026}
3027
Alec Mouri1b0d4e12024-02-12 22:27:19 +00003028bool Layer::setDesiredHdrHeadroom(float desiredRatio) {
3029 if (mDrawingState.desiredHdrSdrRatio == desiredRatio) return false;
3030 mDrawingState.desiredHdrSdrRatio = desiredRatio;
3031 mDrawingState.modified = true;
3032 setTransactionFlags(eTransactionNeeded);
3033 return true;
3034}
3035
Alec Mourif4af03e2023-02-11 00:25:24 +00003036bool Layer::setCachingHint(gui::CachingHint cachingHint) {
3037 if (mDrawingState.cachingHint == cachingHint) return false;
3038 mDrawingState.cachingHint = cachingHint;
3039 mDrawingState.modified = true;
3040 setTransactionFlags(eTransactionNeeded);
3041 return true;
3042}
3043
Patrick Williamsbb25f802022-08-30 23:02:34 +00003044bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3045 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3046 mDrawingState.hdrMetadata = hdrMetadata;
3047 mDrawingState.modified = true;
3048 setTransactionFlags(eTransactionNeeded);
3049 return true;
3050}
3051
3052bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Sally Qi2b1b4292023-03-14 16:47:39 +00003053 if (mDrawingState.surfaceDamageRegion.hasSameRects(surfaceDamage)) return false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003054 mDrawingState.surfaceDamageRegion = surfaceDamage;
3055 mDrawingState.modified = true;
3056 setTransactionFlags(eTransactionNeeded);
Arthur Hung69f95222023-10-04 07:39:02 +00003057 setIsSmallDirty(surfaceDamage, getTransform());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003058 return true;
3059}
3060
3061bool Layer::setApi(int32_t api) {
3062 if (mDrawingState.api == api) return false;
3063 mDrawingState.api = api;
3064 mDrawingState.modified = true;
3065 setTransactionFlags(eTransactionNeeded);
3066 return true;
3067}
3068
Dorin Drimuse5374e52023-08-02 17:52:43 +00003069bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream, const FrameTimelineInfo& info,
Vishnu Nair39a74a92024-07-29 19:01:50 +00003070 nsecs_t postTime, gui::GameMode gameMode) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003071 if (mDrawingState.sidebandStream == sidebandStream) return false;
3072
3073 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3074 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3075 } else if (sidebandStream != nullptr) {
3076 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3077 }
3078
3079 mDrawingState.sidebandStream = sidebandStream;
3080 mDrawingState.modified = true;
Dorin Drimuse5374e52023-08-02 17:52:43 +00003081 if (sidebandStream != nullptr && mDrawingState.buffer != nullptr) {
3082 releasePreviousBuffer();
3083 resetDrawingStateBufferInfo();
3084 mDrawingState.bufferSurfaceFrameTX = nullptr;
Vishnu Nair39a74a92024-07-29 19:01:50 +00003085 setFrameTimelineVsyncForBufferlessTransaction(info, postTime, gameMode);
Dorin Drimuse5374e52023-08-02 17:52:43 +00003086 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003087 setTransactionFlags(eTransactionNeeded);
3088 if (!mSidebandStreamChanged.exchange(true)) {
3089 // mSidebandStreamChanged was false
3090 mFlinger->onLayerUpdate();
3091 }
3092 return true;
3093}
3094
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003095bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3096 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003097 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3098 if (handles.empty()) {
3099 mReleasePreviousBuffer = false;
3100 return false;
3101 }
3102
Pascal Muetschard81cef292023-02-06 12:18:52 +01003103 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003104 for (const auto& handle : handles) {
3105 // If this transaction set a buffer on this layer, release its previous buffer
3106 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3107
3108 // If this layer will be presented in this frame
3109 if (willPresent) {
3110 // If this transaction set an acquire fence on this layer, set its acquire time
3111 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3112 handle->frameNumber = mDrawingState.frameNumber;
Alec Mouri21d94322023-10-17 19:51:39 +00003113 handle->previousFrameNumber = mDrawingState.previousFrameNumber;
Melody Hsu793f8362024-01-08 20:00:35 +00003114 if (FlagManager::getInstance().ce_fence_promise() &&
Alec Mouri9892aac2023-12-11 21:16:59 +00003115 mPreviousReleaseBufferEndpoint == handle->listener) {
Melody Hsue4ef87f2024-03-26 23:54:45 +00003116 // Add fence from previous screenshot now so that it can be dispatched to the
Alec Mouri9892aac2023-12-11 21:16:59 +00003117 // client.
Melody Hsue4ef87f2024-03-26 23:54:45 +00003118 for (auto& [_, future] : mAdditionalPreviousReleaseFences) {
3119 handle->previousReleaseFences.emplace_back(std::move(future));
Alec Mouri9892aac2023-12-11 21:16:59 +00003120 }
3121 mAdditionalPreviousReleaseFences.clear();
Melody Hsu793f8362024-01-08 20:00:35 +00003122 } else if (FlagManager::getInstance().screenshot_fence_preservation() &&
3123 mPreviousReleaseBufferEndpoint == handle->listener) {
3124 // Add fences from previous screenshots now so that they can be dispatched to the
3125 // client.
3126 for (const auto& futureAndContinution : mPreviousReleaseFenceAndContinuations) {
3127 handle->previousSharedReleaseFences.emplace_back(futureAndContinution.chain());
3128 }
3129 mPreviousReleaseFenceAndContinuations.clear();
Alec Mouri9892aac2023-12-11 21:16:59 +00003130 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003131 // Store so latched time and release fence can be set
3132 mDrawingState.callbackHandles.push_back(handle);
3133
3134 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01003135 // Queue this handle to be notified below.
3136 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003137 }
3138 }
3139
Pascal Muetschard81cef292023-02-06 12:18:52 +01003140 if (!remainingHandles.empty()) {
3141 // Notify the transaction completed threads these handles are done. These are only the
3142 // handles that were not added to the mDrawingState, which will be notified later.
Pascal Mütschardd56514e2024-05-24 17:37:13 +02003143 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles);
Pascal Muetschard81cef292023-02-06 12:18:52 +01003144 }
3145
Patrick Williamsbb25f802022-08-30 23:02:34 +00003146 mReleasePreviousBuffer = false;
3147 mCallbackHandleAcquireTimeOrFence = -1;
3148
3149 return willPresent;
3150}
3151
3152Rect Layer::getBufferSize(const State& /*s*/) const {
3153 // for buffer state layers we use the display frame size as the buffer size.
3154
3155 if (mBufferInfo.mBuffer == nullptr) {
3156 return Rect::INVALID_RECT;
3157 }
3158
3159 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3160 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3161
3162 // Undo any transformations on the buffer and return the result.
3163 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3164 std::swap(bufWidth, bufHeight);
3165 }
3166
3167 if (getTransformToDisplayInverse()) {
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003168 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003169 if (invTransform & ui::Transform::ROT_90) {
3170 std::swap(bufWidth, bufHeight);
3171 }
3172 }
3173
3174 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3175}
3176
3177FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3178 if (mBufferInfo.mBuffer == nullptr) {
3179 return parentBounds;
3180 }
3181
3182 return getBufferSize(getDrawingState()).toFloatRect();
3183}
3184
3185bool Layer::fenceHasSignaled() const {
3186 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3187 return true;
3188 }
3189
3190 const bool fenceSignaled =
3191 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3192 if (!fenceSignaled) {
3193 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3194 TimeStats::LatchSkipReason::LateAcquire);
3195 }
3196
3197 return fenceSignaled;
3198}
3199
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003200void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003201 for (const auto& handle : mDrawingState.callbackHandles) {
3202 handle->refreshStartTime = refreshStartTime;
3203 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003204}
3205
3206void Layer::setAutoRefresh(bool autoRefresh) {
3207 mDrawingState.autoRefresh = autoRefresh;
3208}
3209
3210bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3211 // 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 +00003212 auto* snapshot = editLayerSnapshot();
3213 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003214
3215 if (mSidebandStreamChanged.exchange(false)) {
3216 const State& s(getDrawingState());
3217 // mSidebandStreamChanged was true
3218 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003219 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003220 if (mSidebandStream != nullptr) {
3221 setTransactionFlags(eTransactionNeeded);
3222 mFlinger->setTransactionFlags(eTraversalNeeded);
3223 }
3224 recomputeVisibleRegions = true;
3225
3226 return true;
3227 }
3228 return false;
3229}
3230
3231bool Layer::hasFrameUpdate() const {
3232 const State& c(getDrawingState());
3233 return (mDrawingStateModified || mDrawingState.modified) &&
3234 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3235}
3236
Vishnu Naird47bcee2023-02-24 18:08:51 +00003237void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003238 const State& s(getDrawingState());
3239
3240 if (!s.buffer) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003241 if (bgColorOnly || mBufferInfo.mBuffer) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003242 for (auto& handle : mDrawingState.callbackHandles) {
3243 handle->latchTime = latchTime;
3244 }
3245 }
3246 return;
3247 }
3248
3249 for (auto& handle : mDrawingState.callbackHandles) {
3250 if (handle->frameNumber == mDrawingState.frameNumber) {
3251 handle->latchTime = latchTime;
3252 }
3253 }
3254
3255 const int32_t layerId = getSequence();
3256 const uint64_t bufferId = mDrawingState.buffer->getId();
3257 const uint64_t frameNumber = mDrawingState.frameNumber;
3258 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3259 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3260 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3261
3262 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3263 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3264 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3265 FrameTracer::FrameEvent::LATCH);
3266
3267 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3268 if (bufferSurfaceFrame != nullptr &&
3269 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3270 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3271 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3272 // are processing the next state.
3273 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3274 mDrawingState.acquireFenceTime->getSignalTime(),
3275 latchTime);
3276 mDrawingState.bufferSurfaceFrameTX.reset();
3277 }
3278
3279 std::deque<sp<CallbackHandle>> remainingHandles;
3280 mFlinger->getTransactionCallbackInvoker()
3281 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3282 mDrawingState.callbackHandles = remainingHandles;
3283
3284 mDrawingStateModified = false;
3285}
3286
3287void Layer::gatherBufferInfo() {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003288 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3289 mPreviousReleaseBufferEndpoint = mBufferInfo.mReleaseBufferEndpoint;
3290 if (!mDrawingState.buffer) {
3291 mBufferInfo = {};
3292 return;
3293 }
3294
3295 if ((!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer))) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003296 decrementPendingBufferCount();
3297 }
3298
Patrick Williamsbb25f802022-08-30 23:02:34 +00003299 mBufferInfo.mBuffer = mDrawingState.buffer;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003300 mBufferInfo.mReleaseBufferEndpoint = mDrawingState.releaseBufferEndpoint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003301 mBufferInfo.mFence = mDrawingState.acquireFence;
3302 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3303 mBufferInfo.mPixelFormat =
3304 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3305 mBufferInfo.mFrameLatencyNeeded = true;
3306 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3307 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3308 mBufferInfo.mFence = mDrawingState.acquireFence;
3309 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3310 auto lastDataspace = mBufferInfo.mDataspace;
3311 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
Alec Mouri74c7ae12023-03-26 02:57:47 +00003312 if (mBufferInfo.mBuffer != nullptr) {
3313 auto& mapper = GraphicBufferMapper::get();
3314 // TODO: We should measure if it's faster to do a blind write if we're on newer api levels
3315 // and don't need to possibly remaps buffers.
3316 ui::Dataspace dataspace = ui::Dataspace::UNKNOWN;
3317 status_t err = OK;
3318 {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003319 SFTRACE_NAME("getDataspace");
Alec Mouri74c7ae12023-03-26 02:57:47 +00003320 err = mapper.getDataspace(mBufferInfo.mBuffer->getBuffer()->handle, &dataspace);
3321 }
3322 if (err != OK || dataspace != mBufferInfo.mDataspace) {
3323 {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003324 SFTRACE_NAME("setDataspace");
Alec Mouri74c7ae12023-03-26 02:57:47 +00003325 err = mapper.setDataspace(mBufferInfo.mBuffer->getBuffer()->handle,
3326 static_cast<ui::Dataspace>(mBufferInfo.mDataspace));
3327 }
3328
3329 // Some GPU drivers may cache gralloc metadata which means before we composite we need
3330 // to upsert RenderEngine's caches. Put in a special workaround to be backwards
3331 // compatible with old vendors, with a ticking clock.
3332 static const int32_t kVendorVersion =
Alec Mouri8a06fb72023-11-16 22:07:13 +00003333 base::GetIntProperty("ro.board.api_level", __ANDROID_API_FUTURE__);
Alec Mouri74c7ae12023-03-26 02:57:47 +00003334 if (const auto format =
3335 static_cast<aidl::android::hardware::graphics::common::PixelFormat>(
3336 mBufferInfo.mBuffer->getPixelFormat());
3337 err == OK && kVendorVersion < __ANDROID_API_U__ &&
3338 (format ==
3339 aidl::android::hardware::graphics::common::PixelFormat::
3340 IMPLEMENTATION_DEFINED ||
3341 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_420_888 ||
3342 format == aidl::android::hardware::graphics::common::PixelFormat::YV12 ||
3343 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_P010)) {
3344 mBufferInfo.mBuffer->remapBuffer();
3345 }
3346 }
3347 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003348 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003349 mFlinger->mHdrLayerInfoChanged = true;
3350 }
Sally Qi963049b2023-03-23 14:06:21 -07003351 if (mBufferInfo.mDesiredHdrSdrRatio != mDrawingState.desiredHdrSdrRatio) {
3352 mBufferInfo.mDesiredHdrSdrRatio = mDrawingState.desiredHdrSdrRatio;
John Reck68796592023-01-25 13:47:12 -05003353 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003354 }
3355 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3356 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3357 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3358 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3359 mBufferInfo.mApi = mDrawingState.api;
3360 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003361}
3362
3363Rect Layer::computeBufferCrop(const State& s) {
3364 if (s.buffer && !s.bufferCrop.isEmpty()) {
3365 Rect bufferCrop;
3366 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3367 return bufferCrop;
3368 } else if (s.buffer) {
3369 return s.buffer->getBounds();
3370 } else {
3371 return s.bufferCrop;
3372 }
3373}
3374
Melody Hsu12ecd082024-04-17 19:03:13 +00003375sp<Layer> Layer::createClone() {
Kean Mariotti4ba343c2023-04-19 13:31:02 +00003376 surfaceflinger::LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0,
3377 LayerMetadata());
Patrick Williams83f36b22022-09-14 17:57:35 +00003378 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003379 return layer;
3380}
3381
Patrick Williamsbb25f802022-08-30 23:02:34 +00003382void Layer::decrementPendingBufferCount() {
3383 int32_t pendingBuffers = --mPendingBufferTransactions;
3384 tracePendingBufferCount(pendingBuffers);
3385}
3386
3387void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003388 SFTRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003389}
3390
3391/*
3392 * We don't want to send the layer's transform to input, but rather the
3393 * parent's transform. This is because Layer's transform is
3394 * information about how the buffer is placed on screen. The parent's
3395 * transform makes more sense to send since it's information about how the
3396 * layer is placed on screen. This transform is used by input to determine
3397 * how to go from screen space back to window space.
3398 */
3399ui::Transform Layer::getInputTransform() const {
3400 if (!hasBufferOrSidebandStream()) {
3401 return getTransform();
3402 }
3403 sp<Layer> parent = mDrawingParent.promote();
3404 if (parent == nullptr) {
3405 return ui::Transform();
3406 }
3407
3408 return parent->getTransform();
3409}
3410
3411/**
Vishnu Nairfed7c122023-03-18 01:54:43 +00003412 * Returns the bounds used to fill the input frame and the touchable region.
3413 *
Patrick Williamsbb25f802022-08-30 23:02:34 +00003414 * Similar to getInputTransform, we need to update the bounds to include the transform.
3415 * This is because bounds don't include the buffer transform, where the input assumes
3416 * that's already included.
3417 */
Vishnu Nairfed7c122023-03-18 01:54:43 +00003418std::pair<FloatRect, bool> Layer::getInputBounds(bool fillParentBounds) const {
3419 Rect croppedBufferSize = getCroppedBufferSize(getDrawingState());
3420 FloatRect inputBounds = croppedBufferSize.toFloatRect();
3421 if (hasBufferOrSidebandStream() && croppedBufferSize.isValid() &&
3422 mDrawingState.transform.getType() != ui::Transform::IDENTITY) {
3423 inputBounds = mDrawingState.transform.transform(inputBounds);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003424 }
3425
Vishnu Nairfed7c122023-03-18 01:54:43 +00003426 bool inputBoundsValid = croppedBufferSize.isValid();
3427 if (!inputBoundsValid) {
3428 /**
3429 * Input bounds are based on the layer crop or buffer size. But if we are using
3430 * the layer bounds as the input bounds (replaceTouchableRegionWithCrop flag) then
3431 * we can use the parent bounds as the input bounds if the layer does not have buffer
3432 * or a crop. We want to unify this logic but because of compat reasons we cannot always
3433 * use the parent bounds. A layer without a buffer can get input. So when a window is
3434 * initially added, its touchable region can fill its parent layer bounds and that can
3435 * have negative consequences.
3436 */
3437 inputBounds = fillParentBounds ? mBounds : FloatRect{};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003438 }
Vishnu Nairfed7c122023-03-18 01:54:43 +00003439
3440 // Clamp surface inset to the input bounds.
3441 const float inset = static_cast<float>(mDrawingState.inputInfo.surfaceInset);
3442 const float xSurfaceInset = std::clamp(inset, 0.f, inputBounds.getWidth() / 2.f);
3443 const float ySurfaceInset = std::clamp(inset, 0.f, inputBounds.getHeight() / 2.f);
3444
3445 // Apply the insets to the input bounds.
3446 inputBounds.left += xSurfaceInset;
3447 inputBounds.top += ySurfaceInset;
3448 inputBounds.right -= xSurfaceInset;
3449 inputBounds.bottom -= ySurfaceInset;
3450
3451 return {inputBounds, inputBoundsValid};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003452}
3453
Ady Abraham005398b2023-06-05 13:59:41 -07003454bool Layer::isSimpleBufferUpdate(const layer_state_t& s) const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003455 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3456
3457 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3458 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3459 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
Ady Abrahambb1ad762024-03-27 18:31:28 -07003460 layer_state_t::eLayerStackChanged | layer_state_t::eReparent |
3461 (FlagManager::getInstance().latch_unsignaled_with_auto_refresh_changed()
3462 ? 0
3463 : layer_state_t::eAutoRefreshChanged);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003464
Patrick Williamsbb25f802022-08-30 23:02:34 +00003465 if ((s.what & requiredFlags) != requiredFlags) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003466 SFTRACE_FORMAT_INSTANT("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3467 (s.what | requiredFlags) & ~s.what);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003468 return false;
3469 }
3470
3471 if (s.what & deniedFlags) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003472 SFTRACE_FORMAT_INSTANT("%s: false [has denied flags 0x%" PRIx64 "]", __func__,
3473 s.what & deniedFlags);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003474 return false;
3475 }
3476
Patrick Williamsbb25f802022-08-30 23:02:34 +00003477 if (s.what & layer_state_t::ePositionChanged) {
3478 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003479 SFTRACE_FORMAT_INSTANT("%s: false [ePositionChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003480 return false;
3481 }
3482 }
3483
3484 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003485 if (mDrawingState.color.a != s.color.a) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003486 SFTRACE_FORMAT_INSTANT("%s: false [eAlphaChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003487 return false;
3488 }
3489 }
3490
3491 if (s.what & layer_state_t::eColorTransformChanged) {
3492 if (mDrawingState.colorTransform != s.colorTransform) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003493 SFTRACE_FORMAT_INSTANT("%s: false [eColorTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003494 return false;
3495 }
3496 }
3497
3498 if (s.what & layer_state_t::eBackgroundColorChanged) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003499 if (mDrawingState.bgColorLayer || s.bgColor.a != 0) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003500 SFTRACE_FORMAT_INSTANT("%s: false [eBackgroundColorChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003501 return false;
3502 }
3503 }
3504
3505 if (s.what & layer_state_t::eMatrixChanged) {
3506 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3507 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3508 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3509 mRequestedTransform.dsdy() != s.matrix.dsdy) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003510 SFTRACE_FORMAT_INSTANT("%s: false [eMatrixChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003511 return false;
3512 }
3513 }
3514
3515 if (s.what & layer_state_t::eCornerRadiusChanged) {
3516 if (mDrawingState.cornerRadius != s.cornerRadius) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003517 SFTRACE_FORMAT_INSTANT("%s: false [eCornerRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003518 return false;
3519 }
3520 }
3521
3522 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3523 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003524 SFTRACE_FORMAT_INSTANT("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003525 return false;
3526 }
3527 }
3528
Vishnu Nairbbceb462022-10-10 04:52:13 +00003529 if (s.what & layer_state_t::eBufferTransformChanged) {
3530 if (mDrawingState.bufferTransform != s.bufferTransform) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003531 SFTRACE_FORMAT_INSTANT("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003532 return false;
3533 }
3534 }
3535
3536 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3537 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003538 SFTRACE_FORMAT_INSTANT("%s: false [eTransformToDisplayInverseChanged changed]",
3539 __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003540 return false;
3541 }
3542 }
3543
3544 if (s.what & layer_state_t::eCropChanged) {
3545 if (mDrawingState.crop != s.crop) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003546 SFTRACE_FORMAT_INSTANT("%s: false [eCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003547 return false;
3548 }
3549 }
3550
3551 if (s.what & layer_state_t::eDataspaceChanged) {
3552 if (mDrawingState.dataspace != s.dataspace) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003553 SFTRACE_FORMAT_INSTANT("%s: false [eDataspaceChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003554 return false;
3555 }
3556 }
3557
3558 if (s.what & layer_state_t::eHdrMetadataChanged) {
3559 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003560 SFTRACE_FORMAT_INSTANT("%s: false [eHdrMetadataChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003561 return false;
3562 }
3563 }
3564
3565 if (s.what & layer_state_t::eSidebandStreamChanged) {
3566 if (mDrawingState.sidebandStream != s.sidebandStream) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003567 SFTRACE_FORMAT_INSTANT("%s: false [eSidebandStreamChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003568 return false;
3569 }
3570 }
3571
3572 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3573 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003574 SFTRACE_FORMAT_INSTANT("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003575 return false;
3576 }
3577 }
3578
3579 if (s.what & layer_state_t::eShadowRadiusChanged) {
3580 if (mDrawingState.shadowRadius != s.shadowRadius) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003581 SFTRACE_FORMAT_INSTANT("%s: false [eShadowRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003582 return false;
3583 }
3584 }
3585
3586 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3587 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003588 SFTRACE_FORMAT_INSTANT("%s: false [eFixedTransformHintChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003589 return false;
3590 }
3591 }
3592
3593 if (s.what & layer_state_t::eTrustedOverlayChanged) {
Vishnu Nair9e0017e2024-05-22 19:02:44 +00003594 if (mDrawingState.isTrustedOverlay != (s.trustedOverlay == gui::TrustedOverlay::ENABLED)) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003595 SFTRACE_FORMAT_INSTANT("%s: false [eTrustedOverlayChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003596 return false;
3597 }
3598 }
3599
3600 if (s.what & layer_state_t::eStretchChanged) {
3601 StretchEffect temp = s.stretchEffect;
3602 temp.sanitize();
3603 if (mDrawingState.stretchEffect != temp) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003604 SFTRACE_FORMAT_INSTANT("%s: false [eStretchChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003605 return false;
3606 }
3607 }
3608
3609 if (s.what & layer_state_t::eBufferCropChanged) {
3610 if (mDrawingState.bufferCrop != s.bufferCrop) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003611 SFTRACE_FORMAT_INSTANT("%s: false [eBufferCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003612 return false;
3613 }
3614 }
3615
3616 if (s.what & layer_state_t::eDestinationFrameChanged) {
3617 if (mDrawingState.destinationFrame != s.destinationFrame) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003618 SFTRACE_FORMAT_INSTANT("%s: false [eDestinationFrameChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003619 return false;
3620 }
3621 }
3622
3623 if (s.what & layer_state_t::eDimmingEnabledChanged) {
3624 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003625 SFTRACE_FORMAT_INSTANT("%s: false [eDimmingEnabledChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003626 return false;
3627 }
3628 }
3629
John Reck68796592023-01-25 13:47:12 -05003630 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
Sally Qi963049b2023-03-23 14:06:21 -07003631 if (mDrawingState.currentHdrSdrRatio != s.currentHdrSdrRatio ||
3632 mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003633 SFTRACE_FORMAT_INSTANT("%s: false [eExtendedRangeBrightnessChanged changed]", __func__);
John Reck68796592023-01-25 13:47:12 -05003634 return false;
3635 }
3636 }
3637
Alec Mouri1b0d4e12024-02-12 22:27:19 +00003638 if (s.what & layer_state_t::eDesiredHdrHeadroomChanged) {
3639 if (mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003640 SFTRACE_FORMAT_INSTANT("%s: false [eDesiredHdrHeadroomChanged changed]", __func__);
Alec Mouri1b0d4e12024-02-12 22:27:19 +00003641 return false;
3642 }
3643 }
3644
Patrick Williamsbb25f802022-08-30 23:02:34 +00003645 return true;
3646}
3647
Vishnu Naire14c6b32022-08-06 04:20:15 +00003648sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003649 // 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 +00003650 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003651}
3652
Vishnu Naire14c6b32022-08-06 04:20:15 +00003653const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003654 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003655}
3656
Vishnu Naire14c6b32022-08-06 04:20:15 +00003657LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003658 return mSnapshot.get();
3659}
Vishnu Naire14c6b32022-08-06 04:20:15 +00003660
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003661std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
3662 return std::move(mSnapshot);
3663}
3664
3665void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
3666 mSnapshot = std::move(snapshot);
3667}
3668
Patrick Williamsbb25f802022-08-30 23:02:34 +00003669const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003670 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003671}
3672
Patrick Williams7584c6a2022-10-29 02:10:58 +00003673sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Lloyd Pique70ddc672024-04-30 18:20:40 -07003674 auto result = mFlinger->getFactory().createLayerFE(mName, this);
Patrick Williams7584c6a2022-10-29 02:10:58 +00003675 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
3676 return result;
3677}
3678
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003679sp<LayerFE> Layer::getCompositionEngineLayerFE(
3680 const frontend::LayerHierarchy::TraversalPath& path) {
3681 for (auto& [p, layerFE] : mLayerFEs) {
3682 if (p == path) {
3683 return layerFE;
3684 }
3685 }
Lloyd Pique70ddc672024-04-30 18:20:40 -07003686 auto layerFE = mFlinger->getFactory().createLayerFE(mName, this);
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003687 mLayerFEs.emplace_back(path, layerFE);
3688 return layerFE;
3689}
3690
Patrick Williamsbb25f802022-08-30 23:02:34 +00003691void Layer::useSurfaceDamage() {
3692 if (mFlinger->mForceFullDamage) {
3693 surfaceDamageRegion = Region::INVALID_REGION;
3694 } else {
3695 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
3696 }
3697}
3698
3699void Layer::useEmptyDamage() {
3700 surfaceDamageRegion.clear();
3701}
3702
3703bool Layer::isOpaque(const Layer::State& s) const {
3704 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
3705 // layer's opaque flag.
3706 if (!hasSomethingToDraw()) {
3707 return false;
3708 }
3709
3710 // if the layer has the opaque flag, then we're always opaque
3711 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
3712 return true;
3713 }
3714
3715 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00003716 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003717 return true;
3718 }
3719
3720 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
3721 return fillsColor() && getAlpha() == 1.0_hf;
3722}
3723
3724bool Layer::canReceiveInput() const {
3725 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
3726}
3727
3728bool Layer::isVisible() const {
3729 if (!hasSomethingToDraw()) {
3730 return false;
3731 }
3732
3733 if (isHiddenByPolicy()) {
3734 return false;
3735 }
3736
3737 return getAlpha() > 0.0f || hasBlur();
3738}
3739
Leon Scroggins III5b581492023-10-31 14:29:41 -04003740void Layer::onCompositionPresented(const DisplayDevice* display,
3741 const std::shared_ptr<FenceTime>& glDoneFence,
3742 const std::shared_ptr<FenceTime>& presentFence,
Vishnu Nair39a74a92024-07-29 19:01:50 +00003743 const CompositorTiming& compositorTiming,
3744 gui::GameMode gameMode) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003745 // mFrameLatencyNeeded is true when a new frame was latched for the
3746 // composition.
3747 if (!mBufferInfo.mFrameLatencyNeeded) return;
3748
3749 for (const auto& handle : mDrawingState.callbackHandles) {
3750 handle->gpuCompositionDoneFence = glDoneFence;
3751 handle->compositorTiming = compositorTiming;
3752 }
3753
3754 // Update mFrameTracker.
3755 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
3756 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
3757
3758 const int32_t layerId = getSequence();
3759 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
3760
3761 const auto outputLayer = findOutputLayerForDisplay(display);
3762 if (outputLayer && outputLayer->requiresClientComposition()) {
3763 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
3764 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3765 clientCompositionTimestamp,
3766 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
3767 // Update the SurfaceFrames in the drawing state
3768 if (mDrawingState.bufferSurfaceFrameTX) {
3769 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
3770 }
3771 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
3772 surfaceFrame->setGpuComposition();
3773 }
3774 }
3775
3776 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
3777 if (frameReadyFence->isValid()) {
3778 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
3779 } else {
3780 // There was no fence for this frame, so assume that it was ready
3781 // to be presented at the desired present time.
3782 mFrameTracker.setFrameReadyTime(desiredPresentTime);
3783 }
3784
3785 if (display) {
Dominik Laskowskife749dc2024-07-26 10:09:31 -04003786 const auto activeMode = display->refreshRateSelector().getActiveMode();
3787 const Fps refreshRate = activeMode.fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003788 const std::optional<Fps> renderRate =
3789 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
3790
Alec Mouri7c1d8b52023-08-29 20:14:46 +00003791 const auto vote = frameRateToSetFrameRateVotePayload(getFrameRateForLayerTree());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003792
3793 if (presentFence->isValid()) {
3794 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
3795 refreshRate, renderRate, vote, gameMode);
3796 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
3797 presentFence,
3798 FrameTracer::FrameEvent::PRESENT_FENCE);
3799 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
3800 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
3801 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04003802 // The HWC doesn't support present fences, so use the present timestamp instead.
3803 const nsecs_t presentTimestamp =
3804 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
3805
3806 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
Dominik Laskowskife749dc2024-07-26 10:09:31 -04003807 const nsecs_t vsyncPeriod =
3808 mFlinger->getHwComposer()
3809 .getDisplayVsyncPeriod(*displayId)
3810 .value_opt()
3811 .value_or(activeMode.modePtr->getVsyncRate().getPeriodNsecs());
3812
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04003813 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
3814
Patrick Williamsbb25f802022-08-30 23:02:34 +00003815 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
3816 refreshRate, renderRate, vote, gameMode);
3817 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
3818 mCurrentFrameNumber, actualPresentTime,
3819 FrameTracer::FrameEvent::PRESENT_FENCE);
3820 mFrameTracker.setActualPresentTime(actualPresentTime);
3821 }
3822 }
3823
3824 mFrameTracker.advanceFrame();
3825 mBufferInfo.mFrameLatencyNeeded = false;
3826}
3827
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003828bool Layer::willReleaseBufferOnLatch() const {
3829 return !mDrawingState.buffer && mBufferInfo.mBuffer;
3830}
3831
Patrick Williamsbb25f802022-08-30 23:02:34 +00003832bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003833 const bool bgColorOnly = mDrawingState.bgColorLayer != nullptr;
3834 return latchBufferImpl(recomputeVisibleRegions, latchTime, bgColorOnly);
3835}
3836
3837bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003838 SFTRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
3839 getDrawingState().frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003840
3841 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
3842
3843 if (refreshRequired) {
3844 return refreshRequired;
3845 }
3846
3847 // If the head buffer's acquire fence hasn't signaled yet, return and
3848 // try again later
3849 if (!fenceHasSignaled()) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00003850 SFTRACE_NAME("!fenceHasSignaled()");
Patrick Williamsbb25f802022-08-30 23:02:34 +00003851 mFlinger->onLayerUpdate();
3852 return false;
3853 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00003854 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003855
3856 // Capture the old state of the layer for comparisons later
3857 BufferInfo oldBufferInfo = mBufferInfo;
3858 const bool oldOpacity = isOpaque(mDrawingState);
3859 mPreviousFrameNumber = mCurrentFrameNumber;
3860 mCurrentFrameNumber = mDrawingState.frameNumber;
3861 gatherBufferInfo();
3862
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003863 if (mBufferInfo.mBuffer) {
3864 // We latched a buffer that will be presented soon. Clear the previously presented layer
3865 // stack list.
3866 mPreviouslyPresentedLayerStacks.clear();
3867 }
3868
3869 if (mDrawingState.buffer == nullptr) {
3870 const bool bufferReleased = oldBufferInfo.mBuffer != nullptr;
3871 recomputeVisibleRegions = bufferReleased;
3872 return bufferReleased;
3873 }
3874
Patrick Williamsbb25f802022-08-30 23:02:34 +00003875 if (oldBufferInfo.mBuffer == nullptr) {
3876 // the first time we receive a buffer, we need to trigger a
3877 // geometry invalidation.
3878 recomputeVisibleRegions = true;
3879 }
3880
3881 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
3882 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
3883 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
3884 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
3885 recomputeVisibleRegions = true;
3886 }
3887
3888 if (oldBufferInfo.mBuffer != nullptr) {
3889 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3890 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3891 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
3892 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
3893 recomputeVisibleRegions = true;
3894 }
3895 }
3896
3897 if (oldOpacity != isOpaque(mDrawingState)) {
3898 recomputeVisibleRegions = true;
3899 }
3900
3901 return true;
3902}
3903
3904bool Layer::hasReadyFrame() const {
3905 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
3906}
3907
3908bool Layer::isProtected() const {
3909 return (mBufferInfo.mBuffer != nullptr) &&
3910 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
3911}
3912
Patrick Williamsbb25f802022-08-30 23:02:34 +00003913void Layer::latchAndReleaseBuffer() {
3914 if (hasReadyFrame()) {
3915 bool ignored = false;
3916 latchBuffer(ignored, systemTime());
3917 }
3918 releasePendingBuffer(systemTime());
3919}
3920
3921PixelFormat Layer::getPixelFormat() const {
3922 return mBufferInfo.mPixelFormat;
3923}
3924
3925bool Layer::getTransformToDisplayInverse() const {
3926 return mBufferInfo.mTransformToDisplayInverse;
3927}
3928
3929Rect Layer::getBufferCrop() const {
3930 // this is the crop rectangle that applies to the buffer
3931 // itself (as opposed to the window)
3932 if (!mBufferInfo.mCrop.isEmpty()) {
3933 // if the buffer crop is defined, we use that
3934 return mBufferInfo.mCrop;
3935 } else if (mBufferInfo.mBuffer != nullptr) {
3936 // otherwise we use the whole buffer
3937 return mBufferInfo.mBuffer->getBounds();
3938 } else {
3939 // if we don't have a buffer yet, we use an empty/invalid crop
3940 return Rect();
3941 }
3942}
3943
3944uint32_t Layer::getBufferTransform() const {
3945 return mBufferInfo.mTransform;
3946}
3947
3948ui::Dataspace Layer::getDataSpace() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003949 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
3950}
3951
Alec Mouri89f5d4e2023-10-20 17:12:49 +00003952bool Layer::isFrontBuffered() const {
3953 if (mBufferInfo.mBuffer == nullptr) {
3954 return false;
3955 }
3956
3957 return mBufferInfo.mBuffer->getUsage() & AHARDWAREBUFFER_USAGE_FRONT_BUFFER;
3958}
3959
Patrick Williamsbb25f802022-08-30 23:02:34 +00003960ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
3961 ui::Dataspace updatedDataspace = dataspace;
3962 // translate legacy dataspaces to modern dataspaces
3963 switch (dataspace) {
Alec Mouri74c7ae12023-03-26 02:57:47 +00003964 // Treat unknown dataspaces as V0_sRGB
3965 case ui::Dataspace::UNKNOWN:
Patrick Williamsbb25f802022-08-30 23:02:34 +00003966 case ui::Dataspace::SRGB:
3967 updatedDataspace = ui::Dataspace::V0_SRGB;
3968 break;
3969 case ui::Dataspace::SRGB_LINEAR:
3970 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
3971 break;
3972 case ui::Dataspace::JFIF:
3973 updatedDataspace = ui::Dataspace::V0_JFIF;
3974 break;
3975 case ui::Dataspace::BT601_625:
3976 updatedDataspace = ui::Dataspace::V0_BT601_625;
3977 break;
3978 case ui::Dataspace::BT601_525:
3979 updatedDataspace = ui::Dataspace::V0_BT601_525;
3980 break;
3981 case ui::Dataspace::BT709:
3982 updatedDataspace = ui::Dataspace::V0_BT709;
3983 break;
3984 default:
3985 break;
3986 }
3987
3988 return updatedDataspace;
3989}
3990
3991sp<GraphicBuffer> Layer::getBuffer() const {
3992 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
3993}
3994
Patrick Williamsbb25f802022-08-30 23:02:34 +00003995const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
3996 return mBufferInfo.mBuffer;
3997}
3998
3999bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00004000 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004001 return false;
4002 }
4003
4004 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00004005 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004006 mDrawingState.modified = true;
4007 setTransactionFlags(eTransactionNeeded);
4008 return true;
4009}
4010
4011bool Layer::fillsColor() const {
4012 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4013 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4014}
4015
4016bool Layer::hasBlur() const {
4017 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4018}
4019
Vishnu Nairba354102022-08-01 00:14:18 +00004020void Layer::updateSnapshot(bool updateGeometry) {
4021 if (!getCompositionEngineLayerFE()) {
4022 return;
4023 }
4024
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004025 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004026 if (updateGeometry) {
4027 prepareBasicGeometryCompositionState();
4028 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004029 snapshot->roundedCorner = getRoundedCornerState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004030 snapshot->transformedBounds = mScreenBounds;
4031 if (mEffectiveShadowRadius > 0.f) {
4032 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4033
4034 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4035 // it if transparent regions are present. This may not be necessary since shadows are
4036 // typically cast by layers without transparent regions.
4037 snapshot->shadowSettings.boundaries = mBounds;
4038
4039 const float casterAlpha = snapshot->alpha;
4040 const bool casterIsOpaque =
4041 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4042
4043 // If the casting layer is translucent, we need to fill in the shadow underneath the
4044 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4045 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4046 snapshot->shadowSettings.ambientColor *= casterAlpha;
4047 snapshot->shadowSettings.spotColor *= casterAlpha;
4048 }
4049 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004050 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004051 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004052 snapshot->layerOpaqueFlagSet =
4053 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004054 sp<Layer> p = mDrawingParent.promote();
4055 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004056 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004057 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004058 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004059 }
4060 snapshot->bufferSize = getBufferSize(mDrawingState);
4061 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004062 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00004063 preparePerFrameCompositionState();
4064}
4065
Vishnu Naire14c6b32022-08-06 04:20:15 +00004066void Layer::updateChildrenSnapshots(bool updateGeometry) {
4067 for (const sp<Layer>& child : mDrawingChildren) {
4068 child->updateSnapshot(updateGeometry);
4069 child->updateChildrenSnapshots(updateGeometry);
4070 }
4071}
4072
Chavi Weingarten328a8312023-01-26 21:17:52 +00004073bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00004074 TrustedPresentationListener const& listener) {
4075 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4076 mTrustedPresentationListener = listener;
4077 mTrustedPresentationThresholds = thresholds;
4078 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4079 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4080 mFlinger->mNumTrustedPresentationListeners++;
4081 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4082 mFlinger->mNumTrustedPresentationListeners--;
4083 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00004084
4085 // Reset trusted presentation states to ensure we start the time again.
4086 mEnteredTrustedPresentationStateTime = -1;
4087 mLastReportedTrustedPresentationState = false;
4088 mLastComputedTrustedPresentationState = false;
4089
4090 // If there's a new trusted presentation listener, the code needs to go through the composite
4091 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
4092 // we're already in the requested state.
4093 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00004094}
4095
Vishnu Naira156f482023-02-22 00:23:38 +00004096void Layer::updateLastLatchTime(nsecs_t latchTime) {
4097 mLastLatchTime = latchTime;
4098}
4099
Arthur Hung69f95222023-10-04 07:39:02 +00004100void Layer::setIsSmallDirty(const Region& damageRegion,
4101 const ui::Transform& layerToDisplayTransform) {
4102 mSmallDirty = false;
Jerry Chang36678002023-11-29 16:56:17 +00004103 if (!mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +00004104 return;
4105 }
4106
4107 if (mWindowType != WindowInfo::Type::APPLICATION &&
4108 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
4109 return;
4110 }
Arthur Hung69f95222023-10-04 07:39:02 +00004111
4112 Rect bounds = damageRegion.getBounds();
Arthur Hungc70bee22023-06-02 01:35:52 +00004113 if (!bounds.isValid()) {
4114 return;
4115 }
4116
Arthur Hung69f95222023-10-04 07:39:02 +00004117 // Transform to screen space.
4118 bounds = layerToDisplayTransform.transform(bounds);
4119
Arthur Hungc70bee22023-06-02 01:35:52 +00004120 // If the damage region is a small dirty, this could give the hint for the layer history that
4121 // it could suppress the heuristic rate when calculating.
Tony Huangf3621102023-09-04 17:14:22 +08004122 mSmallDirty = mFlinger->mScheduler->isSmallDirtyArea(mOwnerAppId,
Tony Huang9ac5e6e2023-08-24 09:01:44 +00004123 bounds.getWidth() * bounds.getHeight());
Arthur Hungc70bee22023-06-02 01:35:52 +00004124}
4125
Arthur Hung69f95222023-10-04 07:39:02 +00004126void Layer::setIsSmallDirty(frontend::LayerSnapshot* snapshot) {
4127 setIsSmallDirty(snapshot->surfaceDamage, snapshot->localTransform);
4128 snapshot->isSmallDirty = mSmallDirty;
4129}
4130
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004131} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004132
4133#if defined(__gl_h_)
4134#error "don't include gl/gl.h in this file"
4135#endif
4136
4137#if defined(__gl2_h_)
4138#error "don't include gl2/gl2.h in this file"
4139#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004140
4141// TODO(b/129481165): remove the #pragma below and fix conversion issues
4142#pragma clang diagnostic pop // ignored "-Wconversion"