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