blob: edd9f9ce4f4865749588f9cd11ae33fb4df745b7 [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>
Patrick Williamsbb25f802022-08-30 23:02:34 +000030#include <compositionengine/CompositionEngine.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080031#include <compositionengine/Display.h>
Lloyd Piquea83776c2019-01-29 18:42:32 -080032#include <compositionengine/LayerFECompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080033#include <compositionengine/OutputLayer.h>
34#include <compositionengine/impl/OutputLayerCompositionState.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070035#include <cutils/compiler.h>
Mathias Agopian076b1cc2009-04-10 14:24:30 -070036#include <cutils/native_handle.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070037#include <cutils/properties.h>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070038#include <ftl/enum.h>
Dominik Laskowski298b08e2022-02-15 13:45:02 -080039#include <ftl/fake_guard.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080040#include <gui/BufferItem.h>
41#include <gui/LayerDebugInfo.h>
42#include <gui/Surface.h>
Patrick Williamsbb25f802022-08-30 23:02:34 +000043#include <gui/TraceUtils.h>
Alec Mourie60041e2019-06-14 18:59:51 -070044#include <math.h>
chaviw250bcbb2020-08-05 11:17:54 -070045#include <private/android_filesystem_config.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080046#include <renderengine/RenderEngine.h>
Alec Mourie60041e2019-06-14 18:59:51 -070047#include <stdint.h>
48#include <stdlib.h>
49#include <sys/types.h>
Alec Mouridda07d92022-04-25 22:39:25 +000050#include <system/graphics-base-v1.0.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080051#include <ui/DebugUtils.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000052#include <ui/FloatRect.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080053#include <ui/GraphicBuffer.h>
Sally Qif6918d42023-08-07 15:28:30 -070054#include <ui/HdrRenderTypeUtils.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080055#include <ui/PixelFormat.h>
Vishnu Nairfed7c122023-03-18 01:54:43 +000056#include <ui/Rect.h>
57#include <ui/Transform.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080058#include <utils/Errors.h>
59#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080060#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080062#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Alec Mourie60041e2019-06-14 18:59:51 -070064#include <algorithm>
65#include <mutex>
Vishnu Nair71fcf912022-10-18 09:14:20 -070066#include <optional>
Alec Mourie60041e2019-06-14 18:59:51 -070067#include <sstream>
68
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070069#include "DisplayDevice.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080070#include "DisplayHardware/HWComposer.h"
Ady Abraham22c7b5c2020-09-22 19:33:40 -070071#include "FrameTimeline.h"
Mikael Pessa90092f42019-08-26 17:22:04 -070072#include "FrameTracer/FrameTracer.h"
Vishnu Naircb8be502022-10-12 19:03:23 +000073#include "FrontEnd/LayerCreationArgs.h"
Vishnu Nair07e2a482022-10-18 19:18:16 +000074#include "FrontEnd/LayerHandle.h"
Melody Hsue4ef87f2024-03-26 23:54:45 +000075#include "Layer.h"
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080076#include "LayerProtoHelper.h"
Josh Gao194ff392022-09-08 16:19:29 -070077#include "MutexUtils.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include "SurfaceFlinger.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080079#include "TimeStats/TimeStats.h"
Melody Hsue4ef87f2024-03-26 23:54:45 +000080#include "TransactionCallbackInvoker.h"
Robert Carr3e2a2992021-06-11 13:42:55 -070081#include "TunnelModeEnabledReporter.h"
Alec Mouri9892aac2023-12-11 21:16:59 +000082#include "Utils/FenceUtils.h"
Mathias Agopian1b031492012-06-20 17:51:20 -070083
David Sodman41fdfc92017-11-06 16:09:56 -080084#define DEBUG_RESIZE 0
Patrick Williamsbb25f802022-08-30 23:02:34 +000085#define EARLY_RELEASE_ENABLED false
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080086
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080087namespace android {
Alec Mouri9892aac2023-12-11 21:16:59 +000088using namespace std::chrono_literals;
Marin Shalamanov1876e2e2020-12-04 13:23:59 +010089namespace {
90constexpr int kDumpTableRowLength = 159;
Patrick Williamsbb25f802022-08-30 23:02:34 +000091
Prabir Pradhanda0f62c2022-07-22 19:53:04 +000092const ui::Transform kIdentityTransform;
Patrick Williamsbb25f802022-08-30 23:02:34 +000093
Patrick Williamsbb25f802022-08-30 23:02:34 +000094bool assignTransform(ui::Transform* dst, ui::Transform& from) {
95 if (*dst == from) {
96 return false;
97 }
98 *dst = from;
99 return true;
100}
101
102TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
103 using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
104 using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
105 const auto frameRateCompatibility = [frameRate] {
Rachel Leece6e0042023-06-27 11:22:54 -0700106 switch (frameRate.vote.type) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000107 case Layer::FrameRateCompatibility::Default:
108 return FrameRateCompatibility::Default;
109 case Layer::FrameRateCompatibility::ExactOrMultiple:
110 return FrameRateCompatibility::ExactOrMultiple;
111 default:
112 return FrameRateCompatibility::Undefined;
113 }
114 }();
115
116 const auto seamlessness = [frameRate] {
Rachel Leece6e0042023-06-27 11:22:54 -0700117 switch (frameRate.vote.seamlessness) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000118 case scheduler::Seamlessness::OnlySeamless:
119 return Seamlessness::ShouldBeSeamless;
120 case scheduler::Seamlessness::SeamedAndSeamless:
121 return Seamlessness::NotRequired;
122 default:
123 return Seamlessness::Undefined;
124 }
125 }();
126
Rachel Leece6e0042023-06-27 11:22:54 -0700127 return TimeStats::SetFrameRateVote{.frameRate = frameRate.vote.rate.getValue(),
Patrick Williamsbb25f802022-08-30 23:02:34 +0000128 .frameRateCompatibility = frameRateCompatibility,
129 .seamlessness = seamlessness};
130}
131
Marin Shalamanov1876e2e2020-12-04 13:23:59 +0100132} // namespace
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800133
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700134using namespace ftl::flag_operators;
135
Yiwei Zhang5434a782018-12-05 18:06:32 -0800136using base::StringAppendF;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000137using frontend::LayerSnapshot;
138using frontend::RoundedCornerState;
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800139using gui::GameMode;
140using gui::LayerMetadata;
chaviw3277faf2021-05-19 16:45:23 -0500141using gui::WindowInfo;
Vishnu Nair494a2e42023-11-10 17:21:19 -0800142using ui::Size;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800143
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700144using PresentState = frametimeline::SurfaceFrame::PresentState;
145
Kean Mariotti4ba343c2023-04-19 13:31:02 +0000146Layer::Layer(const surfaceflinger::LayerCreationArgs& args)
Vishnu Naircb8be502022-10-12 19:03:23 +0000147 : sequence(args.sequence),
Ady Abrahamd11bade2022-08-01 16:18:03 -0700148 mFlinger(sp<SurfaceFlinger>::fromExisting(args.flinger)),
Arthur Hung23e07502021-10-15 11:58:19 +0000149 mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
Ady Abraham8f1ee7f2019-04-05 10:32:50 -0700150 mClientRef(args.client),
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800151 mWindowType(static_cast<WindowInfo::Type>(
152 args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))),
Tianhao Yao67dd7122022-02-22 17:48:33 +0000153 mLayerCreationFlags(args.flags),
Vishnu Nair3af0ec02023-02-10 04:13:48 +0000154 mLegacyLayerFE(args.flinger->getFactory().createLayerFE(mName)) {
Patrick Williamsbb25f802022-08-30 23:02:34 +0000155 ALOGV("Creating Layer %s", getDebugName());
156
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700157 uint32_t layerFlags = 0;
Lloyd Pique42ab75e2018-09-12 20:46:03 -0700158 if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
159 if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
160 if (args.flags & ISurfaceComposerClient::eSecure) layerFlags |= layer_state_t::eLayerSecure;
chaviwc5676c62020-09-18 15:01:04 -0700161 if (args.flags & ISurfaceComposerClient::eSkipScreenshot)
162 layerFlags |= layer_state_t::eLayerSkipScreenshot;
Robert Carr6a160312021-05-17 12:08:20 -0700163 mDrawingState.flags = layerFlags;
Robert Carr6a160312021-05-17 12:08:20 -0700164 mDrawingState.crop.makeInvalid();
Robert Carr6a160312021-05-17 12:08:20 -0700165 mDrawingState.z = 0;
166 mDrawingState.color.a = 1.0f;
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700167 mDrawingState.layerStack = ui::DEFAULT_LAYER_STACK;
Robert Carr6a160312021-05-17 12:08:20 -0700168 mDrawingState.sequence = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700169 mDrawingState.transform.set(0, 0);
170 mDrawingState.frameNumber = 0;
Alec Mouri21d94322023-10-17 19:51:39 +0000171 mDrawingState.previousFrameNumber = 0;
Vishnu Nair63221212023-04-06 15:17:37 -0700172 mDrawingState.barrierFrameNumber = 0;
173 mDrawingState.producerId = 0;
174 mDrawingState.barrierProducerId = 0;
Robert Carr6a160312021-05-17 12:08:20 -0700175 mDrawingState.bufferTransform = 0;
176 mDrawingState.transformToDisplayInverse = false;
Robert Carr6a160312021-05-17 12:08:20 -0700177 mDrawingState.acquireFence = sp<Fence>::make(-1);
178 mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
Alec Mouri74c7ae12023-03-26 02:57:47 +0000179 mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
Robert Carr6a160312021-05-17 12:08:20 -0700180 mDrawingState.hdrMetadata.validTypes = 0;
181 mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
182 mDrawingState.cornerRadius = 0.0f;
183 mDrawingState.backgroundBlurRadius = 0;
184 mDrawingState.api = -1;
185 mDrawingState.hasColorTransform = false;
186 mDrawingState.colorSpaceAgnostic = false;
187 mDrawingState.frameRateSelectionPriority = PRIORITY_UNSET;
188 mDrawingState.metadata = args.metadata;
189 mDrawingState.shadowRadius = 0.f;
190 mDrawingState.fixedTransformHint = ui::Transform::ROT_INVALID;
191 mDrawingState.frameTimelineInfo = {};
192 mDrawingState.postTime = -1;
193 mDrawingState.destinationFrame.makeInvalid();
Robin Leeedb375d2021-09-10 12:03:42 +0000194 mDrawingState.isTrustedOverlay = false;
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -0700195 mDrawingState.dropInputMode = gui::DropInputMode::NONE;
Sally Qi81d95e62022-03-21 19:41:33 -0700196 mDrawingState.dimmingEnabled = true;
Andy Labrada096227e2022-06-15 16:58:11 +0000197 mDrawingState.defaultFrameRateCompatibility = FrameRateCompatibility::Default;
Rachel Lee70f7b692023-11-22 11:24:02 -0800198 mDrawingState.frameRateSelectionStrategy = FrameRateSelectionStrategy::Propagate;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700199
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700200 if (args.flags & ISurfaceComposerClient::eNoColorFill) {
201 // Set an invalid color so there is no color fill.
Robert Carr6a160312021-05-17 12:08:20 -0700202 mDrawingState.color.r = -1.0_hf;
203 mDrawingState.color.g = -1.0_hf;
204 mDrawingState.color.b = -1.0_hf;
Vishnu Nairc43a23c2020-05-29 14:32:27 -0700205 }
Dominik Laskowski4376bd82022-07-07 11:50:20 -0700206
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500207 mFrameTracker.setDisplayRefreshPeriod(
208 args.flinger->mScheduler->getPacesetterVsyncPeriod().ns());
Robert Carr2e102c92018-10-23 12:11:15 -0700209
Vishnu Naircb8be502022-10-12 19:03:23 +0000210 mOwnerUid = args.ownerUid;
211 mOwnerPid = args.ownerPid;
Tony Huangf3621102023-09-04 17:14:22 +0800212 mOwnerAppId = mOwnerUid % PER_USER_RANGE;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000213
214 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
215 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
216 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000217
218 mSnapshot->sequence = sequence;
219 mSnapshot->name = getDebugName();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000220 mSnapshot->premultipliedAlpha = mPremultipliedAlpha;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000221 mSnapshot->parentTransform = {};
Dominik Laskowski75848362019-11-11 17:57:20 -0800222}
223
224void Layer::onFirstRef() {
225 mFlinger->onLayerFirstRef(this);
Dan Stoza436ccf32018-06-21 12:10:12 -0700226}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700227
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700228Layer::~Layer() {
Patrick Williams70093fd2022-12-12 16:51:52 +0000229 LOG_ALWAYS_FATAL_IF(std::this_thread::get_id() != mFlinger->mMainThreadId,
230 "Layer destructor called off the main thread.");
231
Patrick Williamsbb25f802022-08-30 23:02:34 +0000232 // The original layer and the clone layer share the same texture and buffer. Therefore, only
233 // one of the layers, in this case the original layer, needs to handle the deletion. The
234 // original layer and the clone should be removed at the same time so there shouldn't be any
235 // issue with the clone layer trying to use the texture.
236 if (mBufferInfo.mBuffer != nullptr) {
237 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
238 mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
liulijuneb489f62022-10-17 22:02:14 +0800239 mBufferInfo.mFence);
Patrick Williamsbb25f802022-08-30 23:02:34 +0000240 }
Patrick Williamsbb25f802022-08-30 23:02:34 +0000241 const int32_t layerId = getSequence();
242 mFlinger->mTimeStats->onDestroy(layerId);
243 mFlinger->mFrameTracer->onDestroy(layerId);
244
Jorim Jaggi10c985e2018-10-23 11:17:45 +0000245 mFrameTracker.logAndResetStats(mName);
chaviw74d90ad2019-04-26 14:45:26 -0700246 mFlinger->onLayerDestroyed(this);
Robert Carr3e2a2992021-06-11 13:42:55 -0700247
248 if (mDrawingState.sidebandStream != nullptr) {
249 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
250 }
Robert Carr6a0382d2021-07-01 15:57:17 -0700251 if (mHadClonedChild) {
Vishnu Nair3be61902023-04-26 19:47:29 -0700252 auto& roots = mFlinger->mLayerMirrorRoots;
253 roots.erase(std::remove(roots.begin(), roots.end(), this), roots.end());
Robert Carr6a0382d2021-07-01 15:57:17 -0700254 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000255 if (hasTrustedPresentationListener()) {
256 mFlinger->mNumTrustedPresentationListeners--;
Vishnu Nair781d7252023-01-30 18:16:01 +0000257 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Chavi Weingarten076acac2023-01-19 17:20:43 +0000258 }
Mathias Agopian96f08192010-06-02 23:28:45 -0700259}
260
Mathias Agopian13127d82013-03-05 17:47:11 -0800261// ---------------------------------------------------------------------------
262// callbacks
263// ---------------------------------------------------------------------------
264
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700265void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
Robert Carr6a160312021-05-17 12:08:20 -0700266 if (mDrawingState.zOrderRelativeOf == nullptr) {
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700267 return;
268 }
Robert Carr2e102c92018-10-23 12:11:15 -0700269
Robert Carr6a160312021-05-17 12:08:20 -0700270 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700271 if (strongRelative == nullptr) {
272 setZOrderRelativeOf(nullptr);
273 return;
274 }
275
276 if (!std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700277 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700278 mFlinger->setTransactionFlags(eTraversalNeeded);
chaviw606e5cf2019-03-01 10:12:10 -0800279 setZOrderRelativeOf(nullptr);
Robert Carr5edb1ad2017-04-25 10:54:24 -0700280 }
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700281}
282
283void Layer::removeFromCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700284 if (!mRemovedFromDrawingState) {
285 mRemovedFromDrawingState = true;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700286 mFlinger->mScheduler->deregisterLayer(this);
287 }
Vishnu Nair781d7252023-01-30 18:16:01 +0000288 updateTrustedPresentationState(nullptr, nullptr, -1 /* time_in_ms */, true /* leaveState*/);
Rob Carr4bba3702018-10-08 21:53:30 +0000289
Ady Abrahamd11bade2022-08-01 16:18:03 -0700290 mFlinger->markLayerPendingRemovalLocked(sp<Layer>::fromExisting(this));
Chia-I Wuc6657022017-08-15 11:18:17 -0700291}
Chia-I Wu38512252017-05-17 14:36:16 -0700292
chaviw68d4dab2020-06-08 15:07:32 -0700293sp<Layer> Layer::getRootLayer() {
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000294 sp<Layer> parent = getParent();
chaviw68d4dab2020-06-08 15:07:32 -0700295 if (parent == nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700296 return sp<Layer>::fromExisting(this);
chaviw68d4dab2020-06-08 15:07:32 -0700297 }
298 return parent->getRootLayer();
299}
300
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700301void Layer::onRemovedFromCurrentState() {
chaviw68d4dab2020-06-08 15:07:32 -0700302 // Use the root layer since we want to maintain the hierarchy for the entire subtree.
303 auto layersInTree = getRootLayer()->getLayersInTree(LayerVector::StateSet::Current);
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700304 std::sort(layersInTree.begin(), layersInTree.end());
chaviw68d4dab2020-06-08 15:07:32 -0700305
Josh Gao194ff392022-09-08 16:19:29 -0700306 REQUIRE_MUTEX(mFlinger->mStateLock);
307 traverse(LayerVector::StateSet::Current,
308 [&](Layer* layer) REQUIRES(layer->mFlinger->mStateLock) {
309 layer->removeFromCurrentState();
310 layer->removeRelativeZ(layersInTree);
311 });
Vishnu Nairda9c85a2019-06-03 17:26:48 -0700312}
313
chaviw61626f22018-11-15 16:26:27 -0800314void Layer::addToCurrentState() {
Robert Carr6a160312021-05-17 12:08:20 -0700315 if (mRemovedFromDrawingState) {
316 mRemovedFromDrawingState = false;
Ady Abrahambe09aad2021-05-03 18:59:38 -0700317 mFlinger->mScheduler->registerLayer(this);
Robert Carr867be372021-06-29 17:36:02 -0700318 mFlinger->removeFromOffscreenLayers(this);
Ady Abrahambe09aad2021-05-03 18:59:38 -0700319 }
chaviw61626f22018-11-15 16:26:27 -0800320
321 for (const auto& child : mCurrentChildren) {
322 child->addToCurrentState();
323 }
324}
325
Mathias Agopian13127d82013-03-05 17:47:11 -0800326// ---------------------------------------------------------------------------
327// set-up
328// ---------------------------------------------------------------------------
329
chaviw13fdc492017-06-27 12:40:18 -0700330bool Layer::getPremultipledAlpha() const {
331 return mPremultipliedAlpha;
332}
333
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700334sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800335 Mutex::Autolock _l(mLock);
Robert Carrc0df3122019-04-11 13:18:21 -0700336 if (mGetHandleCalled) {
337 ALOGE("Get handle called twice" );
338 return nullptr;
339 }
340 mGetHandleCalled = true;
Vishnu Nair787aa782023-03-17 13:46:46 -0700341 mHandleAlive = true;
Vishnu Nair07e2a482022-10-18 19:18:16 +0000342 return sp<LayerHandle>::make(mFlinger, sp<Layer>::fromExisting(this));
Mathias Agopian13127d82013-03-05 17:47:11 -0800343}
344
345// ---------------------------------------------------------------------------
346// h/w composer set-up
347// ---------------------------------------------------------------------------
348
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700349static Rect reduce(const Rect& win, const Region& exclude) {
350 if (CC_LIKELY(exclude.isEmpty())) {
351 return win;
352 }
353 if (exclude.isRect()) {
354 return win.reduce(exclude.getBounds());
355 }
356 return Region(win).subtract(exclude).getBounds();
357}
358
Dan Stoza80d61162017-12-20 15:57:52 -0800359static FloatRect reduce(const FloatRect& win, const Region& exclude) {
360 if (CC_LIKELY(exclude.isEmpty())) {
361 return win;
362 }
363 // Convert through Rect (by rounding) for lack of FloatRegion
364 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
365}
366
Vishnu Nair4351ad52019-02-11 14:13:02 -0800367Rect Layer::getScreenBounds(bool reduceTransparentRegion) const {
Vishnu Nairf0c28512019-02-08 12:40:28 -0800368 if (!reduceTransparentRegion) {
369 return Rect{mScreenBounds};
370 }
371
372 FloatRect bounds = getBounds();
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800373 ui::Transform t = getTransform();
Vishnu Nair60356342018-11-13 13:00:45 -0800374 // Transform to screen space.
375 bounds = t.transform(bounds);
376 return Rect{bounds};
Robert Carr1f0a16a2016-10-24 16:27:39 -0700377}
378
Vishnu Nair4351ad52019-02-11 14:13:02 -0800379FloatRect Layer::getBounds() const {
Alec Mourib416efd2018-09-06 21:01:59 +0000380 const State& s(getDrawingState());
Vishnu Nair4351ad52019-02-11 14:13:02 -0800381 return getBounds(getActiveTransparentRegion(s));
Michael Lentine6c925ed2014-09-26 17:55:01 -0700382}
383
Vishnu Nairf0c28512019-02-08 12:40:28 -0800384FloatRect Layer::getBounds(const Region& activeTransparentRegion) const {
385 // Subtract the transparent region and snap to the bounds.
386 return reduce(mBounds, activeTransparentRegion);
387}
388
Chavi Weingarten076acac2023-01-19 17:20:43 +0000389// No early returns.
Vishnu Nair781d7252023-01-30 18:16:01 +0000390void Layer::updateTrustedPresentationState(const DisplayDevice* display,
391 const frontend::LayerSnapshot* snapshot,
392 int64_t time_in_ms, bool leaveState) {
Chavi Weingarten076acac2023-01-19 17:20:43 +0000393 if (!hasTrustedPresentationListener()) {
394 return;
395 }
396 const bool lastState = mLastComputedTrustedPresentationState;
397 mLastComputedTrustedPresentationState = false;
398
399 if (!leaveState) {
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000400 const auto outputLayer = findOutputLayerForDisplay(display, snapshot->path);
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000401 if (outputLayer != nullptr) {
402 if (outputLayer->getState().coveredRegionExcludingDisplayOverlays) {
403 Region coveredRegion =
404 *outputLayer->getState().coveredRegionExcludingDisplayOverlays;
405 mLastComputedTrustedPresentationState =
406 computeTrustedPresentationState(snapshot->geomLayerBounds,
407 snapshot->sourceBounds(), coveredRegion,
408 snapshot->transformedBounds,
409 snapshot->alpha,
410 snapshot->geomLayerTransform,
411 mTrustedPresentationThresholds);
412 } else {
413 ALOGE("CoveredRegionExcludingDisplayOverlays was not set for %s. Don't compute "
414 "TrustedPresentationState",
415 getDebugName());
416 }
Chavi Weingarten076acac2023-01-19 17:20:43 +0000417 }
418 }
419 const bool newState = mLastComputedTrustedPresentationState;
420 if (lastState && !newState) {
421 // We were in the trusted presentation state, but now we left it,
422 // emit the callback if needed
423 if (mLastReportedTrustedPresentationState) {
424 mLastReportedTrustedPresentationState = false;
425 mTrustedPresentationListener.invoke(false);
426 }
427 // Reset the timer
428 mEnteredTrustedPresentationStateTime = -1;
429 } else if (!lastState && newState) {
430 // We were not in the trusted presentation state, but we entered it, begin the timer
431 // and make sure this gets called at least once more!
432 mEnteredTrustedPresentationStateTime = time_in_ms;
433 mFlinger->forceFutureUpdate(mTrustedPresentationThresholds.stabilityRequirementMs * 1.5);
434 }
435
436 // Has the timer elapsed, but we are still in the state? Emit a callback if needed
437 if (!mLastReportedTrustedPresentationState && newState &&
438 (time_in_ms - mEnteredTrustedPresentationStateTime >
439 mTrustedPresentationThresholds.stabilityRequirementMs)) {
440 mLastReportedTrustedPresentationState = true;
441 mTrustedPresentationListener.invoke(true);
442 }
443}
444
445/**
446 * See SurfaceComposerClient.h: setTrustedPresentationCallback for discussion
447 * of how the parameters and thresholds are interpreted. The general spirit is
448 * to produce an upper bound on the amount of the buffer which was presented.
449 */
450bool Layer::computeTrustedPresentationState(const FloatRect& bounds, const FloatRect& sourceBounds,
451 const Region& coveredRegion,
452 const FloatRect& screenBounds, float alpha,
453 const ui::Transform& effectiveTransform,
454 const TrustedPresentationThresholds& thresholds) {
455 if (alpha < thresholds.minAlpha) {
456 return false;
457 }
458 if (sourceBounds.getWidth() == 0 || sourceBounds.getHeight() == 0) {
459 return false;
460 }
461 if (screenBounds.getWidth() == 0 || screenBounds.getHeight() == 0) {
462 return false;
463 }
464
465 const float sx = effectiveTransform.dsdx();
466 const float sy = effectiveTransform.dsdy();
467 float fractionRendered = std::min(sx * sy, 1.0f);
468
469 float boundsOverSourceW = bounds.getWidth() / (float)sourceBounds.getWidth();
470 float boundsOverSourceH = bounds.getHeight() / (float)sourceBounds.getHeight();
471 fractionRendered *= boundsOverSourceW * boundsOverSourceH;
472
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000473 Region tJunctionFreeRegion = Region::createTJunctionFreeRegion(coveredRegion);
474 // Compute the size of all the rects since they may be disconnected.
475 float coveredSize = 0;
476 for (auto rect = tJunctionFreeRegion.begin(); rect < tJunctionFreeRegion.end(); rect++) {
477 float size = rect->width() * rect->height();
478 coveredSize += size;
479 }
480
481 fractionRendered *= (1 - (coveredSize / (screenBounds.getWidth() * screenBounds.getHeight())));
Chavi Weingarten076acac2023-01-19 17:20:43 +0000482
483 if (fractionRendered < thresholds.minFractionRendered) {
484 return false;
485 }
486
487 return true;
488}
489
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700490void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
491 float parentShadowRadius) {
Vishnu Nair4351ad52019-02-11 14:13:02 -0800492 const State& s(getDrawingState());
493
494 // Calculate effective layer transform
495 mEffectiveTransform = parentTransform * getActiveTransform(s);
496
Garfield Tan2c1782c2022-02-16 15:25:05 -0800497 if (CC_UNLIKELY(!isTransformValid())) {
498 ALOGW("Stop computing bounds for %s because it has invalid transformation.",
499 getDebugName());
500 return;
501 }
502
Vishnu Nair4351ad52019-02-11 14:13:02 -0800503 // Transform parent bounds to layer space
504 parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
505
Vishnu Nairc652ff82019-03-15 12:48:54 -0700506 // Calculate source bounds
Vishnu Nair4351ad52019-02-11 14:13:02 -0800507 mSourceBounds = computeSourceBounds(parentBounds);
508
509 // Calculate bounds by croping diplay frame with layer crop and parent bounds
510 FloatRect bounds = mSourceBounds;
511 const Rect layerCrop = getCrop(s);
512 if (!layerCrop.isEmpty()) {
513 bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
514 }
515 bounds = bounds.intersect(parentBounds);
516
517 mBounds = bounds;
518 mScreenBounds = mEffectiveTransform.transform(mBounds);
Vishnu Nairc652ff82019-03-15 12:48:54 -0700519
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700520 // Use the layer's own shadow radius if set. Otherwise get the radius from
521 // parent.
522 if (s.shadowRadius > 0.f) {
523 mEffectiveShadowRadius = s.shadowRadius;
524 } else {
525 mEffectiveShadowRadius = parentShadowRadius;
526 }
527
528 // Shadow radius is passed down to only one layer so if the layer can draw shadows,
529 // don't pass it to its children.
530 const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
531
Vishnu Nair4351ad52019-02-11 14:13:02 -0800532 for (const sp<Layer>& child : mDrawingChildren) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700533 child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
Vishnu Nair4351ad52019-02-11 14:13:02 -0800534 }
Vishnu Nairba354102022-08-01 00:14:18 +0000535
536 if (mPotentialCursor) {
537 prepareCursorCompositionState();
538 }
Vishnu Nair4351ad52019-02-11 14:13:02 -0800539}
540
Vishnu Nair60356342018-11-13 13:00:45 -0800541Rect Layer::getCroppedBufferSize(const State& s) const {
542 Rect size = getBufferSize(s);
543 Rect crop = getCrop(s);
544 if (!crop.isEmpty() && size.isValid()) {
545 size.intersect(crop, &size);
546 } else if (!crop.isEmpty()) {
547 size = crop;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700548 }
Vishnu Nair60356342018-11-13 13:00:45 -0800549 return size;
Mathias Agopian13127d82013-03-05 17:47:11 -0800550}
551
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700552void Layer::setupRoundedCornersCropCoordinates(Rect win,
553 const FloatRect& roundedCornersCrop) const {
554 // Translate win by the rounded corners rect coordinates, to have all values in
555 // layer coordinate space.
556 win.left -= roundedCornersCrop.left;
557 win.right -= roundedCornersCrop.left;
558 win.top -= roundedCornersCrop.top;
559 win.bottom -= roundedCornersCrop.top;
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700560}
561
Lloyd Piquede196652020-01-22 17:29:58 -0800562void Layer::prepareBasicGeometryCompositionState() {
Lloyd Piquec6687342019-03-07 21:34:57 -0800563 const auto& drawingState{getDrawingState()};
Lloyd Piquec6687342019-03-07 21:34:57 -0800564 const auto alpha = static_cast<float>(getAlpha());
565 const bool opaque = isOpaque(drawingState);
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700566 const bool usesRoundedCorners = hasRoundedCorners();
Lloyd Piquec6687342019-03-07 21:34:57 -0800567
568 auto blendMode = Hwc2::IComposerClient::BlendMode::NONE;
569 if (!opaque || alpha != 1.0f) {
570 blendMode = mPremultipliedAlpha ? Hwc2::IComposerClient::BlendMode::PREMULTIPLIED
571 : Hwc2::IComposerClient::BlendMode::COVERAGE;
572 }
573
Alec Mourif4af03e2023-02-11 00:25:24 +0000574 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000575 auto* snapshot = editLayerSnapshot();
576 snapshot->outputFilter = getOutputFilter();
577 snapshot->isVisible = isVisible();
578 snapshot->isOpaque = opaque && !usesRoundedCorners && alpha == 1.f;
Vishnu Naird9e4f462023-10-06 04:05:45 +0000579 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Lloyd Piquec6687342019-03-07 21:34:57 -0800580
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000581 snapshot->contentDirty = contentDirty;
Lloyd Piquec6687342019-03-07 21:34:57 -0800582 contentDirty = false;
583
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000584 snapshot->geomLayerBounds = mBounds;
585 snapshot->geomLayerTransform = getTransform();
586 snapshot->geomInverseLayerTransform = snapshot->geomLayerTransform.inverse();
587 snapshot->transparentRegionHint = getActiveTransparentRegion(drawingState);
Vishnu Naircfb2d252023-01-19 04:44:02 +0000588 snapshot->localTransform = getActiveTransform(drawingState);
589 snapshot->localTransformInverse = snapshot->localTransform.inverse();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000590 snapshot->blendMode = static_cast<Hwc2::IComposerClient::BlendMode>(blendMode);
591 snapshot->alpha = alpha;
Vishnu Nairc6384702023-07-31 12:22:20 -0700592 snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
593 snapshot->blurRegions = getBlurRegions();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000594 snapshot->stretchEffect = getStretchEffect();
Lloyd Piquec6687342019-03-07 21:34:57 -0800595}
596
Lloyd Piquede196652020-01-22 17:29:58 -0800597void Layer::prepareGeometryCompositionState() {
Lloyd Piquea83776c2019-01-29 18:42:32 -0800598 const auto& drawingState{getDrawingState()};
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000599 auto* snapshot = editLayerSnapshot();
David Sodman15094112018-10-11 09:39:37 -0700600
Alec Mourif4af03e2023-02-11 00:25:24 +0000601 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000602 snapshot->geomBufferSize = getBufferSize(drawingState);
603 snapshot->geomContentCrop = getBufferCrop();
604 snapshot->geomCrop = getCrop(drawingState);
605 snapshot->geomBufferTransform = getBufferTransform();
606 snapshot->geomBufferUsesDisplayInverseTransform = getTransformToDisplayInverse();
607 snapshot->geomUsesSourceCrop = usesSourceCrop();
608 snapshot->isSecure = isSecure();
Lloyd Piquede196652020-01-22 17:29:58 -0800609
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000610 snapshot->metadata.clear();
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800611 const auto& supportedMetadata = mFlinger->getHwComposer().getSupportedLayerGenericMetadata();
612 for (const auto& [key, mandatory] : supportedMetadata) {
613 const auto& genericLayerMetadataCompatibilityMap =
614 mFlinger->getGenericLayerMetadataKeyMap();
615 auto compatIter = genericLayerMetadataCompatibilityMap.find(key);
616 if (compatIter == std::end(genericLayerMetadataCompatibilityMap)) {
617 continue;
618 }
619 const uint32_t id = compatIter->second;
620
621 auto it = drawingState.metadata.mMap.find(id);
622 if (it == std::end(drawingState.metadata.mMap)) {
623 continue;
624 }
625
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000626 snapshot->metadata.emplace(key,
627 compositionengine::GenericLayerMetadataEntry{mandatory,
628 it->second});
Lloyd Pique8d9f8362020-02-11 19:13:09 -0800629 }
Lloyd Piquea83776c2019-01-29 18:42:32 -0800630}
David Sodmanba340492018-08-05 21:51:33 -0700631
Lloyd Piquede196652020-01-22 17:29:58 -0800632void Layer::preparePerFrameCompositionState() {
Lloyd Pique688abd42019-02-15 15:42:24 -0800633 const auto& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000634 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000635 auto* snapshot = editLayerSnapshot();
Lloyd Piquef5275482019-01-29 18:42:42 -0800636
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000637 snapshot->forceClientComposition = false;
Lloyd Piquede196652020-01-22 17:29:58 -0800638
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000639 snapshot->isColorspaceAgnostic = isColorSpaceAgnostic();
640 snapshot->dataspace = getDataSpace();
641 snapshot->colorTransform = getColorTransform();
642 snapshot->colorTransformIsIdentity = !hasColorTransform();
643 snapshot->surfaceDamage = surfaceDamageRegion;
644 snapshot->hasProtectedContent = isProtected();
645 snapshot->dimmingEnabled = isDimmingEnabled();
Sally Qi963049b2023-03-23 14:06:21 -0700646 snapshot->currentHdrSdrRatio = getCurrentHdrSdrRatio();
647 snapshot->desiredHdrSdrRatio = getDesiredHdrSdrRatio();
Alec Mourif4af03e2023-02-11 00:25:24 +0000648 snapshot->cachingHint = getCachingHint();
Lloyd Pique688abd42019-02-15 15:42:24 -0800649
Vishnu Nair50c0afe2022-07-11 15:04:07 -0700650 const bool usesRoundedCorners = hasRoundedCorners();
Vishnu Nairc97b8db2019-10-29 18:19:35 -0700651
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000652 snapshot->isOpaque = isOpaque(drawingState) && !usesRoundedCorners && getAlpha() == 1.0_hf;
Lloyd Piquef5275482019-01-29 18:42:42 -0800653
654 // Force client composition for special cases known only to the front-end.
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400655 // Rounded corners no longer force client composition, since we may use a
656 // hole punch so that the layer will appear to have rounded corners.
Alec Mouri994761f2023-08-04 21:50:55 +0000657 if (drawShadows() || snapshot->stretchEffect.hasEffect()) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000658 snapshot->forceClientComposition = true;
Lloyd Piquef5275482019-01-29 18:42:42 -0800659 }
Vishnu Nairb801a982021-11-02 15:12:08 -0700660 // If there are no visible region changes, we still need to update blur parameters.
Vishnu Nairc6384702023-07-31 12:22:20 -0700661 snapshot->blurRegions = getBlurRegions();
662 snapshot->backgroundBlurRadius = getBackgroundBlurRadius();
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400663
664 // Layer framerate is used in caching decisions.
665 // Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
666 // LayerFECompositionState where it would be visible to Flattener.
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000667 snapshot->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
Patrick Williamsbb25f802022-08-30 23:02:34 +0000668
669 if (hasBufferOrSidebandStream()) {
670 preparePerFrameBufferCompositionState();
671 } else {
672 preparePerFrameEffectsCompositionState();
673 }
674}
675
676void Layer::preparePerFrameBufferCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000677 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000678 auto* snapshot = editLayerSnapshot();
Alec Mourif4af03e2023-02-11 00:25:24 +0000679 // Sideband layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000680 if (snapshot->sidebandStream.get() && !snapshot->sidebandStreamHasFrame) {
681 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000682 aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
683 return;
684 } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000685 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000686 aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
ramindanib2158ee2023-02-13 20:29:59 -0800687 } else if ((mDrawingState.flags & layer_state_t::eLayerIsRefreshRateIndicator) != 0) {
688 snapshot->compositionType =
689 aidl::android::hardware::graphics::composer3::Composition::REFRESH_RATE_INDICATOR;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000690 } else {
691 // Normal buffer layers
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000692 snapshot->hdrMetadata = mBufferInfo.mHdrMetadata;
693 snapshot->compositionType = mPotentialCursor
Patrick Williamsbb25f802022-08-30 23:02:34 +0000694 ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
695 : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
696 }
697
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000698 snapshot->buffer = getBuffer();
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000699 snapshot->acquireFence = mBufferInfo.mFence;
700 snapshot->frameNumber = mBufferInfo.mFrameNumber;
701 snapshot->sidebandStreamHasFrame = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +0000702}
703
704void Layer::preparePerFrameEffectsCompositionState() {
Alec Mourif4af03e2023-02-11 00:25:24 +0000705 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000706 auto* snapshot = editLayerSnapshot();
707 snapshot->color = getColor();
708 snapshot->compositionType =
Patrick Williamsbb25f802022-08-30 23:02:34 +0000709 aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
Lloyd Piquef5275482019-01-29 18:42:42 -0800710}
711
Lloyd Piquede196652020-01-22 17:29:58 -0800712void Layer::prepareCursorCompositionState() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800713 const State& drawingState{getDrawingState()};
Alec Mourif4af03e2023-02-11 00:25:24 +0000714 // Please keep in sync with LayerSnapshotBuilder
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000715 auto* snapshot = editLayerSnapshot();
Lloyd Piquec7b0c752019-03-07 20:59:59 -0800716
717 // Apply the layer's transform, followed by the display's global transform
718 // Here we're guaranteed that the layer's transform preserves rects
719 Rect win = getCroppedBufferSize(drawingState);
720 // Subtract the transparent region and snap to the bounds
721 Rect bounds = reduce(win, getActiveTransparentRegion(drawingState));
722 Rect frame(getTransform().transform(bounds));
723
Vishnu Nairbedb44b2022-08-02 21:47:40 +0000724 snapshot->cursorFrame = frame;
Lloyd Piquede196652020-01-22 17:29:58 -0800725}
726
Lloyd Piquea83776c2019-01-29 18:42:32 -0800727const char* Layer::getDebugName() const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700728 return mName.c_str();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800729}
730
Mathias Agopian13127d82013-03-05 17:47:11 -0800731// ---------------------------------------------------------------------------
732// drawing...
733// ---------------------------------------------------------------------------
734
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500735aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
736 const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -0700737 const auto outputLayer = findOutputLayerForDisplay(&display);
Vishnu Nair3cc15a42023-06-30 06:20:22 +0000738 return getCompositionType(outputLayer);
739}
740
741aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
742 const compositionengine::OutputLayer* outputLayer) const {
Alec Mouri6b9e9912020-01-21 10:50:24 -0800743 if (outputLayer == nullptr) {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500744 return aidl::android::hardware::graphics::composer3::Composition::INVALID;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800745 }
746 if (outputLayer->getState().hwc) {
747 return (*outputLayer->getState().hwc).hwcCompositionType;
748 } else {
Leon Scroggins III2e1aa182021-12-01 17:33:12 -0500749 return aidl::android::hardware::graphics::composer3::Composition::CLIENT;
Alec Mouri6b9e9912020-01-21 10:50:24 -0800750 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800751}
752
Mathias Agopian13127d82013-03-05 17:47:11 -0800753// ----------------------------------------------------------------------------
754// local state
755// ----------------------------------------------------------------------------
756
David Sodman41fdfc92017-11-06 16:09:56 -0800757bool Layer::isSecure() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800758 const State& s(mDrawingState);
Garfield Tande619fa2020-10-02 17:13:53 -0700759 if (s.flags & layer_state_t::eLayerSecure) {
760 return true;
761 }
762
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000763 const auto p = mDrawingParent.promote();
Garfield Tande619fa2020-10-02 17:13:53 -0700764 return (p != nullptr) ? p->isSecure() : false;
Dan Stoza23116082015-06-18 14:58:39 -0700765}
766
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100767void Layer::transferAvailableJankData(const std::deque<sp<CallbackHandle>>& handles,
768 std::vector<JankData>& jankData) {
769 if (mPendingJankClassifications.empty() ||
770 !mPendingJankClassifications.front()->getJankType()) {
771 return;
772 }
773
774 bool includeJankData = false;
775 for (const auto& handle : handles) {
776 for (const auto& cb : handle->callbackIds) {
777 if (cb.includeJankData) {
778 includeJankData = true;
779 break;
780 }
781 }
782
783 if (includeJankData) {
784 jankData.reserve(mPendingJankClassifications.size());
785 break;
786 }
787 }
788
789 while (!mPendingJankClassifications.empty() &&
790 mPendingJankClassifications.front()->getJankType()) {
791 if (includeJankData) {
792 std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
793 mPendingJankClassifications.front();
Pascal Muetschardac7bcd92023-10-03 15:05:36 +0200794 jankData.emplace_back(JankData(surfaceFrame->getToken(),
795 surfaceFrame->getJankType().value(),
796 surfaceFrame->getRenderRate().getPeriodNsecs()));
Pascal Muetschardf54181b2022-12-13 14:53:25 +0100797 }
798 mPendingJankClassifications.pop_front();
799 }
800}
801
Mathias Agopian13127d82013-03-05 17:47:11 -0800802// ----------------------------------------------------------------------------
803// transaction
804// ----------------------------------------------------------------------------
Ady Abraham83729882018-12-07 12:26:48 -0800805
Vishnu Naira156f482023-02-22 00:23:38 +0000806uint32_t Layer::doTransaction(uint32_t flags) {
Marissa Wall61c58622018-07-18 10:12:20 -0700807 ATRACE_CALL();
808
Robert Carr0758e5d2021-03-11 22:15:04 -0800809 // TODO: This is unfortunate.
Robert Carr6a160312021-05-17 12:08:20 -0700810 mDrawingStateModified = mDrawingState.modified;
811 mDrawingState.modified = false;
Marissa Wall61c58622018-07-18 10:12:20 -0700812
Alec Mourib416efd2018-09-06 21:01:59 +0000813 const State& s(getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -0700814
Robert Carr6a160312021-05-17 12:08:20 -0700815 if (updateGeometry()) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800816 // invalidate and recompute the visible regions if needed
817 flags |= Layer::eVisibleRegion;
818 }
819
Robert Carr6a160312021-05-17 12:08:20 -0700820 if (s.sequence != mLastCommittedTxSequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800821 // invalidate and recompute the visible regions if needed
Arthur Hung9ed43392022-05-27 06:31:57 +0000822 mLastCommittedTxSequence = s.sequence;
Mathias Agopian13127d82013-03-05 17:47:11 -0800823 flags |= eVisibleRegion;
824 this->contentDirty = true;
825
826 // we may use linear filtering, if the matrix scales us
Robert Carr6a160312021-05-17 12:08:20 -0700827 mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
Mathias Agopian13127d82013-03-05 17:47:11 -0800828 }
829
Arthur Hung9ed43392022-05-27 06:31:57 +0000830 if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
831 mFlinger->mUpdateInputInfo = true;
832 }
833
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700834 commitTransaction();
Robert Carra1257842020-01-31 13:48:28 -0800835
Mathias Agopian13127d82013-03-05 17:47:11 -0800836 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800837}
838
Vishnu Nairc1d19d72023-08-10 12:35:11 -0700839void Layer::commitTransaction() {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000840 // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
841 // bufferSurfaceFrameTX will be presented in latchBuffer.
842 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
843 if (surfaceFrame->getPresentState() != PresentState::Presented) {
844 // With applyPendingStates, we could end up having presented surfaceframes from previous
845 // states
Vishnu Nair7fe69ed2023-02-13 10:13:26 -0800846 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000847 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
848 }
849 }
Robert Carr6a160312021-05-17 12:08:20 -0700850 mDrawingState.bufferlessSurfaceFramesTX.clear();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700851}
852
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700853uint32_t Layer::clearTransactionFlags(uint32_t mask) {
854 const auto flags = mTransactionFlags & mask;
855 mTransactionFlags &= ~mask;
856 return flags;
Mathias Agopian13127d82013-03-05 17:47:11 -0800857}
858
Dominik Laskowski9e168db2021-05-27 16:05:12 -0700859void Layer::setTransactionFlags(uint32_t mask) {
860 mTransactionFlags |= mask;
Mathias Agopian13127d82013-03-05 17:47:11 -0800861}
862
Robert Carr1f0a16a2016-10-24 16:27:39 -0700863bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
864 ssize_t idx = mCurrentChildren.indexOf(childLayer);
865 if (idx < 0) {
866 return false;
867 }
868 if (childLayer->setLayer(z)) {
869 mCurrentChildren.removeAt(idx);
870 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800871 return true;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700872 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800873 return false;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700874}
875
Robert Carr503c7042017-09-27 15:06:08 -0700876bool Layer::setChildRelativeLayer(const sp<Layer>& childLayer,
877 const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
878 ssize_t idx = mCurrentChildren.indexOf(childLayer);
879 if (idx < 0) {
880 return false;
881 }
882 if (childLayer->setRelativeLayer(relativeToHandle, relativeZ)) {
883 mCurrentChildren.removeAt(idx);
884 mCurrentChildren.add(childLayer);
Robert Carr503d2bd2017-12-04 15:49:47 -0800885 return true;
Robert Carr503c7042017-09-27 15:06:08 -0700886 }
Robert Carr503d2bd2017-12-04 15:49:47 -0800887 return false;
Robert Carr503c7042017-09-27 15:06:08 -0700888}
889
Robert Carrae060832016-11-28 10:51:00 -0800890bool Layer::setLayer(int32_t z) {
Robert Carr6a160312021-05-17 12:08:20 -0700891 if (mDrawingState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
892 mDrawingState.sequence++;
893 mDrawingState.z = z;
894 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700895
Robert Carra70e91c2021-06-11 13:59:52 -0700896 mFlinger->mSomeChildrenChanged = true;
897
Robert Carrdb66e622017-04-10 16:55:57 -0700898 // Discard all relative layering.
Robert Carr6a160312021-05-17 12:08:20 -0700899 if (mDrawingState.zOrderRelativeOf != nullptr) {
900 sp<Layer> strongRelative = mDrawingState.zOrderRelativeOf.promote();
Robert Carrdb66e622017-04-10 16:55:57 -0700901 if (strongRelative != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700902 strongRelative->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700903 }
chaviw606e5cf2019-03-01 10:12:10 -0800904 setZOrderRelativeOf(nullptr);
Robert Carrdb66e622017-04-10 16:55:57 -0700905 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800906 setTransactionFlags(eTransactionNeeded);
907 return true;
908}
Robert Carr1f0a16a2016-10-24 16:27:39 -0700909
Robert Carrdb66e622017-04-10 16:55:57 -0700910void Layer::removeZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700911 mDrawingState.zOrderRelatives.remove(relative);
912 mDrawingState.sequence++;
913 mDrawingState.modified = true;
Robert Carrdb66e622017-04-10 16:55:57 -0700914 setTransactionFlags(eTransactionNeeded);
915}
916
917void Layer::addZOrderRelative(const wp<Layer>& relative) {
Robert Carr6a160312021-05-17 12:08:20 -0700918 mDrawingState.zOrderRelatives.add(relative);
919 mDrawingState.modified = true;
920 mDrawingState.sequence++;
Robert Carrdb66e622017-04-10 16:55:57 -0700921 setTransactionFlags(eTransactionNeeded);
922}
923
chaviw606e5cf2019-03-01 10:12:10 -0800924void Layer::setZOrderRelativeOf(const wp<Layer>& relativeOf) {
Robert Carr6a160312021-05-17 12:08:20 -0700925 mDrawingState.zOrderRelativeOf = relativeOf;
926 mDrawingState.sequence++;
927 mDrawingState.modified = true;
928 mDrawingState.isRelativeOf = relativeOf != nullptr;
chaviwbdb8b802019-10-14 09:17:12 -0700929
chaviw606e5cf2019-03-01 10:12:10 -0800930 setTransactionFlags(eTransactionNeeded);
931}
932
Robert Carr503d2bd2017-12-04 15:49:47 -0800933bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
Vishnu Nair07e2a482022-10-18 19:18:16 +0000934 sp<Layer> relative = LayerHandle::getLayer(relativeToHandle);
Robert Carrdb66e622017-04-10 16:55:57 -0700935 if (relative == nullptr) {
936 return false;
937 }
938
Robert Carr6a160312021-05-17 12:08:20 -0700939 if (mDrawingState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
940 mDrawingState.zOrderRelativeOf == relative) {
Robert Carr503d2bd2017-12-04 15:49:47 -0800941 return false;
942 }
943
Robert Carr88b85e12022-03-21 15:47:35 -0700944 if (CC_UNLIKELY(relative->usingRelativeZ(LayerVector::StateSet::Drawing)) &&
945 (relative->mDrawingState.zOrderRelativeOf == this)) {
946 ALOGE("Detected relative layer loop between %s and %s",
947 mName.c_str(), relative->mName.c_str());
948 ALOGE("Ignoring new call to set relative layer");
949 return false;
950 }
951
Robert Carra70e91c2021-06-11 13:59:52 -0700952 mFlinger->mSomeChildrenChanged = true;
953
Robert Carr6a160312021-05-17 12:08:20 -0700954 mDrawingState.sequence++;
955 mDrawingState.modified = true;
956 mDrawingState.z = relativeZ;
Robert Carrdb66e622017-04-10 16:55:57 -0700957
Robert Carr6a160312021-05-17 12:08:20 -0700958 auto oldZOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
chaviw9ab4bd12017-11-03 13:11:00 -0700959 if (oldZOrderRelativeOf != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700960 oldZOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
chaviw9ab4bd12017-11-03 13:11:00 -0700961 }
chaviw606e5cf2019-03-01 10:12:10 -0800962 setZOrderRelativeOf(relative);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700963 relative->addZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carrdb66e622017-04-10 16:55:57 -0700964
965 setTransactionFlags(eTransactionNeeded);
966
967 return true;
968}
969
Winson Chunga30f7c92021-06-29 15:42:56 -0700970bool Layer::setTrustedOverlay(bool isTrustedOverlay) {
971 if (mDrawingState.isTrustedOverlay == isTrustedOverlay) return false;
972 mDrawingState.isTrustedOverlay = isTrustedOverlay;
973 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +0000974 mFlinger->mUpdateInputInfo = true;
Winson Chunga30f7c92021-06-29 15:42:56 -0700975 setTransactionFlags(eTransactionNeeded);
976 return true;
977}
978
979bool Layer::isTrustedOverlay() const {
980 if (getDrawingState().isTrustedOverlay) {
981 return true;
982 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +0000983 const auto& p = mDrawingParent.promote();
Winson Chunga30f7c92021-06-29 15:42:56 -0700984 return (p != nullptr) && p->isTrustedOverlay();
985}
986
Dan Stoza9e56aa02015-11-02 13:00:03 -0800987bool Layer::setAlpha(float alpha) {
Robert Carr6a160312021-05-17 12:08:20 -0700988 if (mDrawingState.color.a == alpha) return false;
989 mDrawingState.sequence++;
990 mDrawingState.color.a = alpha;
991 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -0800992 setTransactionFlags(eTransactionNeeded);
993 return true;
994}
chaviw13fdc492017-06-27 12:40:18 -0700995
Valerie Haudd0b7572019-01-29 14:59:27 -0800996bool Layer::setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace) {
Robert Carr6a160312021-05-17 12:08:20 -0700997 if (!mDrawingState.bgColorLayer && alpha == 0) {
chaviw13fdc492017-06-27 12:40:18 -0700998 return false;
Valerie Hauaa194562019-02-05 16:21:38 -0800999 }
Robert Carr6a160312021-05-17 12:08:20 -07001000 mDrawingState.sequence++;
1001 mDrawingState.modified = true;
Valerie Hauaa194562019-02-05 16:21:38 -08001002 setTransactionFlags(eTransactionNeeded);
1003
Robert Carr6a160312021-05-17 12:08:20 -07001004 if (!mDrawingState.bgColorLayer && alpha != 0) {
Valerie Haudd0b7572019-01-29 14:59:27 -08001005 // create background color layer if one does not yet exist
Vishnu Nairfa247b12020-02-11 08:58:26 -08001006 uint32_t flags = ISurfaceComposerClient::eFXSurfaceEffect;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001007 std::string name = mName + "BackgroundColorLayer";
Robert Carr6a160312021-05-17 12:08:20 -07001008 mDrawingState.bgColorLayer = mFlinger->getFactory().createEffectLayer(
Kean Mariotti4ba343c2023-04-19 13:31:02 +00001009 surfaceflinger::LayerCreationArgs(mFlinger.get(), nullptr, std::move(name), flags,
1010 LayerMetadata()));
chaviw13fdc492017-06-27 12:40:18 -07001011
Valerie Haudd0b7572019-01-29 14:59:27 -08001012 // add to child list
Robert Carr6a160312021-05-17 12:08:20 -07001013 addChild(mDrawingState.bgColorLayer);
Valerie Haudd0b7572019-01-29 14:59:27 -08001014 mFlinger->mLayersAdded = true;
1015 // set up SF to handle added color layer
1016 if (isRemovedFromCurrentState()) {
Josh Gao194ff392022-09-08 16:19:29 -07001017 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001018 mDrawingState.bgColorLayer->onRemovedFromCurrentState();
Valerie Haudd0b7572019-01-29 14:59:27 -08001019 }
1020 mFlinger->setTransactionFlags(eTransactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001021 } else if (mDrawingState.bgColorLayer && alpha == 0) {
Josh Gao194ff392022-09-08 16:19:29 -07001022 MUTEX_ALIAS(mFlinger->mStateLock, mDrawingState.bgColorLayer->mFlinger->mStateLock);
Robert Carr6a160312021-05-17 12:08:20 -07001023 mDrawingState.bgColorLayer->reparent(nullptr);
1024 mDrawingState.bgColorLayer = nullptr;
Valerie Haudd0b7572019-01-29 14:59:27 -08001025 return true;
1026 }
1027
Robert Carr6a160312021-05-17 12:08:20 -07001028 mDrawingState.bgColorLayer->setColor(color);
1029 mDrawingState.bgColorLayer->setLayer(std::numeric_limits<int32_t>::min());
1030 mDrawingState.bgColorLayer->setAlpha(alpha);
1031 mDrawingState.bgColorLayer->setDataspace(dataspace);
Valerie Haudd0b7572019-01-29 14:59:27 -08001032
chaviw13fdc492017-06-27 12:40:18 -07001033 return true;
1034}
1035
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001036bool Layer::setCornerRadius(float cornerRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001037 if (mDrawingState.cornerRadius == cornerRadius) return false;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001038
Robert Carr6a160312021-05-17 12:08:20 -07001039 mDrawingState.sequence++;
1040 mDrawingState.cornerRadius = cornerRadius;
1041 mDrawingState.modified = true;
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001042 setTransactionFlags(eTransactionNeeded);
1043 return true;
1044}
1045
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001046bool Layer::setBackgroundBlurRadius(int backgroundBlurRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001047 if (mDrawingState.backgroundBlurRadius == backgroundBlurRadius) return false;
Vishnu Nairb801a982021-11-02 15:12:08 -07001048 // If we start or stop drawing blur then the layer's visibility state may change so increment
1049 // the magic sequence number.
1050 if (mDrawingState.backgroundBlurRadius == 0 || backgroundBlurRadius == 0) {
1051 mDrawingState.sequence++;
1052 }
Robert Carr6a160312021-05-17 12:08:20 -07001053 mDrawingState.backgroundBlurRadius = backgroundBlurRadius;
1054 mDrawingState.modified = true;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001055 setTransactionFlags(eTransactionNeeded);
1056 return true;
1057}
Marissa Wall61c58622018-07-18 10:12:20 -07001058
Mathias Agopian13127d82013-03-05 17:47:11 -08001059bool Layer::setTransparentRegionHint(const Region& transparent) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001060 mDrawingState.sequence++;
1061 mDrawingState.transparentRegionHint = transparent;
Robert Carr6a160312021-05-17 12:08:20 -07001062 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001063 setTransactionFlags(eTransactionNeeded);
1064 return true;
1065}
Ana Krulecc84d09b2019-11-02 23:10:29 +01001066
Lucas Dupinc3800b82020-10-02 16:24:48 -07001067bool Layer::setBlurRegions(const std::vector<BlurRegion>& blurRegions) {
Vishnu Nairb801a982021-11-02 15:12:08 -07001068 // If we start or stop drawing blur then the layer's visibility state may change so increment
1069 // the magic sequence number.
1070 if (mDrawingState.blurRegions.size() == 0 || blurRegions.size() == 0) {
1071 mDrawingState.sequence++;
1072 }
Robert Carr6a160312021-05-17 12:08:20 -07001073 mDrawingState.blurRegions = blurRegions;
1074 mDrawingState.modified = true;
Lucas Dupinc3800b82020-10-02 16:24:48 -07001075 setTransactionFlags(eTransactionNeeded);
1076 return true;
1077}
1078
Vishnu Nairf6eddb62021-01-27 22:02:11 -08001079bool Layer::setFlags(uint32_t flags, uint32_t mask) {
Robert Carr6a160312021-05-17 12:08:20 -07001080 const uint32_t newFlags = (mDrawingState.flags & ~mask) | (flags & mask);
1081 if (mDrawingState.flags == newFlags) return false;
1082 mDrawingState.sequence++;
1083 mDrawingState.flags = newFlags;
1084 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001085 setTransactionFlags(eTransactionNeeded);
1086 return true;
1087}
Robert Carr99e27f02016-06-16 15:18:02 -07001088
chaviw25714502021-02-11 10:01:08 -08001089bool Layer::setCrop(const Rect& crop) {
Vishnu Nairea04b6f2022-08-19 21:28:17 +00001090 if (mDrawingState.crop == crop) return false;
Robert Carr6a160312021-05-17 12:08:20 -07001091 mDrawingState.sequence++;
Robert Carr6a160312021-05-17 12:08:20 -07001092 mDrawingState.crop = crop;
Robert Carr7bf247e2017-05-18 14:02:49 -07001093
Robert Carr6a160312021-05-17 12:08:20 -07001094 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001095 setTransactionFlags(eTransactionNeeded);
1096 return true;
1097}
Robert Carr8d5227b2017-03-16 15:41:03 -07001098
Evan Roskyef876c92019-01-25 17:46:06 -08001099bool Layer::setMetadata(const LayerMetadata& data) {
Robert Carr6a160312021-05-17 12:08:20 -07001100 if (!mDrawingState.metadata.merge(data, true /* eraseEmpty */)) return false;
1101 mDrawingState.modified = true;
David Sodman41fdfc92017-11-06 16:09:56 -08001102 setTransactionFlags(eTransactionNeeded);
Evan Rosky1f6d6d52018-12-06 10:47:26 -08001103 return true;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001104}
1105
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001106bool Layer::setLayerStack(ui::LayerStack layerStack) {
Robert Carr6a160312021-05-17 12:08:20 -07001107 if (mDrawingState.layerStack == layerStack) return false;
1108 mDrawingState.sequence++;
1109 mDrawingState.layerStack = layerStack;
1110 mDrawingState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001111 setTransactionFlags(eTransactionNeeded);
1112 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001113}
1114
Peiyong Linc502cb72019-03-01 15:00:23 -08001115bool Layer::setColorSpaceAgnostic(const bool agnostic) {
Robert Carr6a160312021-05-17 12:08:20 -07001116 if (mDrawingState.colorSpaceAgnostic == agnostic) {
Peiyong Linc502cb72019-03-01 15:00:23 -08001117 return false;
1118 }
Robert Carr6a160312021-05-17 12:08:20 -07001119 mDrawingState.sequence++;
1120 mDrawingState.colorSpaceAgnostic = agnostic;
1121 mDrawingState.modified = true;
Peiyong Linc502cb72019-03-01 15:00:23 -08001122 setTransactionFlags(eTransactionNeeded);
1123 return true;
1124}
1125
Sally Qi81d95e62022-03-21 19:41:33 -07001126bool Layer::setDimmingEnabled(const bool dimmingEnabled) {
1127 if (mDrawingState.dimmingEnabled == dimmingEnabled) return false;
1128
1129 mDrawingState.sequence++;
1130 mDrawingState.dimmingEnabled = dimmingEnabled;
1131 mDrawingState.modified = true;
1132 setTransactionFlags(eTransactionNeeded);
1133 return true;
1134}
1135
Ana Krulecc84d09b2019-11-02 23:10:29 +01001136bool Layer::setFrameRateSelectionPriority(int32_t priority) {
Robert Carr6a160312021-05-17 12:08:20 -07001137 if (mDrawingState.frameRateSelectionPriority == priority) return false;
1138 mDrawingState.frameRateSelectionPriority = priority;
1139 mDrawingState.sequence++;
1140 mDrawingState.modified = true;
Ana Krulecc84d09b2019-11-02 23:10:29 +01001141 setTransactionFlags(eTransactionNeeded);
1142 return true;
1143}
1144
1145int32_t Layer::getFrameRateSelectionPriority() const {
1146 // Check if layer has priority set.
1147 if (mDrawingState.frameRateSelectionPriority != PRIORITY_UNSET) {
1148 return mDrawingState.frameRateSelectionPriority;
1149 }
1150 // If not, search whether its parents have it set.
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001151 sp<Layer> parent = getParent();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001152 if (parent != nullptr) {
1153 return parent->getFrameRateSelectionPriority();
1154 }
1155
1156 return Layer::PRIORITY_UNSET;
1157}
1158
Andy Labrada096227e2022-06-15 16:58:11 +00001159bool Layer::setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility) {
1160 if (mDrawingState.defaultFrameRateCompatibility == compatibility) return false;
1161 mDrawingState.defaultFrameRateCompatibility = compatibility;
1162 mDrawingState.modified = true;
Vishnu Nair80e8cfe2023-09-29 17:03:45 -07001163 mFlinger->mScheduler->setDefaultFrameRateCompatibility(sequence, compatibility);
Andy Labrada096227e2022-06-15 16:58:11 +00001164 setTransactionFlags(eTransactionNeeded);
1165 return true;
1166}
1167
Vishnu Nair3fbe3262023-09-29 17:07:00 -07001168scheduler::FrameRateCompatibility Layer::getDefaultFrameRateCompatibility() const {
Andy Labrada096227e2022-06-15 16:58:11 +00001169 return mDrawingState.defaultFrameRateCompatibility;
1170}
1171
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001172bool Layer::isLayerFocusedBasedOnPriority(int32_t priority) {
1173 return priority == PRIORITY_FOCUSED_WITH_MODE || priority == PRIORITY_FOCUSED_WITHOUT_MODE;
1174};
1175
Vishnu Nair73908d12022-10-24 21:46:42 -07001176ui::LayerStack Layer::getLayerStack(LayerVector::StateSet state) const {
1177 bool useDrawing = state == LayerVector::StateSet::Drawing;
1178 const auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
1179 if (parent) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001180 return parent->getLayerStack();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001181 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001182 return getDrawingState().layerStack;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001183}
1184
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001185bool Layer::setShadowRadius(float shadowRadius) {
Robert Carr6a160312021-05-17 12:08:20 -07001186 if (mDrawingState.shadowRadius == shadowRadius) {
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001187 return false;
1188 }
1189
Robert Carr6a160312021-05-17 12:08:20 -07001190 mDrawingState.sequence++;
1191 mDrawingState.shadowRadius = shadowRadius;
1192 mDrawingState.modified = true;
Vishnu Nairc97b8db2019-10-29 18:19:35 -07001193 setTransactionFlags(eTransactionNeeded);
1194 return true;
1195}
1196
Vishnu Nair6213bd92020-05-08 17:42:25 -07001197bool Layer::setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint) {
Robert Carr6a160312021-05-17 12:08:20 -07001198 if (mDrawingState.fixedTransformHint == fixedTransformHint) {
Vishnu Nair6213bd92020-05-08 17:42:25 -07001199 return false;
1200 }
1201
Robert Carr6a160312021-05-17 12:08:20 -07001202 mDrawingState.sequence++;
1203 mDrawingState.fixedTransformHint = fixedTransformHint;
1204 mDrawingState.modified = true;
Vishnu Nair6213bd92020-05-08 17:42:25 -07001205 setTransactionFlags(eTransactionNeeded);
1206 return true;
1207}
1208
John Reckcdb4ed72021-02-04 13:39:33 -05001209bool Layer::setStretchEffect(const StretchEffect& effect) {
1210 StretchEffect temp = effect;
1211 temp.sanitize();
Robert Carr6a160312021-05-17 12:08:20 -07001212 if (mDrawingState.stretchEffect == temp) {
John Reckcdb4ed72021-02-04 13:39:33 -05001213 return false;
1214 }
Robert Carr6a160312021-05-17 12:08:20 -07001215 mDrawingState.sequence++;
1216 mDrawingState.stretchEffect = temp;
1217 mDrawingState.modified = true;
John Reckcdb4ed72021-02-04 13:39:33 -05001218 setTransactionFlags(eTransactionNeeded);
1219 return true;
1220}
1221
John Reckc00c6692021-02-16 11:37:33 -05001222StretchEffect Layer::getStretchEffect() const {
1223 if (mDrawingState.stretchEffect.hasEffect()) {
1224 return mDrawingState.stretchEffect;
1225 }
1226
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001227 sp<Layer> parent = getParent();
John Reckc00c6692021-02-16 11:37:33 -05001228 if (parent != nullptr) {
1229 auto effect = parent->getStretchEffect();
1230 if (effect.hasEffect()) {
1231 // TODO(b/179047472): Map it? Or do we make the effect be in global space?
1232 return effect;
1233 }
1234 }
1235 return StretchEffect{};
1236}
1237
Rachel Lee0faad6c2023-09-08 13:34:34 -07001238bool Layer::propagateFrameRateForLayerTree(FrameRate parentFrameRate, bool overrideChildren,
1239 bool* transactionNeeded) {
1240 // Gets the frame rate to propagate to children.
Ady Abrahama850c182021-08-04 13:04:37 -07001241 const auto frameRate = [&] {
Rachel Lee0faad6c2023-09-08 13:34:34 -07001242 if (overrideChildren && parentFrameRate.isValid()) {
1243 return parentFrameRate;
1244 }
1245
Rachel Leece6e0042023-06-27 11:22:54 -07001246 if (mDrawingState.frameRate.isValid()) {
Ady Abrahama850c182021-08-04 13:04:37 -07001247 return mDrawingState.frameRate;
1248 }
1249
1250 return parentFrameRate;
1251 }();
1252
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001253 auto now = systemTime();
1254 *transactionNeeded |= setFrameRateForLayerTreeLegacy(frameRate, now);
Ady Abrahama850c182021-08-04 13:04:37 -07001255
Rachel Leea021bb02023-11-20 21:51:09 -08001256 // The frame rate is propagated to the children by default, but some properties may override it.
Ady Abrahama850c182021-08-04 13:04:37 -07001257 bool childrenHaveFrameRate = false;
Rachel Leea021bb02023-11-20 21:51:09 -08001258 const bool overrideChildrenFrameRate = overrideChildren || shouldOverrideChildrenFrameRate();
1259 const bool canPropagateFrameRate = shouldPropagateFrameRate() || overrideChildrenFrameRate;
Ady Abrahama850c182021-08-04 13:04:37 -07001260 for (const sp<Layer>& child : mCurrentChildren) {
1261 childrenHaveFrameRate |=
Rachel Leea021bb02023-11-20 21:51:09 -08001262 child->propagateFrameRateForLayerTree(canPropagateFrameRate ? frameRate
1263 : FrameRate(),
1264 overrideChildrenFrameRate, transactionNeeded);
Ady Abrahama850c182021-08-04 13:04:37 -07001265 }
1266
Rachel Leece6e0042023-06-27 11:22:54 -07001267 // If we don't have a valid frame rate specification, but the children do, we set this
Ady Abrahama850c182021-08-04 13:04:37 -07001268 // layer as NoVote to allow the children to control the refresh rate
Rachel Leece6e0042023-06-27 11:22:54 -07001269 if (!frameRate.isValid() && childrenHaveFrameRate) {
Ady Abrahama850c182021-08-04 13:04:37 -07001270 *transactionNeeded |=
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001271 setFrameRateForLayerTreeLegacy(FrameRate(Fps(), FrameRateCompatibility::NoVote),
1272 now);
Ady Abrahama850c182021-08-04 13:04:37 -07001273 }
1274
Rachel Leece6e0042023-06-27 11:22:54 -07001275 // We return whether this layer or its children has a vote. We ignore ExactOrMultiple votes for
Ady Abrahama850c182021-08-04 13:04:37 -07001276 // the same reason we are allowing touch boost for those layers. See
Ady Abraham68636062022-11-16 17:07:25 -08001277 // RefreshRateSelector::rankFrameRates for details.
Ady Abrahama850c182021-08-04 13:04:37 -07001278 const auto layerVotedWithDefaultCompatibility =
Rachel Leece6e0042023-06-27 11:22:54 -07001279 frameRate.vote.rate.isValid() && frameRate.vote.type == FrameRateCompatibility::Default;
1280 const auto layerVotedWithNoVote = frameRate.vote.type == FrameRateCompatibility::NoVote;
1281 const auto layerVotedWithCategory = frameRate.category != FrameRateCategory::Default;
Ady Abrahama850c182021-08-04 13:04:37 -07001282 const auto layerVotedWithExactCompatibility =
Rachel Leece6e0042023-06-27 11:22:54 -07001283 frameRate.vote.rate.isValid() && frameRate.vote.type == FrameRateCompatibility::Exact;
1284 return layerVotedWithDefaultCompatibility || layerVotedWithNoVote || layerVotedWithCategory ||
Ady Abrahama850c182021-08-04 13:04:37 -07001285 layerVotedWithExactCompatibility || childrenHaveFrameRate;
1286}
1287
Ady Abraham60e42ea2020-03-09 19:17:31 -07001288void Layer::updateTreeHasFrameRateVote() {
Ady Abrahama850c182021-08-04 13:04:37 -07001289 const auto root = [&]() -> sp<Layer> {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001290 sp<Layer> layer = sp<Layer>::fromExisting(this);
Ady Abrahama850c182021-08-04 13:04:37 -07001291 while (auto parent = layer->getParent()) {
1292 layer = parent;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001293 }
Ady Abrahama850c182021-08-04 13:04:37 -07001294 return layer;
1295 }();
Ady Abraham60e42ea2020-03-09 19:17:31 -07001296
Ady Abraham60e42ea2020-03-09 19:17:31 -07001297 bool transactionNeeded = false;
Rachel Lee0faad6c2023-09-08 13:34:34 -07001298 root->propagateFrameRateForLayerTree({}, false, &transactionNeeded);
Robert Carr6a160312021-05-17 12:08:20 -07001299
Ady Abrahama850c182021-08-04 13:04:37 -07001300 // TODO(b/195668952): we probably don't need eTraversalNeeded here
Ady Abraham60e42ea2020-03-09 19:17:31 -07001301 if (transactionNeeded) {
1302 mFlinger->setTransactionFlags(eTraversalNeeded);
1303 }
1304}
1305
Rachel Leece6e0042023-06-27 11:22:54 -07001306bool Layer::setFrameRate(FrameRate::FrameRateVote frameRateVote) {
1307 if (mDrawingState.frameRate.vote == frameRateVote) {
Steven Thomas3172e202020-01-06 19:25:30 -08001308 return false;
1309 }
1310
Robert Carr6a160312021-05-17 12:08:20 -07001311 mDrawingState.sequence++;
Rachel Leece6e0042023-06-27 11:22:54 -07001312 mDrawingState.frameRate.vote = frameRateVote;
1313 mDrawingState.modified = true;
1314
1315 updateTreeHasFrameRateVote();
1316
1317 setTransactionFlags(eTransactionNeeded);
1318 return true;
1319}
1320
Rachel Lee67afbea2023-09-28 15:35:07 -07001321bool Layer::setFrameRateCategory(FrameRateCategory category, bool smoothSwitchOnly) {
1322 if (mDrawingState.frameRate.category == category &&
1323 mDrawingState.frameRate.categorySmoothSwitchOnly == smoothSwitchOnly) {
Rachel Leece6e0042023-06-27 11:22:54 -07001324 return false;
1325 }
1326
1327 mDrawingState.sequence++;
1328 mDrawingState.frameRate.category = category;
Rachel Lee67afbea2023-09-28 15:35:07 -07001329 mDrawingState.frameRate.categorySmoothSwitchOnly = smoothSwitchOnly;
Robert Carr6a160312021-05-17 12:08:20 -07001330 mDrawingState.modified = true;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001331
1332 updateTreeHasFrameRateVote();
1333
Steven Thomas3172e202020-01-06 19:25:30 -08001334 setTransactionFlags(eTransactionNeeded);
1335 return true;
1336}
1337
Rachel Lee58cc90d2023-09-05 18:50:20 -07001338bool Layer::setFrameRateSelectionStrategy(FrameRateSelectionStrategy strategy) {
1339 if (mDrawingState.frameRateSelectionStrategy == strategy) return false;
1340 mDrawingState.frameRateSelectionStrategy = strategy;
1341 mDrawingState.sequence++;
1342 mDrawingState.modified = true;
Rachel Leed7479502023-09-25 17:02:35 -07001343
1344 updateTreeHasFrameRateVote();
Rachel Lee58cc90d2023-09-05 18:50:20 -07001345 setTransactionFlags(eTransactionNeeded);
1346 return true;
1347}
1348
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001349void Layer::setFrameTimelineVsyncForBufferTransaction(const FrameTimelineInfo& info,
1350 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001351 mDrawingState.postTime = postTime;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001352
1353 // Check if one of the bufferlessSurfaceFramesTX contains the same vsyncId. This can happen if
1354 // there are two transactions with the same token, the first one without a buffer and the
1355 // second one with a buffer. We promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
1356 // in that case.
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 // Promote the bufferlessSurfaceFrame to a bufferSurfaceFrameTX
Robert Carr6a160312021-05-17 12:08:20 -07001360 mDrawingState.bufferSurfaceFrameTX = it->second;
1361 mDrawingState.bufferlessSurfaceFramesTX.erase(it);
1362 mDrawingState.bufferSurfaceFrameTX->promoteToBuffer();
1363 mDrawingState.bufferSurfaceFrameTX->setActualQueueTime(postTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001364 } else {
Robert Carr6a160312021-05-17 12:08:20 -07001365 mDrawingState.bufferSurfaceFrameTX =
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001366 createSurfaceFrameForBuffer(info, postTime, mTransactionName);
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::setFrameTimelineVsyncForBufferlessTransaction(const FrameTimelineInfo& info,
1373 nsecs_t postTime) {
Robert Carr6a160312021-05-17 12:08:20 -07001374 mDrawingState.frameTimelineInfo = info;
1375 mDrawingState.postTime = postTime;
1376 mDrawingState.modified = true;
Ady Abraham22c7b5c2020-09-22 19:33:40 -07001377 setTransactionFlags(eTransactionNeeded);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001378
Robert Carr6a160312021-05-17 12:08:20 -07001379 if (const auto& bufferSurfaceFrameTX = mDrawingState.bufferSurfaceFrameTX;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001380 bufferSurfaceFrameTX != nullptr) {
1381 if (bufferSurfaceFrameTX->getToken() == info.vsyncId) {
1382 // BufferSurfaceFrame takes precedence over BufferlessSurfaceFrame. If the same token is
1383 // being used for BufferSurfaceFrame, don't create a new one.
1384 return;
1385 }
1386 }
1387 // For Transactions without a buffer, we create only one SurfaceFrame per vsyncId. If multiple
1388 // transactions use the same vsyncId, we just treat them as one SurfaceFrame (unless they are
1389 // targeting different vsyncs).
Robert Carr6a160312021-05-17 12:08:20 -07001390 auto it = mDrawingState.bufferlessSurfaceFramesTX.find(info.vsyncId);
1391 if (it == mDrawingState.bufferlessSurfaceFramesTX.end()) {
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001392 auto surfaceFrame = createSurfaceFrameForTransaction(info, postTime);
Robert Carr6a160312021-05-17 12:08:20 -07001393 mDrawingState.bufferlessSurfaceFramesTX[info.vsyncId] = surfaceFrame;
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001394 } else {
1395 if (it->second->getPresentState() == PresentState::Presented) {
1396 // If the SurfaceFrame was already presented, its safe to overwrite it since it must
1397 // have been from previous vsync.
1398 it->second = createSurfaceFrameForTransaction(info, postTime);
1399 }
1400 }
Ady Abraham5a3e3562023-06-07 10:32:08 -07001401
1402 setFrameTimelineVsyncForSkippedFrames(info, postTime, mTransactionName);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001403}
1404
1405void Layer::addSurfaceFrameDroppedForBuffer(
Ady Abraham5a3e3562023-06-07 10:32:08 -07001406 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t dropTime) {
1407 surfaceFrame->setDropTime(dropTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001408 surfaceFrame->setPresentState(PresentState::Dropped);
1409 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
1410}
1411
1412void Layer::addSurfaceFramePresentedForBuffer(
1413 std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame, nsecs_t acquireFenceTime,
1414 nsecs_t currentLatchTime) {
1415 surfaceFrame->setAcquireFenceTime(acquireFenceTime);
1416 surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
1417 mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
Vishnu Naira156f482023-02-22 00:23:38 +00001418 updateLastLatchTime(currentLatchTime);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001419}
1420
1421std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForTransaction(
1422 const FrameTimelineInfo& info, nsecs_t postTime) {
1423 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001424 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
1425 getSequence(), mName,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001426 mTransactionName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001427 /*isBuffer*/ false, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001428 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001429 // For Transactions, the post time is considered to be both queue and acquire fence time.
1430 surfaceFrame->setActualQueueTime(postTime);
1431 surfaceFrame->setAcquireFenceTime(postTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001432 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1433 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001434 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001435 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001436 onSurfaceFrameCreated(surfaceFrame);
1437 return surfaceFrame;
1438}
1439
1440std::shared_ptr<frametimeline::SurfaceFrame> Layer::createSurfaceFrameForBuffer(
1441 const FrameTimelineInfo& info, nsecs_t queueTime, std::string debugName) {
1442 auto surfaceFrame =
Alec Mouriadebf5c2021-01-05 12:57:36 -08001443 mFlinger->mFrameTimeline->createSurfaceFrameForToken(info, mOwnerPid, mOwnerUid,
Adithya Srinivasan785addd2021-03-09 00:38:00 +00001444 getSequence(), mName, debugName,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +00001445 /*isBuffer*/ true, getGameMode());
Rachel Leeed511ef2021-10-11 15:09:51 -07001446 surfaceFrame->setActualStartTime(info.startTimeNanos);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001447 // For buffers, acquire fence time will set during latch.
1448 surfaceFrame->setActualQueueTime(queueTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001449 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1450 if (fps) {
Alec Mouri819f6302021-02-12 15:37:21 -08001451 surfaceFrame->setRenderRate(*fps);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001452 }
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +00001453 onSurfaceFrameCreated(surfaceFrame);
1454 return surfaceFrame;
Ady Abraham74e17562020-08-24 18:18:19 -07001455}
1456
Ady Abraham5a3e3562023-06-07 10:32:08 -07001457void Layer::setFrameTimelineVsyncForSkippedFrames(const FrameTimelineInfo& info, nsecs_t postTime,
1458 std::string debugName) {
1459 if (info.skippedFrameVsyncId == FrameTimelineInfo::INVALID_VSYNC_ID) {
1460 return;
1461 }
1462
1463 FrameTimelineInfo skippedFrameTimelineInfo = info;
1464 skippedFrameTimelineInfo.vsyncId = info.skippedFrameVsyncId;
1465
1466 auto surfaceFrame =
1467 mFlinger->mFrameTimeline->createSurfaceFrameForToken(skippedFrameTimelineInfo,
1468 mOwnerPid, mOwnerUid,
1469 getSequence(), mName, debugName,
1470 /*isBuffer*/ false, getGameMode());
1471 surfaceFrame->setActualStartTime(skippedFrameTimelineInfo.skippedFrameStartTimeNanos);
1472 // For Transactions, the post time is considered to be both queue and acquire fence time.
1473 surfaceFrame->setActualQueueTime(postTime);
1474 surfaceFrame->setAcquireFenceTime(postTime);
1475 const auto fps = mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
1476 if (fps) {
1477 surfaceFrame->setRenderRate(*fps);
1478 }
1479 onSurfaceFrameCreated(surfaceFrame);
1480 addSurfaceFrameDroppedForBuffer(surfaceFrame, postTime);
1481}
1482
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001483bool Layer::setFrameRateForLayerTreeLegacy(FrameRate frameRate, nsecs_t now) {
Ady Abrahama850c182021-08-04 13:04:37 -07001484 if (mDrawingState.frameRateForLayerTree == frameRate) {
1485 return false;
Ady Abraham60e42ea2020-03-09 19:17:31 -07001486 }
1487
Ady Abrahama850c182021-08-04 13:04:37 -07001488 mDrawingState.frameRateForLayerTree = frameRate;
Ady Abrahamf467f892020-07-31 16:01:53 -07001489
Ady Abrahama850c182021-08-04 13:04:37 -07001490 // TODO(b/195668952): we probably don't need to dirty visible regions here
1491 // or even store frameRateForLayerTree in mDrawingState
1492 mDrawingState.sequence++;
1493 mDrawingState.modified = true;
1494 setTransactionFlags(eTransactionNeeded);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001495
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001496 mFlinger->mScheduler
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001497 ->recordLayerHistory(sequence, getLayerProps(), now, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001498 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
1499 return true;
1500}
Ady Abrahama850c182021-08-04 13:04:37 -07001501
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001502bool Layer::setFrameRateForLayerTree(FrameRate frameRate, const scheduler::LayerProps& layerProps,
1503 nsecs_t now) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001504 if (mDrawingState.frameRateForLayerTree == frameRate) {
1505 return false;
1506 }
1507
1508 mDrawingState.frameRateForLayerTree = frameRate;
1509 mFlinger->mScheduler
Vishnu Nair47b7bb42023-09-29 16:27:33 -07001510 ->recordLayerHistory(sequence, layerProps, now, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00001511 scheduler::LayerHistory::LayerUpdateType::SetFrameRate);
Ady Abrahama850c182021-08-04 13:04:37 -07001512 return true;
Steven Thomas3172e202020-01-06 19:25:30 -08001513}
1514
Ady Abraham59fd8ff2021-04-15 20:13:30 -07001515Layer::FrameRate Layer::getFrameRateForLayerTree() const {
1516 return getDrawingState().frameRateForLayerTree;
1517}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001518
Robert Carr1f0a16a2016-10-24 16:27:39 -07001519bool Layer::isHiddenByPolicy() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001520 const State& s(mDrawingState);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001521 const auto& parent = mDrawingParent.promote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001522 if (parent != nullptr && parent->isHiddenByPolicy()) {
1523 return true;
1524 }
Robert Carr1c5481e2019-07-01 14:42:27 -07001525 if (usingRelativeZ(LayerVector::StateSet::Drawing)) {
1526 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
1527 if (zOrderRelativeOf != nullptr) {
1528 if (zOrderRelativeOf->isHiddenByPolicy()) {
1529 return true;
1530 }
1531 }
1532 }
Garfield Tan2c1782c2022-02-16 15:25:05 -08001533 if (CC_UNLIKELY(!isTransformValid())) {
1534 ALOGW("Hide layer %s because it has invalid transformation.", getDebugName());
1535 return true;
1536 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001537 return s.flags & layer_state_t::eLayerHidden;
1538}
1539
David Sodman41fdfc92017-11-06 16:09:56 -08001540uint32_t Layer::getEffectiveUsage(uint32_t usage) const {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001541 // TODO: should we do something special if mSecure is set?
1542 if (mProtectedByApp) {
1543 // need a hardware-protected path to external video sink
1544 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07001545 }
Riley Andrews03414a12014-07-01 14:22:59 -07001546 if (mPotentialCursor) {
1547 usage |= GraphicBuffer::USAGE_CURSOR;
1548 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07001549 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001550 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001551}
1552
Vishnu Nair71fcf912022-10-18 09:14:20 -07001553void Layer::skipReportingTransformHint() {
1554 mSkipReportingTransformHint = true;
1555}
1556
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001557void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) {
1558 if (mFlinger->mDebugDisableTransformHint || transformHint & ui::Transform::ROT_INVALID) {
1559 transformHint = ui::Transform::ROT_0;
Mathias Agopiana4583642011-08-23 18:03:18 -07001560 }
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001561
Vishnu Nairb76d99a2023-03-19 18:22:31 -07001562 setTransformHintLegacy(transformHint);
Mathias Agopiana4583642011-08-23 18:03:18 -07001563}
1564
Mathias Agopian13127d82013-03-05 17:47:11 -08001565// ----------------------------------------------------------------------------
1566// debugging
1567// ----------------------------------------------------------------------------
1568
Marissa Wall61c58622018-07-18 10:12:20 -07001569// TODO(marissaw): add new layer state info to layer debugging
Huihong Luo05539a12022-02-23 10:29:40 -08001570gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001571 using namespace std::string_literals;
1572
Huihong Luo05539a12022-02-23 10:29:40 -08001573 gui::LayerDebugInfo info;
Alec Mourib416efd2018-09-06 21:01:59 +00001574 const State& ds = getDrawingState();
Kalle Raitaa099a242017-01-11 11:17:29 -08001575 info.mName = getName();
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001576 sp<Layer> parent = mDrawingParent.promote();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001577 info.mParentName = parent ? parent->getName() : "none"s;
chaviw8a01fa42019-08-19 12:39:31 -07001578 info.mType = getType();
Lloyd Piquea2468662019-03-07 21:31:06 -08001579
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001580 info.mVisibleRegion = getVisibleRegion(display);
Kalle Raitaa099a242017-01-11 11:17:29 -08001581 info.mSurfaceDamageRegion = surfaceDamageRegion;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001582 info.mLayerStack = getLayerStack().id;
chaviw4e765532021-04-30 12:11:39 -05001583 info.mX = ds.transform.tx();
1584 info.mY = ds.transform.ty();
Kalle Raitaa099a242017-01-11 11:17:29 -08001585 info.mZ = ds.z;
chaviw25714502021-02-11 10:01:08 -08001586 info.mCrop = ds.crop;
chaviw13fdc492017-06-27 12:40:18 -07001587 info.mColor = ds.color;
Kalle Raitaa099a242017-01-11 11:17:29 -08001588 info.mFlags = ds.flags;
1589 info.mPixelFormat = getPixelFormat();
chaviw4244e032019-09-04 11:27:49 -07001590 info.mDataSpace = static_cast<android_dataspace>(getDataSpace());
chaviw4e765532021-04-30 12:11:39 -05001591 info.mMatrix[0][0] = ds.transform[0][0];
1592 info.mMatrix[0][1] = ds.transform[0][1];
1593 info.mMatrix[1][0] = ds.transform[1][0];
1594 info.mMatrix[1][1] = ds.transform[1][1];
Kalle Raitaa099a242017-01-11 11:17:29 -08001595 {
chaviwd62d3062019-09-04 14:48:02 -07001596 sp<const GraphicBuffer> buffer = getBuffer();
David Sodman5b4cffc2017-11-23 13:20:29 -08001597 if (buffer != 0) {
1598 info.mActiveBufferWidth = buffer->getWidth();
1599 info.mActiveBufferHeight = buffer->getHeight();
1600 info.mActiveBufferStride = buffer->getStride();
1601 info.mActiveBufferFormat = buffer->format;
Kalle Raitaa099a242017-01-11 11:17:29 -08001602 } else {
1603 info.mActiveBufferWidth = 0;
1604 info.mActiveBufferHeight = 0;
1605 info.mActiveBufferStride = 0;
1606 info.mActiveBufferFormat = 0;
1607 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001608 }
Kalle Raitaa099a242017-01-11 11:17:29 -08001609 info.mNumQueuedFrames = getQueuedFrameCount();
Kalle Raitaa099a242017-01-11 11:17:29 -08001610 info.mIsOpaque = isOpaque(ds);
1611 info.mContentDirty = contentDirty;
John Reckc00c6692021-02-16 11:37:33 -05001612 info.mStretchEffect = getStretchEffect();
Kalle Raitaa099a242017-01-11 11:17:29 -08001613 return info;
Mathias Agopian13127d82013-03-05 17:47:11 -08001614}
Chia-I Wu83ce7c12017-10-19 15:18:55 -07001615
Yiwei Zhang5434a782018-12-05 18:06:32 -08001616void Layer::miniDumpHeader(std::string& result) {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001617 result.append(kDumpTableRowLength, '-');
1618 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001619 result.append(" Layer name\n");
1620 result.append(" Z | ");
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001621 result.append(" Window Type | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001622 result.append(" Comp Type | ");
Yichi Chen6ca35192018-05-29 12:20:43 +08001623 result.append(" Transform | ");
Dan Stozae22aec72016-08-01 13:20:59 -07001624 result.append(" Disp Frame (LTRB) | ");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001625 result.append(" Source Crop (LTRB) | ");
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001626 result.append(" Frame Rate (Explicit) (Seamlessness) [Focused]\n");
1627 result.append(kDumpTableRowLength, '-');
1628 result.append("\n");
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001629}
1630
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001631void Layer::miniDumpLegacy(std::string& result, const DisplayDevice& display) const {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001632 const auto outputLayer = findOutputLayerForDisplay(&display);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001633 if (!outputLayer) {
Dan Stozae22aec72016-08-01 13:20:59 -07001634 return;
1635 }
1636
Yiwei Zhang5434a782018-12-05 18:06:32 -08001637 std::string name;
Dan Stozae22aec72016-08-01 13:20:59 -07001638 if (mName.length() > 77) {
1639 std::string shortened;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001640 shortened.append(mName, 0, 36);
Dan Stozae22aec72016-08-01 13:20:59 -07001641 shortened.append("[...]");
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001642 shortened.append(mName, mName.length() - 36);
1643 name = std::move(shortened);
Dan Stozae22aec72016-08-01 13:20:59 -07001644 } else {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001645 name = mName;
Dan Stozae22aec72016-08-01 13:20:59 -07001646 }
1647
Yiwei Zhang5434a782018-12-05 18:06:32 -08001648 StringAppendF(&result, " %s\n", name.c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07001649
Alec Mourib416efd2018-09-06 21:01:59 +00001650 const State& layerState(getDrawingState());
Lloyd Piquede196652020-01-22 17:29:58 -08001651 const auto& outputLayerState = outputLayer->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001652
Chia-I Wu1e043612018-03-01 09:45:09 -08001653 if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001654 StringAppendF(&result, " rel %6d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001655 } else {
Yiwei Zhang5434a782018-12-05 18:06:32 -08001656 StringAppendF(&result, " %10d | ", layerState.z);
Chia-I Wu1e043612018-03-01 09:45:09 -08001657 }
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07001658 StringAppendF(&result, " %10d | ", mWindowType);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07001659 StringAppendF(&result, "%10s | ", toString(getCompositionType(display)).c_str());
Lloyd Piquede196652020-01-22 17:29:58 -08001660 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1661 const Rect& frame = outputLayerState.displayFrame;
Yiwei Zhang5434a782018-12-05 18:06:32 -08001662 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
Lloyd Piquede196652020-01-22 17:29:58 -08001663 const FloatRect& crop = outputLayerState.sourceCrop;
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001664 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
Yiwei Zhang5434a782018-12-05 18:06:32 -08001665 crop.bottom);
Ady Abrahamf467f892020-07-31 16:01:53 -07001666 const auto frameRate = getFrameRateForLayerTree();
Rachel Leece6e0042023-06-27 11:22:54 -07001667 if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
1668 StringAppendF(&result, "%s %15s %17s", to_string(frameRate.vote.rate).c_str(),
1669 ftl::enum_string(frameRate.vote.type).c_str(),
1670 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001671 } else {
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001672 result.append(41, ' ');
Ady Abrahambe23e6a2020-05-04 14:51:16 -07001673 }
Dan Stozae22aec72016-08-01 13:20:59 -07001674
Ady Abrahamaae5ed52020-06-26 09:32:43 -07001675 const auto focused = isLayerFocusedBasedOnPriority(getFrameRateSelectionPriority());
1676 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1677
Marin Shalamanov1876e2e2020-12-04 13:23:59 +01001678 result.append(kDumpTableRowLength, '-');
1679 result.append("\n");
Dan Stozae22aec72016-08-01 13:20:59 -07001680}
Dan Stozae22aec72016-08-01 13:20:59 -07001681
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001682void Layer::miniDump(std::string& result, const frontend::LayerSnapshot& snapshot,
1683 const DisplayDevice& display) const {
1684 const auto outputLayer = findOutputLayerForDisplay(&display, snapshot.path);
1685 if (!outputLayer) {
1686 return;
1687 }
1688
1689 StringAppendF(&result, " %s\n", snapshot.debugName.c_str());
1690 StringAppendF(&result, " %10zu | ", snapshot.globalZ);
1691 StringAppendF(&result, " %10d | ",
1692 snapshot.layerMetadata.getInt32(gui::METADATA_WINDOW_TYPE, 0));
1693 StringAppendF(&result, "%10s | ", toString(getCompositionType(outputLayer)).c_str());
1694 const auto& outputLayerState = outputLayer->getState();
1695 StringAppendF(&result, "%10s | ", toString(outputLayerState.bufferTransform).c_str());
1696 const Rect& frame = outputLayerState.displayFrame;
1697 StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
1698 const FloatRect& crop = outputLayerState.sourceCrop;
1699 StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f | ", crop.left, crop.top, crop.right,
1700 crop.bottom);
1701 const auto frameRate = snapshot.frameRate;
Ady Abraham77d406d2023-11-22 15:00:23 -08001702 std::string frameRateStr;
1703 if (frameRate.vote.rate.isValid()) {
1704 StringAppendF(&frameRateStr, "%.2f", frameRate.vote.rate.getValue());
1705 }
Rachel Leece6e0042023-06-27 11:22:54 -07001706 if (frameRate.vote.rate.isValid() || frameRate.vote.type != FrameRateCompatibility::Default) {
Ady Abraham77d406d2023-11-22 15:00:23 -08001707 StringAppendF(&result, "%6s %15s %17s", frameRateStr.c_str(),
Rachel Leece6e0042023-06-27 11:22:54 -07001708 ftl::enum_string(frameRate.vote.type).c_str(),
1709 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Ady Abraham77d406d2023-11-22 15:00:23 -08001710 } else if (frameRate.category != FrameRateCategory::Default) {
1711 StringAppendF(&result, "%6s %15s %17s", frameRateStr.c_str(),
1712 (std::string("Cat::") + ftl::enum_string(frameRate.category)).c_str(),
1713 ftl::enum_string(frameRate.vote.seamlessness).c_str());
Vishnu Nair3cc15a42023-06-30 06:20:22 +00001714 } else {
1715 result.append(41, ' ');
1716 }
1717
1718 const auto focused = isLayerFocusedBasedOnPriority(snapshot.frameRateSelectionPriority);
1719 StringAppendF(&result, " [%s]\n", focused ? "*" : " ");
1720
1721 result.append(kDumpTableRowLength, '-');
1722 result.append("\n");
1723}
1724
Yiwei Zhang5434a782018-12-05 18:06:32 -08001725void Layer::dumpFrameStats(std::string& result) const {
Svetoslavd85084b2014-03-20 10:28:31 -07001726 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08001727}
1728
Svetoslavd85084b2014-03-20 10:28:31 -07001729void Layer::clearFrameStats() {
1730 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08001731}
1732
Jamie Gennis6547ff42013-07-16 20:12:42 -07001733void Layer::logFrameStats() {
1734 mFrameTracker.logAndResetStats(mName);
1735}
1736
Svetoslavd85084b2014-03-20 10:28:31 -07001737void Layer::getFrameStats(FrameStats* outStats) const {
1738 mFrameTracker.getStats(outStats);
1739}
1740
Vishnu Nair76554eb2022-12-09 03:38:36 +00001741void Layer::dumpOffscreenDebugInfo(std::string& result) const {
1742 std::string hasBuffer = hasBufferOrSidebandStream() ? " (contains buffer)" : "";
Vishnu Nair3be61902023-04-26 19:47:29 -07001743 StringAppendF(&result, "Layer %s%s pid:%d uid:%d%s\n", getName().c_str(), hasBuffer.c_str(),
1744 mOwnerPid, mOwnerUid, isHandleAlive() ? " handleAlive" : "");
Vishnu Nair0f085c62019-08-30 08:49:12 -07001745}
1746
Brian Anderson5ea5e592016-12-01 16:54:33 -08001747void Layer::onDisconnect() {
Yiwei Zhang1a88c402019-11-18 10:43:58 -08001748 const int32_t layerId = getSequence();
1749 mFlinger->mTimeStats->onDestroy(layerId);
1750 mFlinger->mFrameTracer->onDestroy(layerId);
Brian Anderson5ea5e592016-12-01 16:54:33 -08001751}
1752
Vishnu Nair787aa782023-03-17 13:46:46 -07001753size_t Layer::getDescendantCount() const {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001754 size_t count = 0;
Vishnu Nair787aa782023-03-17 13:46:46 -07001755 for (const sp<Layer>& child : mDrawingChildren) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07001756 count += 1 + child->getChildrenCount();
1757 }
1758 return count;
1759}
1760
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001761void Layer::setGameModeForTree(GameMode gameMode) {
1762 const auto& currentState = getDrawingState();
Huihong Luod3d8f8e2022-03-08 14:48:46 -08001763 if (currentState.metadata.has(gui::METADATA_GAME_MODE)) {
1764 gameMode =
1765 static_cast<GameMode>(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001766 }
1767 setGameMode(gameMode);
1768 for (const sp<Layer>& child : mCurrentChildren) {
1769 child->setGameModeForTree(gameMode);
1770 }
1771}
1772
Robert Carr1f0a16a2016-10-24 16:27:39 -07001773void Layer::addChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001774 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001775 setTransactionFlags(eTransactionNeeded);
Robert Carr1323c952019-01-28 18:13:27 -08001776
Robert Carr1f0a16a2016-10-24 16:27:39 -07001777 mCurrentChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07001778 layer->setParent(sp<Layer>::fromExisting(this));
Adithya Srinivasanac977e62021-05-21 22:50:56 +00001779 layer->setGameModeForTree(mGameMode);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001780 updateTreeHasFrameRateVote();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001781}
1782
1783ssize_t Layer::removeChild(const sp<Layer>& layer) {
Robert Carre450fb52021-06-11 13:21:09 -07001784 mFlinger->mSomeChildrenChanged = true;
Robert Carr7f2ed8b2019-02-07 14:45:11 -08001785 setTransactionFlags(eTransactionNeeded);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001786
Robert Carr1323c952019-01-28 18:13:27 -08001787 layer->setParent(nullptr);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001788 const auto removeResult = mCurrentChildren.remove(layer);
1789
1790 updateTreeHasFrameRateVote();
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07001791 layer->setGameModeForTree(GameMode::Unsupported);
Ady Abraham60e42ea2020-03-09 19:17:31 -07001792 layer->updateTreeHasFrameRateVote();
1793
1794 return removeResult;
1795}
1796
Robert Carr15eae092018-03-23 13:43:53 -07001797void Layer::setChildrenDrawingParent(const sp<Layer>& newParent) {
Robert Carr578038f2018-03-09 12:25:24 -08001798 for (const sp<Layer>& child : mDrawingChildren) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001799 child->mDrawingParent = newParent;
xinying1f4200e62022-04-26 14:41:30 +08001800 const float parentShadowRadius =
1801 newParent->canDrawShadows() ? 0.f : newParent->mEffectiveShadowRadius;
Vishnu Nair6bdec7d2021-05-10 15:01:13 -07001802 child->computeBounds(newParent->mBounds, newParent->mEffectiveTransform,
xinying1f4200e62022-04-26 14:41:30 +08001803 parentShadowRadius);
Robert Carr578038f2018-03-09 12:25:24 -08001804 }
1805}
1806
chaviwf1961f72017-09-18 16:41:07 -07001807bool Layer::reparent(const sp<IBinder>& newParentHandle) {
Robert Carr54cf5b12019-01-25 14:02:28 -08001808 sp<Layer> newParent;
1809 if (newParentHandle != nullptr) {
Vishnu Nair07e2a482022-10-18 19:18:16 +00001810 newParent = LayerHandle::getLayer(newParentHandle);
Robert Carr54cf5b12019-01-25 14:02:28 -08001811 if (newParent == nullptr) {
1812 ALOGE("Unable to promote Layer handle");
1813 return false;
1814 }
1815 if (newParent == this) {
1816 ALOGE("Invalid attempt to reparent Layer (%s) to itself", getName().c_str());
1817 return false;
1818 }
1819 }
1820
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001821 sp<Layer> parent = getParent();
chaviwf1961f72017-09-18 16:41:07 -07001822 if (parent != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001823 parent->removeChild(sp<Layer>::fromExisting(this));
chaviw06178942017-07-27 10:25:59 -07001824 }
1825
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001826 if (newParentHandle != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07001827 newParent->addChild(sp<Layer>::fromExisting(this));
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001828 if (!newParent->isRemovedFromCurrentState()) {
1829 addToCurrentState();
1830 } else {
1831 onRemovedFromCurrentState();
1832 }
Robert Carr6fb1a7e2018-12-11 12:07:25 -08001833 } else {
1834 onRemovedFromCurrentState();
chaviw61626f22018-11-15 16:26:27 -08001835 }
1836
chaviw06178942017-07-27 10:25:59 -07001837 return true;
1838}
1839
Peiyong Lind3788632018-09-18 16:01:31 -07001840bool Layer::setColorTransform(const mat4& matrix) {
Peiyong Lin747321c2018-10-01 10:03:11 -07001841 static const mat4 identityMatrix = mat4();
1842
Robert Carr6a160312021-05-17 12:08:20 -07001843 if (mDrawingState.colorTransform == matrix) {
Peiyong Lind3788632018-09-18 16:01:31 -07001844 return false;
1845 }
Robert Carr6a160312021-05-17 12:08:20 -07001846 ++mDrawingState.sequence;
1847 mDrawingState.colorTransform = matrix;
1848 mDrawingState.hasColorTransform = matrix != identityMatrix;
1849 mDrawingState.modified = true;
Peiyong Lind3788632018-09-18 16:01:31 -07001850 setTransactionFlags(eTransactionNeeded);
1851 return true;
1852}
1853
chaviwf66724d2018-11-28 16:35:21 -08001854mat4 Layer::getColorTransform() const {
1855 mat4 colorTransform = mat4(getDrawingState().colorTransform);
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001856 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001857 colorTransform = parent->getColorTransform() * colorTransform;
1858 }
1859 return colorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001860}
1861
1862bool Layer::hasColorTransform() const {
chaviwf66724d2018-11-28 16:35:21 -08001863 bool hasColorTransform = getDrawingState().hasColorTransform;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001864 if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
chaviwf66724d2018-11-28 16:35:21 -08001865 hasColorTransform = hasColorTransform || parent->hasColorTransform();
1866 }
1867 return hasColorTransform;
Peiyong Lind3788632018-09-18 16:01:31 -07001868}
1869
Chia-I Wu11481472018-05-04 10:43:19 -07001870bool Layer::isLegacyDataSpace() const {
1871 // return true when no higher bits are set
chaviw4244e032019-09-04 11:27:49 -07001872 return !(getDataSpace() &
1873 (ui::Dataspace::STANDARD_MASK | ui::Dataspace::TRANSFER_MASK |
1874 ui::Dataspace::RANGE_MASK));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001875}
1876
Robert Carr1f0a16a2016-10-24 16:27:39 -07001877void Layer::setParent(const sp<Layer>& layer) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00001878 mCurrentParent = layer;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001879}
1880
Robert Carr6a160312021-05-17 12:08:20 -07001881int32_t Layer::getZ(LayerVector::StateSet) const {
1882 return mDrawingState.z;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001883}
1884
Robert Carr1c5481e2019-07-01 14:42:27 -07001885bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) const {
Robert Carr29abff82017-12-04 13:51:20 -08001886 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
Robert Carr6a160312021-05-17 12:08:20 -07001887 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviwe5ac40f2019-09-24 16:36:55 -07001888 return state.isRelativeOf;
Robert Carr29abff82017-12-04 13:51:20 -08001889}
1890
David Sodman41fdfc92017-11-06 16:09:56 -08001891__attribute__((no_sanitize("unsigned-integer-overflow"))) LayerVector Layer::makeTraversalList(
Robert Carr29abff82017-12-04 13:51:20 -08001892 LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers) {
Dan Stoza412903f2017-04-27 13:42:17 -07001893 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
1894 "makeTraversalList received invalid stateSet");
1895 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
1896 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07001897 const State& state = useDrawing ? mDrawingState : mDrawingState;
Dan Stoza412903f2017-04-27 13:42:17 -07001898
Robert Carr29abff82017-12-04 13:51:20 -08001899 if (state.zOrderRelatives.size() == 0) {
1900 *outSkipRelativeZUsers = true;
1901 return children;
1902 }
1903
chaviwfd462612018-05-31 16:11:27 -07001904 LayerVector traverse(stateSet);
Dan Stoza412903f2017-04-27 13:42:17 -07001905 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
Robert Carrdb66e622017-04-10 16:55:57 -07001906 sp<Layer> strongRelative = weakRelative.promote();
1907 if (strongRelative != nullptr) {
1908 traverse.add(strongRelative);
Robert Carrdb66e622017-04-10 16:55:57 -07001909 }
1910 }
1911
Dan Stoza412903f2017-04-27 13:42:17 -07001912 for (const sp<Layer>& child : children) {
chaviwe5ac40f2019-09-24 16:36:55 -07001913 if (child->usingRelativeZ(stateSet)) {
Robert Carr503c7042017-09-27 15:06:08 -07001914 continue;
1915 }
Robert Carrdb66e622017-04-10 16:55:57 -07001916 traverse.add(child);
1917 }
1918
1919 return traverse;
1920}
1921
Robert Carr1f0a16a2016-10-24 16:27:39 -07001922/**
Robert Carrdb66e622017-04-10 16:55:57 -07001923 * Negatively signed relatives are before 'this' in Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001924 */
Dan Stoza412903f2017-04-27 13:42:17 -07001925void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001926 // In the case we have other layers who are using a relative Z to us, makeTraversalList will
1927 // produce a new list for traversing, including our relatives, and not including our children
1928 // who are relatives of another surface. In the case that there are no relative Z,
1929 // makeTraversalList returns our children directly to avoid significant overhead.
1930 // However in this case we need to take the responsibility for filtering children which
1931 // are relatives of another surface here.
1932 bool skipRelativeZUsers = false;
1933 const LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001934
Robert Carr1f0a16a2016-10-24 16:27:39 -07001935 size_t i = 0;
Robert Carrdb66e622017-04-10 16:55:57 -07001936 for (; i < list.size(); i++) {
1937 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001938 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1939 continue;
1940 }
1941
chaviw301b1d82019-11-06 13:15:09 -08001942 if (relative->getZ(stateSet) >= 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001943 break;
Robert Carrdb66e622017-04-10 16:55:57 -07001944 }
Dan Stoza412903f2017-04-27 13:42:17 -07001945 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001946 }
Robert Carr29abff82017-12-04 13:51:20 -08001947
Dan Stoza412903f2017-04-27 13:42:17 -07001948 visitor(this);
Robert Carrdb66e622017-04-10 16:55:57 -07001949 for (; i < list.size(); i++) {
1950 const auto& relative = list[i];
Lloyd Pique0449b0f2018-12-20 16:23:45 -08001951
Robert Carr29abff82017-12-04 13:51:20 -08001952 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1953 continue;
1954 }
Dan Stoza412903f2017-04-27 13:42:17 -07001955 relative->traverseInZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001956 }
1957}
1958
1959/**
Robert Carrdb66e622017-04-10 16:55:57 -07001960 * Positively signed relatives are before 'this' in reverse Z-order.
Robert Carr1f0a16a2016-10-24 16:27:39 -07001961 */
Dan Stoza412903f2017-04-27 13:42:17 -07001962void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
1963 const LayerVector::Visitor& visitor) {
Robert Carr29abff82017-12-04 13:51:20 -08001964 // See traverseInZOrder for documentation.
1965 bool skipRelativeZUsers = false;
1966 LayerVector list = makeTraversalList(stateSet, &skipRelativeZUsers);
Robert Carrdb66e622017-04-10 16:55:57 -07001967
Robert Carr1f0a16a2016-10-24 16:27:39 -07001968 int32_t i = 0;
Joel Galensonbf324992017-11-06 11:04:12 -08001969 for (i = int32_t(list.size()) - 1; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001970 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001971
1972 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1973 continue;
1974 }
1975
chaviw301b1d82019-11-06 13:15:09 -08001976 if (relative->getZ(stateSet) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001977 break;
1978 }
Dan Stoza412903f2017-04-27 13:42:17 -07001979 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001980 }
Dan Stoza412903f2017-04-27 13:42:17 -07001981 visitor(this);
David Sodman41fdfc92017-11-06 16:09:56 -08001982 for (; i >= 0; i--) {
Robert Carrdb66e622017-04-10 16:55:57 -07001983 const auto& relative = list[i];
Robert Carr29abff82017-12-04 13:51:20 -08001984
1985 if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
1986 continue;
1987 }
1988
Dan Stoza412903f2017-04-27 13:42:17 -07001989 relative->traverseInReverseZOrder(stateSet, visitor);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001990 }
1991}
1992
Edgar Arriaga844fa672020-01-16 14:21:42 -08001993void Layer::traverse(LayerVector::StateSet state, const LayerVector::Visitor& visitor) {
1994 visitor(this);
1995 const LayerVector& children =
Robert Carr6a160312021-05-17 12:08:20 -07001996 state == LayerVector::StateSet::Drawing ? mDrawingChildren : mCurrentChildren;
Edgar Arriaga844fa672020-01-16 14:21:42 -08001997 for (const sp<Layer>& child : children) {
1998 child->traverse(state, visitor);
1999 }
2000}
2001
Vishnu Nair787aa782023-03-17 13:46:46 -07002002void Layer::traverseChildren(const LayerVector::Visitor& visitor) {
2003 for (const sp<Layer>& child : mDrawingChildren) {
2004 visitor(child.get());
2005 }
2006}
2007
chaviw4b129c22018-04-09 16:19:43 -07002008LayerVector Layer::makeChildrenTraversalList(LayerVector::StateSet stateSet,
2009 const std::vector<Layer*>& layersInTree) {
2010 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2011 "makeTraversalList received invalid stateSet");
chaviwa76b2712017-09-20 12:02:26 -07002012 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2013 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002014 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07002015
chaviwfd462612018-05-31 16:11:27 -07002016 LayerVector traverse(stateSet);
chaviw4b129c22018-04-09 16:19:43 -07002017 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2018 sp<Layer> strongRelative = weakRelative.promote();
2019 // Only add relative layers that are also descendents of the top most parent of the tree.
2020 // If a relative layer is not a descendent, then it should be ignored.
2021 if (std::binary_search(layersInTree.begin(), layersInTree.end(), strongRelative.get())) {
2022 traverse.add(strongRelative);
2023 }
2024 }
2025
2026 for (const sp<Layer>& child : children) {
Robert Carr6a160312021-05-17 12:08:20 -07002027 const State& childState = useDrawing ? child->mDrawingState : child->mDrawingState;
chaviw4b129c22018-04-09 16:19:43 -07002028 // If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
2029 // descendent of the top most parent of the tree. If it's not a descendent, then just add
2030 // the child here since it won't be added later as a relative.
2031 if (std::binary_search(layersInTree.begin(), layersInTree.end(),
2032 childState.zOrderRelativeOf.promote().get())) {
2033 continue;
2034 }
2035 traverse.add(child);
2036 }
2037
2038 return traverse;
2039}
2040
2041void Layer::traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree,
2042 LayerVector::StateSet stateSet,
2043 const LayerVector::Visitor& visitor) {
2044 const LayerVector list = makeChildrenTraversalList(stateSet, layersInTree);
chaviwa76b2712017-09-20 12:02:26 -07002045
2046 size_t i = 0;
chaviw4b129c22018-04-09 16:19:43 -07002047 for (; i < list.size(); i++) {
2048 const auto& relative = list[i];
chaviw301b1d82019-11-06 13:15:09 -08002049 if (relative->getZ(stateSet) >= 0) {
chaviwa76b2712017-09-20 12:02:26 -07002050 break;
2051 }
chaviw4b129c22018-04-09 16:19:43 -07002052 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002053 }
chaviw4b129c22018-04-09 16:19:43 -07002054
chaviwa76b2712017-09-20 12:02:26 -07002055 visitor(this);
chaviw4b129c22018-04-09 16:19:43 -07002056 for (; i < list.size(); i++) {
2057 const auto& relative = list[i];
2058 relative->traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
chaviwa76b2712017-09-20 12:02:26 -07002059 }
2060}
2061
chaviw4b129c22018-04-09 16:19:43 -07002062std::vector<Layer*> Layer::getLayersInTree(LayerVector::StateSet stateSet) {
2063 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2064 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2065
2066 std::vector<Layer*> layersInTree = {this};
2067 for (size_t i = 0; i < children.size(); i++) {
2068 const auto& child = children[i];
2069 std::vector<Layer*> childLayers = child->getLayersInTree(stateSet);
2070 layersInTree.insert(layersInTree.end(), childLayers.cbegin(), childLayers.cend());
2071 }
2072
2073 return layersInTree;
2074}
2075
2076void Layer::traverseChildrenInZOrder(LayerVector::StateSet stateSet,
2077 const LayerVector::Visitor& visitor) {
2078 std::vector<Layer*> layersInTree = getLayersInTree(stateSet);
2079 std::sort(layersInTree.begin(), layersInTree.end());
2080 traverseChildrenInZOrderInner(layersInTree, stateSet, visitor);
2081}
2082
Peiyong Linefefaac2018-08-17 12:27:51 -07002083ui::Transform Layer::getTransform() const {
Vishnu Nairf0c28512019-02-08 12:40:28 -08002084 return mEffectiveTransform;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002085}
2086
Garfield Tan2c1782c2022-02-16 15:25:05 -08002087bool Layer::isTransformValid() const {
2088 float transformDet = getTransform().det();
2089 return transformDet != 0 && !isinf(transformDet) && !isnan(transformDet);
2090}
2091
chaviw13fdc492017-06-27 12:40:18 -07002092half Layer::getAlpha() const {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002093 const auto& p = mDrawingParent.promote();
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002094
chaviw13fdc492017-06-27 12:40:18 -07002095 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2096 return parentAlpha * getDrawingState().color.a;
Robert Carr6452f122017-03-21 10:41:29 -07002097}
Robert Carr6452f122017-03-21 10:41:29 -07002098
Vishnu Nair6213bd92020-05-08 17:42:25 -07002099ui::Transform::RotationFlags Layer::getFixedTransformHint() const {
Robert Carr6a160312021-05-17 12:08:20 -07002100 ui::Transform::RotationFlags fixedTransformHint = mDrawingState.fixedTransformHint;
Vishnu Nair6213bd92020-05-08 17:42:25 -07002101 if (fixedTransformHint != ui::Transform::ROT_INVALID) {
2102 return fixedTransformHint;
2103 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002104 const auto& p = mCurrentParent.promote();
Vishnu Nair6213bd92020-05-08 17:42:25 -07002105 if (!p) return fixedTransformHint;
2106 return p->getFixedTransformHint();
2107}
2108
chaviw13fdc492017-06-27 12:40:18 -07002109half4 Layer::getColor() const {
2110 const half4 color(getDrawingState().color);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002111 return half4(color.r, color.g, color.b, getAlpha());
Robert Carr6452f122017-03-21 10:41:29 -07002112}
Robert Carr6452f122017-03-21 10:41:29 -07002113
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002114int32_t Layer::getBackgroundBlurRadius() const {
Vishnu Nair29810f72022-07-01 16:38:41 +00002115 if (getDrawingState().backgroundBlurRadius == 0) {
2116 return 0;
2117 }
Galia Peychevada7de0e2020-12-03 17:24:35 +01002118
Vishnu Nair29810f72022-07-01 16:38:41 +00002119 const auto& p = mDrawingParent.promote();
Galia Peychevada7de0e2020-12-03 17:24:35 +01002120 half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
2121 return parentAlpha * getDrawingState().backgroundBlurRadius;
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08002122}
2123
Galia Peychevae0acf382021-04-12 21:22:34 +02002124const std::vector<BlurRegion> Layer::getBlurRegions() const {
2125 auto regionsCopy(getDrawingState().blurRegions);
Galia Peycheva3c286542021-06-17 15:21:28 +02002126 float layerAlpha = getAlpha();
Galia Peychevae0acf382021-04-12 21:22:34 +02002127 for (auto& region : regionsCopy) {
2128 region.alpha = region.alpha * layerAlpha;
2129 }
2130 return regionsCopy;
Lucas Dupinc3800b82020-10-02 16:24:48 -07002131}
2132
Vishnu Naire14c6b32022-08-06 04:20:15 +00002133RoundedCornerState Layer::getRoundedCornerState() const {
Leon Scroggins IIIc1dbfcb2022-03-21 16:48:10 -04002134 // Today's DPUs cannot do rounded corners. If RenderEngine cannot render
2135 // protected content, remove rounded corners from protected content so it
2136 // can be rendered by the DPU.
2137 if (isProtected() && !mFlinger->getRenderEngine().supportsProtectedContent()) {
2138 return {};
2139 }
2140
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002141 // Get parent settings
2142 RoundedCornerState parentSettings;
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002143 const auto& parent = mDrawingParent.promote();
2144 if (parent != nullptr) {
2145 parentSettings = parent->getRoundedCornerState();
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002146 if (parentSettings.hasRoundedCorners()) {
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002147 ui::Transform t = getActiveTransform(getDrawingState());
2148 t = t.inverse();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002149 parentSettings.cropRect = t.transform(parentSettings.cropRect);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002150 parentSettings.radius.x *= t.getScaleX();
2151 parentSettings.radius.y *= t.getScaleY();
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002152 }
2153 }
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002154
2155 // Get layer settings
2156 Rect layerCropRect = getCroppedBufferSize(getDrawingState());
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002157 const vec2 radius(getDrawingState().cornerRadius, getDrawingState().cornerRadius);
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002158 RoundedCornerState layerSettings(layerCropRect.toFloatRect(), radius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002159 const bool layerSettingsValid = layerSettings.hasRoundedCorners() && layerCropRect.isValid();
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002160
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002161 if (layerSettingsValid && parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002162 // If the parent and the layer have rounded corner settings, use the parent settings if the
2163 // parent crop is entirely inside the layer crop.
2164 // This has limitations and cause rendering artifacts. See b/200300845 for correct fix.
2165 if (parentSettings.cropRect.left > layerCropRect.left &&
2166 parentSettings.cropRect.top > layerCropRect.top &&
2167 parentSettings.cropRect.right < layerCropRect.right &&
2168 parentSettings.cropRect.bottom < layerCropRect.bottom) {
2169 return parentSettings;
2170 } else {
2171 return layerSettings;
2172 }
Vishnu Nairb1845592021-10-07 12:17:57 -07002173 } else if (layerSettingsValid) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002174 return layerSettings;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002175 } else if (parentSettings.hasRoundedCorners()) {
Vishnu Nair9dbf8e82021-09-16 16:24:47 -07002176 return parentSettings;
2177 }
2178 return {};
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002179}
2180
Robert Carr88b85e12022-03-21 15:47:35 -07002181bool Layer::findInHierarchy(const sp<Layer>& l) {
2182 if (l == this) {
2183 return true;
2184 }
2185 for (auto& child : mDrawingChildren) {
2186 if (child->findInHierarchy(l)) {
2187 return true;
2188 }
2189 }
2190 return false;
2191}
2192
Robert Carr1f0a16a2016-10-24 16:27:39 -07002193void Layer::commitChildList() {
2194 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2195 const auto& child = mCurrentChildren[i];
2196 child->commitChildList();
2197 }
2198 mDrawingChildren = mCurrentChildren;
Chia-I Wue41dbe62017-06-13 14:10:56 -07002199 mDrawingParent = mCurrentParent;
Robert Carr88b85e12022-03-21 15:47:35 -07002200 if (CC_UNLIKELY(usingRelativeZ(LayerVector::StateSet::Drawing))) {
2201 auto zOrderRelativeOf = mDrawingState.zOrderRelativeOf.promote();
2202 if (zOrderRelativeOf == nullptr) return;
2203 if (findInHierarchy(zOrderRelativeOf)) {
2204 ALOGE("Detected Z ordering loop between %s and %s", mName.c_str(),
2205 zOrderRelativeOf->mName.c_str());
2206 ALOGE("Severing rel Z loop, potentially dangerous");
2207 mDrawingState.isRelativeOf = false;
Ady Abrahamd11bade2022-08-01 16:18:03 -07002208 zOrderRelativeOf->removeZOrderRelative(wp<Layer>::fromExisting(this));
Robert Carr88b85e12022-03-21 15:47:35 -07002209 }
2210 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002211}
2212
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002213
chaviw3277faf2021-05-19 16:45:23 -05002214void Layer::setInputInfo(const WindowInfo& info) {
Robert Carr6a160312021-05-17 12:08:20 -07002215 mDrawingState.inputInfo = info;
Vishnu Nair07e2a482022-10-18 19:18:16 +00002216 mDrawingState.touchableRegionCrop =
2217 LayerHandle::getLayer(info.touchableRegionCropHandle.promote());
Robert Carr6a160312021-05-17 12:08:20 -07002218 mDrawingState.modified = true;
Arthur Hung9ed43392022-05-27 06:31:57 +00002219 mFlinger->mUpdateInputInfo = true;
Robert Carr720e5062018-07-30 17:45:14 -07002220 setTransactionFlags(eTransactionNeeded);
2221}
2222
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002223perfetto::protos::LayerProto* Layer::writeToProto(perfetto::protos::LayersProto& layersProto,
2224 uint32_t traceFlags) {
2225 perfetto::protos::LayerProto* layerProto = layersProto.add_layers();
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002226 writeToProtoDrawingState(layerProto);
chaviw08f3cb22020-01-13 13:17:21 -08002227 writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
2228
Vishnu Nair00b90132021-11-05 14:03:40 -07002229 if (traceFlags & LayerTracing::TRACE_COMPOSITION) {
Vishnu Nair2f65e972023-04-04 16:36:28 +00002230 ui::LayerStack layerStack =
2231 (mSnapshot) ? mSnapshot->outputFilter.layerStack : ui::INVALID_LAYER_STACK;
2232 writeCompositionStateToProto(layerProto, layerStack);
Alec Mouri6b9e9912020-01-21 10:50:24 -08002233 }
2234
chaviw08f3cb22020-01-13 13:17:21 -08002235 for (const sp<Layer>& layer : mDrawingChildren) {
Vishnu Naird8f5e9f2022-02-03 10:23:28 -08002236 layer->writeToProto(layersProto, traceFlags);
chaviw08f3cb22020-01-13 13:17:21 -08002237 }
chaviw6d89e2d2020-01-14 14:42:01 -08002238
2239 return layerProto;
chaviw08f3cb22020-01-13 13:17:21 -08002240}
2241
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002242void Layer::writeCompositionStateToProto(perfetto::protos::LayerProto* layerProto,
2243 ui::LayerStack layerStack) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002244 ftl::FakeGuard guard(mFlinger->mStateLock); // Called from the main thread.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002245 ftl::FakeGuard mainThreadGuard(kMainThreadContext);
Vishnu Nairea6ff812023-02-27 17:41:39 +00002246
2247 // Only populate for the primary display.
Vishnu Nair2f65e972023-04-04 16:36:28 +00002248 if (const auto display = mFlinger->getDisplayFromLayerStack(layerStack)) {
Vishnu Nairea6ff812023-02-27 17:41:39 +00002249 const auto compositionType = getCompositionType(*display);
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002250 layerProto->set_hwc_composition_type(
2251 static_cast<perfetto::protos::HwcCompositionType>(compositionType));
Vishnu Nair2f65e972023-04-04 16:36:28 +00002252 LayerProtoHelper::writeToProto(getVisibleRegion(display),
Vishnu Nairea6ff812023-02-27 17:41:39 +00002253 [&]() { return layerProto->mutable_visible_region(); });
2254 }
2255}
2256
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002257void Layer::writeToProtoDrawingState(perfetto::protos::LayerProto* layerInfo) {
Vishnu Nair6b7c5c92020-09-29 17:27:05 -07002258 const ui::Transform transform = getTransform();
Vishnu Naird37343b2022-01-12 16:18:56 -08002259 auto buffer = getExternalTexture();
Vishnu Nair00b90132021-11-05 14:03:40 -07002260 if (buffer != nullptr) {
Vishnu Naird37343b2022-01-12 16:18:56 -08002261 LayerProtoHelper::writeToProto(*buffer,
Vishnu Nair00b90132021-11-05 14:03:40 -07002262 [&]() { return layerInfo->mutable_active_buffer(); });
2263 LayerProtoHelper::writeToProtoDeprecated(ui::Transform(getBufferTransform()),
2264 layerInfo->mutable_buffer_transform());
2265 }
2266 layerInfo->set_invalidate(contentDirty);
2267 layerInfo->set_is_protected(isProtected());
2268 layerInfo->set_dataspace(dataspaceDetails(static_cast<android_dataspace>(getDataSpace())));
2269 layerInfo->set_queued_frames(getQueuedFrameCount());
Vishnu Nair00b90132021-11-05 14:03:40 -07002270 layerInfo->set_curr_frame(mCurrentFrameNumber);
Vishnu Nair00b90132021-11-05 14:03:40 -07002271 layerInfo->set_requested_corner_radius(getDrawingState().cornerRadius);
Vishnu Nair50c0afe2022-07-11 15:04:07 -07002272 layerInfo->set_corner_radius(
2273 (getRoundedCornerState().radius.x + getRoundedCornerState().radius.y) / 2.0);
Vishnu Nair00b90132021-11-05 14:03:40 -07002274 layerInfo->set_background_blur_radius(getBackgroundBlurRadius());
2275 layerInfo->set_is_trusted_overlay(isTrustedOverlay());
2276 LayerProtoHelper::writeToProtoDeprecated(transform, layerInfo->mutable_transform());
2277 LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
2278 [&]() { return layerInfo->mutable_position(); });
2279 LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
Vishnu Nair00b90132021-11-05 14:03:40 -07002280 LayerProtoHelper::writeToProto(surfaceDamageRegion,
2281 [&]() { return layerInfo->mutable_damage_region(); });
Vishnu Nair8406fd72019-07-30 11:29:31 -07002282
Vishnu Nair00b90132021-11-05 14:03:40 -07002283 if (hasColorTransform()) {
2284 LayerProtoHelper::writeToProto(getColorTransform(), layerInfo->mutable_color_transform());
Vishnu Nair8406fd72019-07-30 11:29:31 -07002285 }
2286
Vishnu Nair60db8c02020-04-02 11:55:16 -07002287 LayerProtoHelper::writeToProto(mSourceBounds,
2288 [&]() { return layerInfo->mutable_source_bounds(); });
2289 LayerProtoHelper::writeToProto(mScreenBounds,
2290 [&]() { return layerInfo->mutable_screen_bounds(); });
2291 LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
2292 [&]() { return layerInfo->mutable_corner_radius_crop(); });
2293 layerInfo->set_shadow_radius(mEffectiveShadowRadius);
Vishnu Nair8406fd72019-07-30 11:29:31 -07002294}
2295
Kean Mariotti4ba343c2023-04-19 13:31:02 +00002296void Layer::writeToProtoCommonState(perfetto::protos::LayerProto* layerInfo,
2297 LayerVector::StateSet stateSet, uint32_t traceFlags) {
chaviw1d044282017-09-27 12:19:28 -07002298 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2299 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
Robert Carr6a160312021-05-17 12:08:20 -07002300 const State& state = useDrawing ? mDrawingState : mDrawingState;
chaviw1d044282017-09-27 12:19:28 -07002301
chaviw766c9c52021-02-10 17:36:47 -08002302 ui::Transform requestedTransform = state.transform;
chaviw1d044282017-09-27 12:19:28 -07002303
Vishnu Nair00b90132021-11-05 14:03:40 -07002304 layerInfo->set_id(sequence);
2305 layerInfo->set_name(getName().c_str());
2306 layerInfo->set_type(getType());
chaviw1d044282017-09-27 12:19:28 -07002307
Vishnu Nair00b90132021-11-05 14:03:40 -07002308 for (const auto& child : children) {
2309 layerInfo->add_children(child->sequence);
chaviwadc40c22018-07-10 16:57:27 -07002310 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002311
Vishnu Nair00b90132021-11-05 14:03:40 -07002312 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2313 sp<Layer> strongRelative = weakRelative.promote();
2314 if (strongRelative != nullptr) {
2315 layerInfo->add_relatives(strongRelative->sequence);
2316 }
2317 }
2318
Vishnu Nairea04b6f2022-08-19 21:28:17 +00002319 LayerProtoHelper::writeToProto(state.transparentRegionHint,
Vishnu Nair00b90132021-11-05 14:03:40 -07002320 [&]() { return layerInfo->mutable_transparent_region(); });
2321
2322 layerInfo->set_layer_stack(getLayerStack().id);
2323 layerInfo->set_z(state.z);
2324
2325 LayerProtoHelper::writePositionToProto(requestedTransform.tx(), requestedTransform.ty(), [&]() {
2326 return layerInfo->mutable_requested_position();
2327 });
2328
Vishnu Nair00b90132021-11-05 14:03:40 -07002329 LayerProtoHelper::writeToProto(state.crop, [&]() { return layerInfo->mutable_crop(); });
2330
2331 layerInfo->set_is_opaque(isOpaque(state));
2332
2333 layerInfo->set_pixel_format(decodePixelFormat(getPixelFormat()));
2334 LayerProtoHelper::writeToProto(getColor(), [&]() { return layerInfo->mutable_color(); });
2335 LayerProtoHelper::writeToProto(state.color,
2336 [&]() { return layerInfo->mutable_requested_color(); });
2337 layerInfo->set_flags(state.flags);
2338
2339 LayerProtoHelper::writeToProtoDeprecated(requestedTransform,
2340 layerInfo->mutable_requested_transform());
2341
2342 auto parent = useDrawing ? mDrawingParent.promote() : mCurrentParent.promote();
2343 if (parent != nullptr) {
2344 layerInfo->set_parent(parent->sequence);
Vishnu Nair00b90132021-11-05 14:03:40 -07002345 }
2346
2347 auto zOrderRelativeOf = state.zOrderRelativeOf.promote();
2348 if (zOrderRelativeOf != nullptr) {
2349 layerInfo->set_z_order_relative_of(zOrderRelativeOf->sequence);
Vishnu Nair00b90132021-11-05 14:03:40 -07002350 }
2351
2352 layerInfo->set_is_relative_of(state.isRelativeOf);
2353
2354 layerInfo->set_owner_uid(mOwnerUid);
2355
Arthur Hung4cf2d8c2022-04-07 14:52:00 +00002356 if ((traceFlags & LayerTracing::TRACE_INPUT) && needsInputInfo()) {
chaviw3277faf2021-05-19 16:45:23 -05002357 WindowInfo info;
chaviw4c34a092020-07-08 11:30:06 -07002358 if (useDrawing) {
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002359 info = fillInputInfo(
2360 InputDisplayArgs{.transform = &kIdentityTransform, .isSecure = true});
chaviw4c34a092020-07-08 11:30:06 -07002361 } else {
2362 info = state.inputInfo;
2363 }
2364
2365 LayerProtoHelper::writeToProto(info, state.touchableRegionCrop,
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002366 [&]() { return layerInfo->mutable_input_window_info(); });
Evan Rosky1f6d6d52018-12-06 10:47:26 -08002367 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002368
Vishnu Nair00b90132021-11-05 14:03:40 -07002369 if (traceFlags & LayerTracing::TRACE_EXTRA) {
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002370 auto protoMap = layerInfo->mutable_metadata();
2371 for (const auto& entry : state.metadata.mMap) {
2372 (*protoMap)[entry.first] = std::string(entry.second.cbegin(), entry.second.cend());
2373 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07002374 }
Vishnu Naird2aaab12022-02-10 14:49:09 -08002375
2376 LayerProtoHelper::writeToProto(state.destinationFrame,
2377 [&]() { return layerInfo->mutable_destination_frame(); });
chaviw1d044282017-09-27 12:19:28 -07002378}
2379
Robert Carr2e102c92018-10-23 12:11:15 -07002380bool Layer::isRemovedFromCurrentState() const {
Robert Carr6a160312021-05-17 12:08:20 -07002381 return mRemovedFromDrawingState;
Robert Carr2e102c92018-10-23 12:11:15 -07002382}
2383
Prabir Pradhan33da9462022-06-14 14:55:57 +00002384// Applies the given transform to the region, while protecting against overflows caused by any
2385// offsets. If applying the offset in the transform to any of the Rects in the region would result
2386// in an overflow, they are not added to the output Region.
2387static Region transformTouchableRegionSafely(const ui::Transform& t, const Region& r,
2388 const std::string& debugWindowName) {
2389 // Round the translation using the same rounding strategy used by ui::Transform.
2390 const auto tx = static_cast<int32_t>(t.tx() + 0.5);
2391 const auto ty = static_cast<int32_t>(t.ty() + 0.5);
2392
2393 ui::Transform transformWithoutOffset = t;
2394 transformWithoutOffset.set(0.f, 0.f);
2395
2396 const Region transformed = transformWithoutOffset.transform(r);
2397
2398 // Apply the translation to each of the Rects in the region while discarding any that overflow.
2399 Region ret;
2400 for (const auto& rect : transformed) {
2401 Rect newRect;
2402 if (__builtin_add_overflow(rect.left, tx, &newRect.left) ||
2403 __builtin_add_overflow(rect.top, ty, &newRect.top) ||
2404 __builtin_add_overflow(rect.right, tx, &newRect.right) ||
2405 __builtin_add_overflow(rect.bottom, ty, &newRect.bottom)) {
2406 ALOGE("Applying transform to touchable region of window '%s' resulted in an overflow.",
2407 debugWindowName.c_str());
2408 continue;
2409 }
2410 ret.orSelf(newRect);
2411 }
2412 return ret;
2413}
2414
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002415void Layer::fillInputFrameInfo(WindowInfo& info, const ui::Transform& screenToDisplay) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002416 auto [inputBounds, inputBoundsValid] = getInputBounds(/*fillParentBounds=*/false);
2417 if (!inputBoundsValid) {
Prabir Pradhan6fa425a2021-12-16 07:16:04 -08002418 info.touchableRegion.clear();
chaviw7e72caf2020-12-02 16:50:43 -08002419 }
2420
Chavi Weingarten7f019192023-08-08 20:39:01 +00002421 info.frame = getInputBoundsInDisplaySpace(inputBounds, screenToDisplay);
chaviw1ff3d1e2020-07-01 15:53:47 -07002422
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002423 ui::Transform inputToLayer;
Vishnu Nairfed7c122023-03-18 01:54:43 +00002424 inputToLayer.set(inputBounds.left, inputBounds.top);
2425 const ui::Transform layerToScreen = getInputTransform();
2426 const ui::Transform inputToDisplay = screenToDisplay * layerToScreen * inputToLayer;
chaviw39cfa2e2020-11-04 14:19:02 -08002427
Prabir Pradhanc9589c12021-09-22 06:11:43 -07002428 // InputDispatcher expects a display-to-input transform.
2429 info.transform = inputToDisplay.inverse();
2430
2431 // The touchable region is specified in the input coordinate space. Change it to display space.
Prabir Pradhan33da9462022-06-14 14:55:57 +00002432 info.touchableRegion =
2433 transformTouchableRegionSafely(inputToDisplay, info.touchableRegion, mName);
chaviw7e72caf2020-12-02 16:50:43 -08002434}
2435
chaviw3277faf2021-05-19 16:45:23 -05002436void Layer::fillTouchOcclusionMode(WindowInfo& info) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002437 sp<Layer> p = sp<Layer>::fromExisting(this);
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002438 while (p != nullptr && !p->hasInputInfo()) {
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002439 p = p->mDrawingParent.promote();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002440 }
2441 if (p != nullptr) {
2442 info.touchOcclusionMode = p->mDrawingState.inputInfo.touchOcclusionMode;
2443 }
2444}
2445
Vishnu Naira066d902021-09-13 18:40:17 -07002446gui::DropInputMode Layer::getDropInputMode() const {
2447 gui::DropInputMode mode = mDrawingState.dropInputMode;
2448 if (mode == gui::DropInputMode::ALL) {
2449 return mode;
2450 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002451 sp<Layer> parent = mDrawingParent.promote();
2452 if (parent) {
2453 gui::DropInputMode parentMode = parent->getDropInputMode();
Vishnu Naira066d902021-09-13 18:40:17 -07002454 if (parentMode != gui::DropInputMode::NONE) {
2455 return parentMode;
2456 }
2457 }
2458 return mode;
2459}
2460
2461void Layer::handleDropInputMode(gui::WindowInfo& info) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002462 if (mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Vishnu Naira066d902021-09-13 18:40:17 -07002463 return;
2464 }
2465
2466 // Check if we need to drop input unconditionally
2467 gui::DropInputMode dropInputMode = getDropInputMode();
2468 if (dropInputMode == gui::DropInputMode::ALL) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002469 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002470 ALOGV("Dropping input for %s as requested by policy.", getDebugName());
2471 return;
2472 }
2473
2474 // Check if we need to check if the window is obscured by parent
2475 if (dropInputMode != gui::DropInputMode::OBSCURED) {
2476 return;
2477 }
2478
2479 // Check if the parent has set an alpha on the layer
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002480 sp<Layer> parent = mDrawingParent.promote();
2481 if (parent && parent->getAlpha() != 1.0_hf) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002482 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002483 ALOGV("Dropping input for %s as requested by policy because alpha=%f", getDebugName(),
2484 static_cast<float>(getAlpha()));
2485 }
2486
2487 // Check if the parent has cropped the buffer
2488 Rect bufferSize = getCroppedBufferSize(getDrawingState());
2489 if (!bufferSize.isValid()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002490 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002491 return;
2492 }
2493
2494 // Screenbounds are the layer bounds cropped by parents, transformed to screenspace.
2495 // To check if the layer has been cropped, we take the buffer bounds, apply the local
2496 // layer crop and apply the same set of transforms to move to screenspace. If the bounds
2497 // match then the layer has not been cropped by its parents.
2498 Rect bufferInScreenSpace(getTransform().transform(bufferSize));
2499 bool croppedByParent = bufferInScreenSpace != Rect{mScreenBounds};
2500
2501 if (croppedByParent) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002502 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Naira066d902021-09-13 18:40:17 -07002503 ALOGV("Dropping input for %s as requested by policy because buffer is cropped by parent",
2504 getDebugName());
2505 } else {
2506 // If the layer is not obscured by its parents (by setting an alpha or crop), then only drop
2507 // input if the window is obscured. This check should be done in surfaceflinger but the
2508 // logic currently resides in inputflinger. So pass the if_obscured check to input to only
2509 // drop input events if the window is obscured.
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002510 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED;
Vishnu Naira066d902021-09-13 18:40:17 -07002511 }
2512}
2513
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002514WindowInfo Layer::fillInputInfo(const InputDisplayArgs& displayArgs) {
chaviw7e72caf2020-12-02 16:50:43 -08002515 if (!hasInputInfo()) {
2516 mDrawingState.inputInfo.name = getName();
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002517 mDrawingState.inputInfo.ownerUid = gui::Uid{mOwnerUid};
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00002518 mDrawingState.inputInfo.ownerPid = gui::Pid{mOwnerPid};
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002519 mDrawingState.inputInfo.inputConfig |= WindowInfo::InputConfig::NO_INPUT_CHANNEL;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002520 mDrawingState.inputInfo.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002521 }
2522
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002523 const ui::Transform& displayTransform =
2524 displayArgs.transform != nullptr ? *displayArgs.transform : kIdentityTransform;
2525
chaviw3277faf2021-05-19 16:45:23 -05002526 WindowInfo info = mDrawingState.inputInfo;
chaviw7e72caf2020-12-02 16:50:43 -08002527 info.id = sequence;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002528 info.displayId = getLayerStack().id;
chaviw7e72caf2020-12-02 16:50:43 -08002529
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002530 fillInputFrameInfo(info, displayTransform);
chaviw7e72caf2020-12-02 16:50:43 -08002531
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002532 if (displayArgs.transform == nullptr) {
2533 // Do not let the window receive touches if it is not associated with a valid display
2534 // transform. We still allow the window to receive keys and prevent ANRs.
2535 info.inputConfig |= WindowInfo::InputConfig::NOT_TOUCHABLE;
2536 }
2537
Patrick Williams1caf3b72023-03-31 10:59:10 -05002538 info.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !isVisibleForInput());
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002539
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002540 info.alpha = getAlpha();
Bernardo Rufinoa9d0a532021-06-11 15:59:12 +01002541 fillTouchOcclusionMode(info);
Vishnu Naira066d902021-09-13 18:40:17 -07002542 handleDropInputMode(info);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002543
Vishnu Nair16a938f2021-09-24 07:14:54 -07002544 // If the window will be blacked out on a display because the display does not have the secure
2545 // flag and the layer has the secure flag set, then drop input.
Prabir Pradhanda0f62c2022-07-22 19:53:04 +00002546 if (!displayArgs.isSecure && isSecure()) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002547 info.inputConfig |= WindowInfo::InputConfig::DROP_INPUT;
Vishnu Nair16a938f2021-09-24 07:14:54 -07002548 }
2549
Vishnu Nairfed7c122023-03-18 01:54:43 +00002550 sp<Layer> cropLayer = mDrawingState.touchableRegionCrop.promote();
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002551 if (info.replaceTouchableRegionWithCrop) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002552 Rect inputBoundsInDisplaySpace;
2553 if (!cropLayer) {
2554 FloatRect inputBounds = getInputBounds(/*fillParentBounds=*/true).first;
2555 inputBoundsInDisplaySpace = getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2556 } else {
2557 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2558 inputBoundsInDisplaySpace =
2559 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2560 }
2561 info.touchableRegion = Region(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002562 } else if (cropLayer != nullptr) {
Vishnu Nairfed7c122023-03-18 01:54:43 +00002563 FloatRect inputBounds = cropLayer->getInputBounds(/*fillParentBounds=*/true).first;
2564 Rect inputBoundsInDisplaySpace =
2565 cropLayer->getInputBoundsInDisplaySpace(inputBounds, displayTransform);
2566 info.touchableRegion = info.touchableRegion.intersect(inputBoundsInDisplaySpace);
Vishnu Nair6fabeec2019-03-12 13:42:49 -07002567 }
2568
Winson Chunga30f7c92021-06-29 15:42:56 -07002569 // Inherit the trusted state from the parent hierarchy, but don't clobber the trusted state
2570 // if it was set by WM for a known system overlay
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002571 if (isTrustedOverlay()) {
2572 info.inputConfig |= WindowInfo::InputConfig::TRUSTED_OVERLAY;
2573 }
Winson Chunga30f7c92021-06-29 15:42:56 -07002574
chaviwaf87b3e2019-10-01 16:59:28 -07002575 // If the layer is a clone, we need to crop the input region to cloned root to prevent
2576 // touches from going outside the cloned area.
2577 if (isClone()) {
chaviw8577ea82022-06-01 16:32:26 -05002578 info.inputConfig |= WindowInfo::InputConfig::CLONE;
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002579 if (const sp<Layer> clonedRoot = getClonedRoot()) {
2580 const Rect rect = displayTransform.transform(Rect{clonedRoot->mScreenBounds});
chaviwaf87b3e2019-10-01 16:59:28 -07002581 info.touchableRegion = info.touchableRegion.intersect(rect);
2582 }
2583 }
2584
Vishnu Nair494a2e42023-11-10 17:21:19 -08002585 Rect bufferSize = getBufferSize(getDrawingState());
2586 info.contentSize = Size(bufferSize.width(), bufferSize.height());
2587
Robert Carr720e5062018-07-30 17:45:14 -07002588 return info;
2589}
2590
Vishnu Nairfed7c122023-03-18 01:54:43 +00002591Rect Layer::getInputBoundsInDisplaySpace(const FloatRect& inputBounds,
2592 const ui::Transform& screenToDisplay) {
2593 // InputDispatcher works in the display device's coordinate space. Here, we calculate the
2594 // frame and transform used for the layer, which determines the bounds and the coordinate space
2595 // within which the layer will receive input.
2596
2597 // Coordinate space definitions:
2598 // - display: The display device's coordinate space. Correlates to pixels on the display.
2599 // - screen: The post-rotation coordinate space for the display, a.k.a. logical display space.
2600 // - layer: The coordinate space of this layer.
2601 // - input: The coordinate space in which this layer will receive input events. This could be
2602 // different than layer space if a surfaceInset is used, which changes the origin
2603 // of the input space.
2604
2605 // Crop the input bounds to ensure it is within the parent's bounds.
2606 const FloatRect croppedInputBounds = mBounds.intersect(inputBounds);
2607 const ui::Transform layerToScreen = getInputTransform();
2608 const ui::Transform layerToDisplay = screenToDisplay * layerToScreen;
2609 return Rect{layerToDisplay.transform(croppedInputBounds)};
2610}
2611
chaviwaf87b3e2019-10-01 16:59:28 -07002612sp<Layer> Layer::getClonedRoot() {
2613 if (mClonedChild != nullptr) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002614 return sp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002615 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002616 if (mDrawingParent == nullptr || mDrawingParent.promote() == nullptr) {
chaviwaf87b3e2019-10-01 16:59:28 -07002617 return nullptr;
2618 }
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002619 return mDrawingParent.promote()->getClonedRoot();
chaviwaf87b3e2019-10-01 16:59:28 -07002620}
2621
Robert Carredd13602020-04-13 17:24:34 -07002622bool Layer::hasInputInfo() const {
Linus Tufvessona1858822022-03-04 09:32:07 +00002623 return mDrawingState.inputInfo.token != nullptr ||
2624 mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Robert Carr720e5062018-07-30 17:45:14 -07002625}
2626
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002627compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002628 const DisplayDevice* display) const {
2629 if (!display) return nullptr;
Lloyd Pique30db6402023-06-26 18:56:51 +00002630 if (!mFlinger->mLayerLifecycleManagerEnabled) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00002631 return display->getCompositionDisplay()->getOutputLayerForLayer(
2632 getCompositionEngineLayerFE());
2633 }
2634 sp<LayerFE> layerFE;
2635 frontend::LayerHierarchy::TraversalPath path{.id = static_cast<uint32_t>(sequence)};
2636 for (auto& [p, layer] : mLayerFEs) {
2637 if (p == path) {
2638 layerFE = layer;
2639 }
2640 }
2641
2642 if (!layerFE) return nullptr;
2643 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002644}
2645
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002646compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
2647 const DisplayDevice* display, const frontend::LayerHierarchy::TraversalPath& path) const {
2648 if (!display) return nullptr;
Vishnu Naire9ee0002023-07-01 03:14:51 +00002649 if (!mFlinger->mLayerLifecycleManagerEnabled) {
2650 return display->getCompositionDisplay()->getOutputLayerForLayer(
2651 getCompositionEngineLayerFE());
2652 }
Vishnu Nair3cc15a42023-06-30 06:20:22 +00002653 sp<LayerFE> layerFE;
2654 for (auto& [p, layer] : mLayerFEs) {
2655 if (p == path) {
2656 layerFE = layer;
2657 }
2658 }
2659
2660 if (!layerFE) return nullptr;
2661 return display->getCompositionDisplay()->getOutputLayerForLayer(layerFE);
2662}
2663
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002664Region Layer::getVisibleRegion(const DisplayDevice* display) const {
2665 const auto outputLayer = findOutputLayerForDisplay(display);
2666 return outputLayer ? outputLayer->getState().visibleRegion : Region();
Lloyd Piquea2468662019-03-07 21:31:06 -08002667}
2668
Vishnu Nairde177252023-04-21 12:44:10 -07002669void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom, uint32_t mirrorRootId) {
Vishnu Nair83d91622023-12-08 23:00:22 +00002670 if (mFlinger->mLayerLifecycleManagerEnabled) return;
Vishnu Nairde177252023-04-21 12:44:10 -07002671 mSnapshot->path.id = clonedFrom->getSequence();
Vishnu Nair6f878312023-09-08 11:05:01 -07002672 mSnapshot->path.mirrorRootIds.emplace_back(mirrorRootId);
Vishnu Nairde177252023-04-21 12:44:10 -07002673
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002674 cloneDrawingState(clonedFrom.get());
chaviwb4c6e582019-08-16 14:35:07 -07002675 mClonedFrom = clonedFrom;
Patrick Williamsbb25f802022-08-30 23:02:34 +00002676 mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
2677 mPotentialCursor = clonedFrom->mPotentialCursor;
2678 mProtectedByApp = clonedFrom->mProtectedByApp;
2679 updateCloneBufferInfo();
2680}
2681
2682void Layer::updateCloneBufferInfo() {
2683 if (!isClone() || !isClonedFromAlive()) {
2684 return;
2685 }
2686
2687 sp<Layer> clonedFrom = getClonedFrom();
2688 mBufferInfo = clonedFrom->mBufferInfo;
2689 mSidebandStream = clonedFrom->mSidebandStream;
2690 surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
2691 mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
2692 mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
2693
2694 // After buffer info is updated, the drawingState from the real layer needs to be copied into
2695 // the cloned. This is because some properties of drawingState can change when latchBuffer is
2696 // called. However, copying the drawingState would also overwrite the cloned layer's relatives
2697 // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
2698 // the cloned drawingState again.
2699 wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
2700 SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
2701 wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
2702 WindowInfo tmpInputInfo = mDrawingState.inputInfo;
2703
2704 cloneDrawingState(clonedFrom.get());
2705
2706 mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
2707 mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
2708 mDrawingState.zOrderRelatives = tmpZOrderRelatives;
2709 mDrawingState.inputInfo = tmpInputInfo;
chaviwb4c6e582019-08-16 14:35:07 -07002710}
chaviw74b03172019-08-19 11:09:03 -07002711
Vishnu Nair3be61902023-04-26 19:47:29 -07002712bool Layer::updateMirrorInfo(const std::deque<Layer*>& cloneRootsPendingUpdates) {
chaviw74b03172019-08-19 11:09:03 -07002713 if (mClonedChild == nullptr || !mClonedChild->isClonedFromAlive()) {
2714 // If mClonedChild is null, there is nothing to mirror. If isClonedFromAlive returns false,
2715 // it means that there is a clone, but the layer it was cloned from has been destroyed. In
2716 // that case, we want to delete the reference to the clone since we want it to get
2717 // destroyed. The root, this layer, will still be around since the client can continue
2718 // to hold a reference, but no cloned layers will be displayed.
2719 mClonedChild = nullptr;
Vishnu Nair3be61902023-04-26 19:47:29 -07002720 return true;
chaviw74b03172019-08-19 11:09:03 -07002721 }
2722
2723 std::map<sp<Layer>, sp<Layer>> clonedLayersMap;
2724 // If the real layer exists and is in current state, add the clone as a child of the root.
2725 // There's no need to remove from drawingState when the layer is offscreen since currentState is
2726 // copied to drawingState for the root layer. So the clonedChild is always removed from
2727 // drawingState and then needs to be added back each traversal.
2728 if (!mClonedChild->getClonedFrom()->isRemovedFromCurrentState()) {
2729 addChildToDrawing(mClonedChild);
2730 }
2731
2732 mClonedChild->updateClonedDrawingState(clonedLayersMap);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002733 mClonedChild->updateClonedChildren(sp<Layer>::fromExisting(this), clonedLayersMap);
chaviw74b03172019-08-19 11:09:03 -07002734 mClonedChild->updateClonedRelatives(clonedLayersMap);
Vishnu Nair3be61902023-04-26 19:47:29 -07002735
2736 for (Layer* root : cloneRootsPendingUpdates) {
2737 if (clonedLayersMap.find(sp<Layer>::fromExisting(root)) != clonedLayersMap.end()) {
2738 return false;
2739 }
2740 }
2741 return true;
chaviw74b03172019-08-19 11:09:03 -07002742}
2743
2744void Layer::updateClonedDrawingState(std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2745 // If the layer the clone was cloned from is alive, copy the content of the drawingState
2746 // to the clone. If the real layer is no longer alive, continue traversing the children
2747 // since we may be able to pull out other children that are still alive.
2748 if (isClonedFromAlive()) {
2749 sp<Layer> clonedFrom = getClonedFrom();
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002750 cloneDrawingState(clonedFrom.get());
Ady Abrahamd11bade2022-08-01 16:18:03 -07002751 clonedLayersMap.emplace(clonedFrom, sp<Layer>::fromExisting(this));
chaviw74b03172019-08-19 11:09:03 -07002752 }
2753
2754 // The clone layer may have children in drawingState since they may have been created and
2755 // added from a previous request to updateMirorInfo. This is to ensure we don't recreate clones
2756 // that already exist, since we can just re-use them.
2757 // The drawingChildren will not get overwritten by the currentChildren since the clones are
2758 // not updated in the regular traversal. They are skipped since the root will lose the
2759 // reference to them when it copies its currentChildren to drawing.
2760 for (sp<Layer>& child : mDrawingChildren) {
2761 child->updateClonedDrawingState(clonedLayersMap);
2762 }
2763}
2764
2765void Layer::updateClonedChildren(const sp<Layer>& mirrorRoot,
2766 std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2767 mDrawingChildren.clear();
2768
2769 if (!isClonedFromAlive()) {
2770 return;
2771 }
2772
2773 sp<Layer> clonedFrom = getClonedFrom();
2774 for (sp<Layer>& child : clonedFrom->mDrawingChildren) {
2775 if (child == mirrorRoot) {
2776 // This is to avoid cyclical mirroring.
2777 continue;
2778 }
2779 sp<Layer> clonedChild = clonedLayersMap[child];
2780 if (clonedChild == nullptr) {
Vishnu Nairde177252023-04-21 12:44:10 -07002781 clonedChild = child->createClone(mirrorRoot->getSequence());
chaviw74b03172019-08-19 11:09:03 -07002782 clonedLayersMap[child] = clonedChild;
2783 }
2784 addChildToDrawing(clonedChild);
2785 clonedChild->updateClonedChildren(mirrorRoot, clonedLayersMap);
2786 }
2787}
2788
chaviwaf87b3e2019-10-01 16:59:28 -07002789void Layer::updateClonedInputInfo(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
2790 auto cropLayer = mDrawingState.touchableRegionCrop.promote();
2791 if (cropLayer != nullptr) {
2792 if (clonedLayersMap.count(cropLayer) == 0) {
2793 // Real layer had a crop layer but it's not in the cloned hierarchy. Just set to
2794 // self as crop layer to avoid going outside bounds.
Ady Abrahamd11bade2022-08-01 16:18:03 -07002795 mDrawingState.touchableRegionCrop = wp<Layer>::fromExisting(this);
chaviwaf87b3e2019-10-01 16:59:28 -07002796 } else {
2797 const sp<Layer>& clonedCropLayer = clonedLayersMap.at(cropLayer);
2798 mDrawingState.touchableRegionCrop = clonedCropLayer;
2799 }
2800 }
2801 // Cloned layers shouldn't handle watch outside since their z order is not determined by
2802 // WM or the client.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002803 mDrawingState.inputInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, false);
chaviwaf87b3e2019-10-01 16:59:28 -07002804}
2805
2806void Layer::updateClonedRelatives(const std::map<sp<Layer>, sp<Layer>>& clonedLayersMap) {
Ady Abrahamd11bade2022-08-01 16:18:03 -07002807 mDrawingState.zOrderRelativeOf = wp<Layer>();
chaviw74b03172019-08-19 11:09:03 -07002808 mDrawingState.zOrderRelatives.clear();
2809
2810 if (!isClonedFromAlive()) {
2811 return;
2812 }
2813
chaviwaf87b3e2019-10-01 16:59:28 -07002814 const sp<Layer>& clonedFrom = getClonedFrom();
chaviw74b03172019-08-19 11:09:03 -07002815 for (wp<Layer>& relativeWeak : clonedFrom->mDrawingState.zOrderRelatives) {
chaviwaf87b3e2019-10-01 16:59:28 -07002816 const sp<Layer>& relative = relativeWeak.promote();
2817 if (clonedLayersMap.count(relative) > 0) {
2818 auto& clonedRelative = clonedLayersMap.at(relative);
chaviw74b03172019-08-19 11:09:03 -07002819 mDrawingState.zOrderRelatives.add(clonedRelative);
2820 }
2821 }
2822
2823 // Check if the relativeLayer for the real layer is part of the cloned hierarchy.
2824 // It's possible that the layer it's relative to is outside the requested cloned hierarchy.
2825 // In that case, we treat the layer as if the relativeOf has been removed. This way, it will
2826 // still traverse the children, but the layer with the missing relativeOf will not be shown
2827 // on screen.
chaviwaf87b3e2019-10-01 16:59:28 -07002828 const sp<Layer>& relativeOf = clonedFrom->mDrawingState.zOrderRelativeOf.promote();
2829 if (clonedLayersMap.count(relativeOf) > 0) {
2830 const sp<Layer>& clonedRelativeOf = clonedLayersMap.at(relativeOf);
chaviw74b03172019-08-19 11:09:03 -07002831 mDrawingState.zOrderRelativeOf = clonedRelativeOf;
2832 }
2833
chaviwaf87b3e2019-10-01 16:59:28 -07002834 updateClonedInputInfo(clonedLayersMap);
2835
chaviw74b03172019-08-19 11:09:03 -07002836 for (sp<Layer>& child : mDrawingChildren) {
2837 child->updateClonedRelatives(clonedLayersMap);
2838 }
2839}
2840
2841void Layer::addChildToDrawing(const sp<Layer>& layer) {
2842 mDrawingChildren.add(layer);
Ady Abrahamd11bade2022-08-01 16:18:03 -07002843 layer->mDrawingParent = sp<Layer>::fromExisting(this);
chaviw74b03172019-08-19 11:09:03 -07002844}
2845
Dominik Laskowski29fa1462021-04-27 15:51:50 -07002846bool Layer::isInternalDisplayOverlay() const {
chaviwc5676c62020-09-18 15:01:04 -07002847 const State& s(mDrawingState);
2848 if (s.flags & layer_state_t::eLayerSkipScreenshot) {
2849 return true;
2850 }
2851
Rob Carrc6d2d2b2021-10-25 16:51:49 +00002852 sp<Layer> parent = mDrawingParent.promote();
2853 return parent && parent->isInternalDisplayOverlay();
chaviwc5676c62020-09-18 15:01:04 -07002854}
2855
Robert Carr6a0382d2021-07-01 15:57:17 -07002856void Layer::setClonedChild(const sp<Layer>& clonedChild) {
2857 mClonedChild = clonedChild;
2858 mHadClonedChild = true;
Vishnu Nair3be61902023-04-26 19:47:29 -07002859 mFlinger->mLayerMirrorRoots.push_back(this);
Robert Carr6a0382d2021-07-01 15:57:17 -07002860}
2861
Vishnu Nair9cf4a4d2021-09-17 12:16:08 -07002862bool Layer::setDropInputMode(gui::DropInputMode mode) {
2863 if (mDrawingState.dropInputMode == mode) {
2864 return false;
2865 }
2866 mDrawingState.dropInputMode = mode;
2867 return true;
2868}
2869
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002870void Layer::cloneDrawingState(const Layer* from) {
2871 mDrawingState = from->mDrawingState;
2872 // Skip callback info since they are not applicable for cloned layers.
2873 mDrawingState.releaseBufferListener = nullptr;
Vishnu Naircfb2d252023-01-19 04:44:02 +00002874 // TODO (b/238781169) currently broken for mirror layers because we do not
2875 // track release fences for mirror layers composed on other displays
Vishnu Nair3bb11d02021-11-26 09:24:11 -08002876 mDrawingState.callbackHandles = {};
2877}
2878
Patrick Williamsbb25f802022-08-30 23:02:34 +00002879void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
2880 const sp<GraphicBuffer>& buffer, uint64_t framenumber,
liulijuneb489f62022-10-17 22:02:14 +08002881 const sp<Fence>& releaseFence) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002882 if (!listener) {
2883 return;
2884 }
2885 ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
liulijuneb489f62022-10-17 22:02:14 +08002886 uint32_t currentMaxAcquiredBufferCount =
2887 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
Huihong Luoffee3bc2023-01-17 16:14:35 +00002888 listener->onReleaseBuffer({buffer->getId(), framenumber},
2889 releaseFence ? releaseFence : Fence::NO_FENCE,
2890 currentMaxAcquiredBufferCount);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002891}
2892
Melody Hsu793f8362024-01-08 20:00:35 +00002893sp<CallbackHandle> Layer::findCallbackHandle() {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002894 // If we are displayed on multiple displays in a single composition cycle then we would
2895 // need to do careful tracking to enable the use of the mLastClientCompositionFence.
2896 // For example we can only use it if all the displays are client comp, and we need
2897 // to merge all the client comp fences. We could do this, but for now we just
2898 // disable the optimization when a layer is composed on multiple displays.
2899 if (mClearClientCompositionFenceOnLayerDisplayed) {
2900 mLastClientCompositionFence = nullptr;
2901 } else {
2902 mClearClientCompositionFenceOnLayerDisplayed = true;
2903 }
2904
2905 // The previous release fence notifies the client that SurfaceFlinger is done with the previous
2906 // buffer that was presented on this layer. The first transaction that came in this frame that
2907 // replaced the previous buffer on this layer needs this release fence, because the fence will
2908 // let the client know when that previous buffer is removed from the screen.
2909 //
2910 // Every other transaction on this layer does not need a release fence because no other
2911 // Transactions that were set on this layer this frame are going to have their preceding buffer
2912 // removed from the display this frame.
2913 //
2914 // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
2915 // buffer so it doesn't need a previous release fence because the layer still needs the previous
2916 // buffer. The second transaction contains a buffer so it needs a previous release fence because
2917 // the previous buffer will be released this frame. The third transaction also contains a
2918 // buffer. It replaces the buffer in the second transaction. The buffer in the second
2919 // transaction will now no longer be presented so it is released immediately and the third
2920 // transaction doesn't need a previous release fence.
2921 sp<CallbackHandle> ch;
2922 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07002923 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00002924 ch = handle;
2925 break;
2926 }
2927 }
Melody Hsu793f8362024-01-08 20:00:35 +00002928 return ch;
2929}
2930
2931void Layer::prepareReleaseCallbacks(ftl::Future<FenceResult> futureFenceResult,
2932 ui::LayerStack layerStack) {
2933 sp<CallbackHandle> ch = findCallbackHandle();
2934
2935 if (ch != nullptr) {
2936 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
2937 ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
2938 ch->name = mName;
2939 } else {
Melody Hsue4ef87f2024-03-26 23:54:45 +00002940 // If we didn't get a release callback yet (e.g. some scenarios when capturing
2941 // screenshots asynchronously) then make sure we don't drop the fence.
2942 // Older fences for the same layer stack can be dropped when a new fence arrives.
2943 // An assumption here is that RenderEngine performs work sequentially, so an
2944 // incoming fence will not fire before an existing fence.
2945 mAdditionalPreviousReleaseFences.emplace_or_replace(layerStack,
2946 std::move(futureFenceResult));
Melody Hsu793f8362024-01-08 20:00:35 +00002947 }
2948
2949 if (mBufferInfo.mBuffer) {
2950 mPreviouslyPresentedLayerStacks.push_back(layerStack);
2951 }
2952
2953 if (mDrawingState.frameNumber > 0) {
2954 mDrawingState.previousFrameNumber = mDrawingState.frameNumber;
2955 }
2956}
2957
2958void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult,
2959 ui::LayerStack layerStack,
2960 std::function<FenceResult(FenceResult)>&& continuation) {
2961 sp<CallbackHandle> ch = findCallbackHandle();
Alec Mouri9892aac2023-12-11 21:16:59 +00002962
2963 if (!FlagManager::getInstance().screenshot_fence_preservation() && continuation) {
2964 futureFenceResult = ftl::Future(futureFenceResult).then(std::move(continuation)).share();
2965 }
2966
Patrick Williamsbb25f802022-08-30 23:02:34 +00002967 if (ch != nullptr) {
2968 ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
Melody Hsu793f8362024-01-08 20:00:35 +00002969 ch->previousSharedReleaseFences.emplace_back(std::move(futureFenceResult));
Patrick Williamsbb25f802022-08-30 23:02:34 +00002970 ch->name = mName;
Alec Mouri9892aac2023-12-11 21:16:59 +00002971 } else if (FlagManager::getInstance().screenshot_fence_preservation()) {
2972 // If we didn't get a release callback yet, e.g. some scenarios when capturing screenshots
2973 // asynchronously, then make sure we don't drop the fence.
Melody Hsu793f8362024-01-08 20:00:35 +00002974 mPreviousReleaseFenceAndContinuations.emplace_back(std::move(futureFenceResult),
2975 std::move(continuation));
Alec Mouri9892aac2023-12-11 21:16:59 +00002976 std::vector<FenceAndContinuation> mergedFences;
2977 sp<Fence> prevFence = nullptr;
2978 // For a layer that's frequently screenshotted, try to merge fences to make sure we don't
2979 // grow unbounded.
Melody Hsu793f8362024-01-08 20:00:35 +00002980 for (const auto& futureAndContinuation : mPreviousReleaseFenceAndContinuations) {
2981 auto result = futureAndContinuation.future.wait_for(0s);
Alec Mouri9892aac2023-12-11 21:16:59 +00002982 if (result != std::future_status::ready) {
Melody Hsu793f8362024-01-08 20:00:35 +00002983 mergedFences.emplace_back(futureAndContinuation);
Alec Mouri9892aac2023-12-11 21:16:59 +00002984 continue;
2985 }
2986
Melody Hsu793f8362024-01-08 20:00:35 +00002987 mergeFence(getDebugName(),
2988 futureAndContinuation.chain().get().value_or(Fence::NO_FENCE), prevFence);
Alec Mouri9892aac2023-12-11 21:16:59 +00002989 }
2990 if (prevFence != nullptr) {
2991 mergedFences.emplace_back(ftl::yield(FenceResult(std::move(prevFence))).share());
2992 }
2993
Melody Hsu793f8362024-01-08 20:00:35 +00002994 mPreviousReleaseFenceAndContinuations.swap(mergedFences);
Patrick Williamsbb25f802022-08-30 23:02:34 +00002995 }
Alec Mouri9892aac2023-12-11 21:16:59 +00002996
Vishnu Nair316b7f42023-10-13 23:44:46 +00002997 if (mBufferInfo.mBuffer) {
2998 mPreviouslyPresentedLayerStacks.push_back(layerStack);
2999 }
Alec Mouri21d94322023-10-17 19:51:39 +00003000
3001 if (mDrawingState.frameNumber > 0) {
3002 mDrawingState.previousFrameNumber = mDrawingState.frameNumber;
3003 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003004}
3005
3006void Layer::onSurfaceFrameCreated(
3007 const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
3008 while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
3009 // Too many SurfaceFrames pending classification. The front of the deque is probably not
3010 // tracked by FrameTimeline and will never be presented. This will only result in a memory
3011 // leak.
Pascal Muetschard55626262022-11-08 11:05:19 +01003012 if (hasBufferOrSidebandStreamInDrawing()) {
3013 // Only log for layers with a buffer, since we expect the jank data to be drained for
3014 // these, while there may be no jank listeners for bufferless layers.
3015 ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
3016 mName.c_str());
3017 std::string miniDump = mPendingJankClassifications.front()->miniDump();
3018 ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
3019 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003020 mPendingJankClassifications.pop_front();
3021 }
3022 mPendingJankClassifications.emplace_back(surfaceFrame);
3023}
3024
3025void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
3026 for (const auto& handle : mDrawingState.callbackHandles) {
Lloyd Pique30db6402023-06-26 18:56:51 +00003027 if (mFlinger->mLayerLifecycleManagerEnabled) {
Vishnu Nairb76d99a2023-03-19 18:22:31 -07003028 handle->transformHint = mTransformHint;
3029 } else {
3030 handle->transformHint = mSkipReportingTransformHint
3031 ? std::nullopt
3032 : std::make_optional<uint32_t>(mTransformHintLegacy);
3033 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003034 handle->dequeueReadyTime = dequeueReadyTime;
3035 handle->currentMaxAcquiredBufferCount =
3036 mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
3037 ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
3038 handle->previousReleaseCallbackId.framenumber);
3039 }
3040
3041 for (auto& handle : mDrawingState.callbackHandles) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003042 if (handle->releasePreviousBuffer && mPreviousReleaseBufferEndpoint == handle->listener) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003043 handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
3044 break;
3045 }
3046 }
3047
3048 std::vector<JankData> jankData;
Pascal Muetschardf54181b2022-12-13 14:53:25 +01003049 transferAvailableJankData(mDrawingState.callbackHandles, jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003050 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
3051 jankData);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003052 mDrawingState.callbackHandles = {};
3053}
3054
3055bool Layer::willPresentCurrentTransaction() const {
3056 // Returns true if the most recent Transaction applied to CurrentState will be presented.
3057 return (getSidebandStreamChanged() || getAutoRefresh() ||
3058 (mDrawingState.modified &&
3059 (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
3060}
3061
3062bool Layer::setTransform(uint32_t transform) {
3063 if (mDrawingState.bufferTransform == transform) return false;
3064 mDrawingState.bufferTransform = transform;
3065 mDrawingState.modified = true;
3066 setTransactionFlags(eTransactionNeeded);
3067 return true;
3068}
3069
3070bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
3071 if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
3072 mDrawingState.sequence++;
3073 mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
3074 mDrawingState.modified = true;
3075 setTransactionFlags(eTransactionNeeded);
3076 return true;
3077}
3078
3079bool Layer::setBufferCrop(const Rect& bufferCrop) {
3080 if (mDrawingState.bufferCrop == bufferCrop) return false;
3081
3082 mDrawingState.sequence++;
3083 mDrawingState.bufferCrop = bufferCrop;
3084
3085 mDrawingState.modified = true;
3086 setTransactionFlags(eTransactionNeeded);
3087 return true;
3088}
3089
3090bool Layer::setDestinationFrame(const Rect& destinationFrame) {
3091 if (mDrawingState.destinationFrame == destinationFrame) return false;
3092
3093 mDrawingState.sequence++;
3094 mDrawingState.destinationFrame = destinationFrame;
3095
3096 mDrawingState.modified = true;
3097 setTransactionFlags(eTransactionNeeded);
3098 return true;
3099}
3100
3101// Translate destination frame into scale and position. If a destination frame is not set, use the
3102// provided scale and position
3103bool Layer::updateGeometry() {
3104 if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
3105 mDrawingState.destinationFrame.isEmpty()) {
3106 // If destination frame is not set, use the requested transform set via
3107 // Layer::setPosition and Layer::setMatrix.
3108 return assignTransform(&mDrawingState.transform, mRequestedTransform);
3109 }
3110
3111 Rect destRect = mDrawingState.destinationFrame;
3112 int32_t destW = destRect.width();
3113 int32_t destH = destRect.height();
3114 if (destRect.left < 0) {
3115 destRect.left = 0;
3116 destRect.right = destW;
3117 }
3118 if (destRect.top < 0) {
3119 destRect.top = 0;
3120 destRect.bottom = destH;
3121 }
3122
3123 if (!mDrawingState.buffer) {
3124 ui::Transform t;
3125 t.set(destRect.left, destRect.top);
3126 return assignTransform(&mDrawingState.transform, t);
3127 }
3128
3129 uint32_t bufferWidth = mDrawingState.buffer->getWidth();
3130 uint32_t bufferHeight = mDrawingState.buffer->getHeight();
3131 // Undo any transformations on the buffer.
3132 if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
3133 std::swap(bufferWidth, bufferHeight);
3134 }
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003135 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003136 if (mDrawingState.transformToDisplayInverse) {
3137 if (invTransform & ui::Transform::ROT_90) {
3138 std::swap(bufferWidth, bufferHeight);
3139 }
3140 }
3141
3142 float sx = destW / static_cast<float>(bufferWidth);
3143 float sy = destH / static_cast<float>(bufferHeight);
3144 ui::Transform t;
3145 t.set(sx, 0, 0, sy);
3146 t.set(destRect.left, destRect.top);
3147 return assignTransform(&mDrawingState.transform, t);
3148}
3149
3150bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
3151 if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
3152 mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
3153 return false;
3154 }
3155
3156 mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
3157
3158 mDrawingState.sequence++;
3159 mDrawingState.modified = true;
3160 setTransactionFlags(eTransactionNeeded);
3161
3162 return true;
3163}
3164
3165bool Layer::setPosition(float x, float y) {
3166 if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
3167 return false;
3168 }
3169
3170 mRequestedTransform.set(x, y);
3171
3172 mDrawingState.sequence++;
3173 mDrawingState.modified = true;
3174 setTransactionFlags(eTransactionNeeded);
3175
3176 return true;
3177}
3178
Dorin Drimuse5374e52023-08-02 17:52:43 +00003179void Layer::releasePreviousBuffer() {
3180 mReleasePreviousBuffer = true;
3181 if (!mBufferInfo.mBuffer ||
3182 (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
3183 mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
3184 // If mDrawingState has a buffer, and we are about to update again
3185 // before swapping to drawing state, then the first buffer will be
3186 // dropped and we should decrement the pending buffer count and
3187 // call any release buffer callbacks if set.
3188 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3189 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3190 mDrawingState.acquireFence);
3191 decrementPendingBufferCount();
3192 if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
3193 mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
3194 addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX, systemTime());
3195 mDrawingState.bufferSurfaceFrameTX.reset();
3196 }
3197 } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
3198 callReleaseBufferCallback(mDrawingState.releaseBufferListener,
3199 mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
3200 mLastClientCompositionFence);
3201 mLastClientCompositionFence = nullptr;
3202 }
3203}
3204
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003205void Layer::resetDrawingStateBufferInfo() {
3206 mDrawingState.producerId = 0;
3207 mDrawingState.frameNumber = 0;
Alec Mouri21d94322023-10-17 19:51:39 +00003208 mDrawingState.previousFrameNumber = 0;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003209 mDrawingState.releaseBufferListener = nullptr;
3210 mDrawingState.buffer = nullptr;
3211 mDrawingState.acquireFence = sp<Fence>::make(-1);
3212 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3213 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3214 mDrawingState.releaseBufferEndpoint = nullptr;
3215}
3216
Patrick Williamsbb25f802022-08-30 23:02:34 +00003217bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
3218 const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
3219 bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
Brian Lindahl439afad2022-11-14 11:16:55 -07003220 const FrameTimelineInfo& info) {
Chavi Weingarten009619f2022-09-15 20:27:25 +00003221 ATRACE_FORMAT("setBuffer %s - hasBuffer=%s", getDebugName(), (buffer ? "true" : "false"));
Patrick Williamsbb25f802022-08-30 23:02:34 +00003222
3223 const bool frameNumberChanged =
3224 bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
3225 const uint64_t frameNumber =
3226 frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
Chavi Weingarten009619f2022-09-15 20:27:25 +00003227 ATRACE_FORMAT_INSTANT("setBuffer %s - %" PRIu64, getDebugName(), frameNumber);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003228
3229 if (mDrawingState.buffer) {
Dorin Drimuse5374e52023-08-02 17:52:43 +00003230 releasePreviousBuffer();
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003231 } else if (buffer) {
Vishnu Nairc09c0232023-03-02 03:22:35 +00003232 // if we are latching a buffer for the first time then clear the mLastLatchTime since
3233 // we don't want to incorrectly classify a frame if we miss the desired present time.
3234 updateLastLatchTime(0);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003235 }
3236
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003237 mDrawingState.desiredPresentTime = desiredPresentTime;
3238 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3239 mDrawingState.latchedVsyncId = info.vsyncId;
Ady Abraham55269162023-05-09 11:26:06 -07003240 mDrawingState.useVsyncIdForRefreshRateSelection = info.useForRefreshRateSelection;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003241 mDrawingState.modified = true;
3242 if (!buffer) {
3243 resetDrawingStateBufferInfo();
3244 setTransactionFlags(eTransactionNeeded);
3245 mDrawingState.bufferSurfaceFrameTX = nullptr;
3246 setFrameTimelineVsyncForBufferlessTransaction(info, postTime);
3247 return true;
Dorin Drimuse5374e52023-08-02 17:52:43 +00003248 } else {
3249 // release sideband stream if it exists and a non null buffer is being set
3250 if (mDrawingState.sidebandStream != nullptr) {
Dorin Drimus66ed1c42023-09-27 13:10:16 +00003251 setSidebandStream(nullptr, info, postTime);
Dorin Drimuse5374e52023-08-02 17:52:43 +00003252 }
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003253 }
3254
Vishnu Naird1f74982023-06-15 20:16:51 -07003255 if ((mDrawingState.producerId > bufferData.producerId) ||
3256 ((mDrawingState.producerId == bufferData.producerId) &&
3257 (mDrawingState.frameNumber > frameNumber))) {
3258 ALOGE("Out of order buffers detected for %s producedId=%d frameNumber=%" PRIu64
3259 " -> producedId=%d frameNumber=%" PRIu64,
3260 getDebugName(), mDrawingState.producerId, mDrawingState.frameNumber,
3261 bufferData.producerId, frameNumber);
3262 TransactionTraceWriter::getInstance().invoke("out_of_order_buffers_", /*overwrite=*/false);
3263 }
3264
liulijuneb489f62022-10-17 22:02:14 +08003265 mDrawingState.producerId = bufferData.producerId;
Vishnu Nair63221212023-04-06 15:17:37 -07003266 mDrawingState.barrierProducerId =
3267 std::max(mDrawingState.producerId, mDrawingState.barrierProducerId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003268 mDrawingState.frameNumber = frameNumber;
Vishnu Nair63221212023-04-06 15:17:37 -07003269 mDrawingState.barrierFrameNumber =
3270 std::max(mDrawingState.frameNumber, mDrawingState.barrierFrameNumber);
3271
Patrick Williamsbb25f802022-08-30 23:02:34 +00003272 mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
3273 mDrawingState.buffer = std::move(buffer);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003274 mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
3275 ? bufferData.acquireFence
3276 : Fence::NO_FENCE;
3277 mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
3278 if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
3279 // We latched this buffer unsiganled, so we need to pass the acquire fence
3280 // on the callback instead of just the acquire time, since it's unknown at
3281 // this point.
3282 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
3283 } else {
3284 mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
3285 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003286 setTransactionFlags(eTransactionNeeded);
3287
3288 const int32_t layerId = getSequence();
3289 mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
3290 mOwnerUid, postTime, getGameMode());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003291
Lloyd Pique30db6402023-06-26 18:56:51 +00003292 if (mFlinger->mLegacyFrontEndEnabled) {
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003293 recordLayerHistoryBufferUpdate(getLayerProps(), systemTime());
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003294 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003295
3296 setFrameTimelineVsyncForBufferTransaction(info, postTime);
3297
3298 if (dequeueTime && *dequeueTime != 0) {
3299 const uint64_t bufferId = mDrawingState.buffer->getId();
3300 mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
3301 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
3302 FrameTracer::FrameEvent::DEQUEUE);
3303 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
3304 FrameTracer::FrameEvent::QUEUE);
3305 }
3306
3307 mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
Arthur Hungc70bee22023-06-02 01:35:52 +00003308
3309 // If the layer had been updated a TextureView, this would make sure the present time could be
3310 // same to TextureView update when it's a small dirty, and get the correct heuristic rate.
Jerry Chang36678002023-11-29 16:56:17 +00003311 if (mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +00003312 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
3313 mUsedVsyncIdForRefreshRateSelection = true;
3314 }
3315 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003316 return true;
3317}
3318
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003319void Layer::setDesiredPresentTime(nsecs_t desiredPresentTime, bool isAutoTimestamp) {
3320 mDrawingState.desiredPresentTime = desiredPresentTime;
3321 mDrawingState.isAutoTimestamp = isAutoTimestamp;
3322}
3323
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003324void Layer::recordLayerHistoryBufferUpdate(const scheduler::LayerProps& layerProps, nsecs_t now) {
Ady Abraham55269162023-05-09 11:26:06 -07003325 ATRACE_CALL();
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003326 const nsecs_t presentTime = [&] {
Ady Abraham55269162023-05-09 11:26:06 -07003327 if (!mDrawingState.isAutoTimestamp) {
3328 ATRACE_FORMAT_INSTANT("desiredPresentTime");
3329 return mDrawingState.desiredPresentTime;
3330 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003331
Ady Abraham55269162023-05-09 11:26:06 -07003332 if (mDrawingState.useVsyncIdForRefreshRateSelection) {
3333 const auto prediction =
3334 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3335 mDrawingState.latchedVsyncId);
3336 if (prediction.has_value()) {
3337 ATRACE_FORMAT_INSTANT("predictedPresentTime");
Arthur Hungc70bee22023-06-02 01:35:52 +00003338 mMaxTimeForUseVsyncId = prediction->presentTime +
3339 scheduler::LayerHistory::kMaxPeriodForHistory.count();
Ady Abraham55269162023-05-09 11:26:06 -07003340 return prediction->presentTime;
3341 }
3342 }
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003343
Jerry Chang36678002023-11-29 16:56:17 +00003344 if (!mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +00003345 return static_cast<nsecs_t>(0);
3346 }
3347
3348 // If the layer is not an application and didn't set an explicit rate or desiredPresentTime,
3349 // return "0" to tell the layer history that it will use the max refresh rate without
3350 // calculating the adaptive rate.
3351 if (mWindowType != WindowInfo::Type::APPLICATION &&
3352 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
3353 return static_cast<nsecs_t>(0);
3354 }
3355
3356 // Return the valid present time only when the layer potentially updated a TextureView so
3357 // LayerHistory could heuristically calculate the rate if the UI is continually updating.
3358 if (mUsedVsyncIdForRefreshRateSelection) {
3359 const auto prediction =
3360 mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(
3361 mDrawingState.latchedVsyncId);
3362 if (prediction.has_value()) {
3363 if (mMaxTimeForUseVsyncId >= prediction->presentTime) {
3364 return prediction->presentTime;
3365 }
3366 mUsedVsyncIdForRefreshRateSelection = false;
3367 }
3368 }
3369
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003370 return static_cast<nsecs_t>(0);
3371 }();
Ady Abraham55269162023-05-09 11:26:06 -07003372
3373 if (ATRACE_ENABLED() && presentTime > 0) {
3374 const auto presentIn = TimePoint::fromNs(presentTime) - TimePoint::now();
3375 ATRACE_FORMAT_INSTANT("presentIn %s", to_string(presentIn).c_str());
3376 }
3377
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003378 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003379 scheduler::LayerHistory::LayerUpdateType::Buffer);
3380}
3381
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003382void Layer::recordLayerHistoryAnimationTx(const scheduler::LayerProps& layerProps, nsecs_t now) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003383 const nsecs_t presentTime =
3384 mDrawingState.isAutoTimestamp ? 0 : mDrawingState.desiredPresentTime;
Vishnu Nair47b7bb42023-09-29 16:27:33 -07003385 mFlinger->mScheduler->recordLayerHistory(sequence, layerProps, presentTime, now,
Vishnu Nairef68d6d2023-02-28 06:18:27 +00003386 scheduler::LayerHistory::LayerUpdateType::AnimationTX);
3387}
3388
Patrick Williamsbb25f802022-08-30 23:02:34 +00003389bool Layer::setDataspace(ui::Dataspace dataspace) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003390 if (mDrawingState.dataspace == dataspace) return false;
3391 mDrawingState.dataspace = dataspace;
3392 mDrawingState.modified = true;
3393 setTransactionFlags(eTransactionNeeded);
3394 return true;
3395}
3396
John Reck68796592023-01-25 13:47:12 -05003397bool Layer::setExtendedRangeBrightness(float currentBufferRatio, float desiredRatio) {
Sally Qi963049b2023-03-23 14:06:21 -07003398 if (mDrawingState.currentHdrSdrRatio == currentBufferRatio &&
3399 mDrawingState.desiredHdrSdrRatio == desiredRatio)
John Reck68796592023-01-25 13:47:12 -05003400 return false;
Sally Qi963049b2023-03-23 14:06:21 -07003401 mDrawingState.currentHdrSdrRatio = currentBufferRatio;
3402 mDrawingState.desiredHdrSdrRatio = desiredRatio;
John Reck68796592023-01-25 13:47:12 -05003403 mDrawingState.modified = true;
3404 setTransactionFlags(eTransactionNeeded);
3405 return true;
3406}
3407
Alec Mouri1b0d4e12024-02-12 22:27:19 +00003408bool Layer::setDesiredHdrHeadroom(float desiredRatio) {
3409 if (mDrawingState.desiredHdrSdrRatio == desiredRatio) return false;
3410 mDrawingState.desiredHdrSdrRatio = desiredRatio;
3411 mDrawingState.modified = true;
3412 setTransactionFlags(eTransactionNeeded);
3413 return true;
3414}
3415
Alec Mourif4af03e2023-02-11 00:25:24 +00003416bool Layer::setCachingHint(gui::CachingHint cachingHint) {
3417 if (mDrawingState.cachingHint == cachingHint) return false;
3418 mDrawingState.cachingHint = cachingHint;
3419 mDrawingState.modified = true;
3420 setTransactionFlags(eTransactionNeeded);
3421 return true;
3422}
3423
Patrick Williamsbb25f802022-08-30 23:02:34 +00003424bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
3425 if (mDrawingState.hdrMetadata == hdrMetadata) return false;
3426 mDrawingState.hdrMetadata = hdrMetadata;
3427 mDrawingState.modified = true;
3428 setTransactionFlags(eTransactionNeeded);
3429 return true;
3430}
3431
3432bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
Sally Qi2b1b4292023-03-14 16:47:39 +00003433 if (mDrawingState.surfaceDamageRegion.hasSameRects(surfaceDamage)) return false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003434 mDrawingState.surfaceDamageRegion = surfaceDamage;
3435 mDrawingState.modified = true;
3436 setTransactionFlags(eTransactionNeeded);
Arthur Hung69f95222023-10-04 07:39:02 +00003437 setIsSmallDirty(surfaceDamage, getTransform());
Patrick Williamsbb25f802022-08-30 23:02:34 +00003438 return true;
3439}
3440
3441bool Layer::setApi(int32_t api) {
3442 if (mDrawingState.api == api) return false;
3443 mDrawingState.api = api;
3444 mDrawingState.modified = true;
3445 setTransactionFlags(eTransactionNeeded);
3446 return true;
3447}
3448
Dorin Drimuse5374e52023-08-02 17:52:43 +00003449bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream, const FrameTimelineInfo& info,
3450 nsecs_t postTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003451 if (mDrawingState.sidebandStream == sidebandStream) return false;
3452
3453 if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
3454 mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
3455 } else if (sidebandStream != nullptr) {
3456 mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
3457 }
3458
3459 mDrawingState.sidebandStream = sidebandStream;
3460 mDrawingState.modified = true;
Dorin Drimuse5374e52023-08-02 17:52:43 +00003461 if (sidebandStream != nullptr && mDrawingState.buffer != nullptr) {
3462 releasePreviousBuffer();
3463 resetDrawingStateBufferInfo();
3464 mDrawingState.bufferSurfaceFrameTX = nullptr;
3465 setFrameTimelineVsyncForBufferlessTransaction(info, postTime);
3466 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003467 setTransactionFlags(eTransactionNeeded);
3468 if (!mSidebandStreamChanged.exchange(true)) {
3469 // mSidebandStreamChanged was false
3470 mFlinger->onLayerUpdate();
3471 }
3472 return true;
3473}
3474
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003475bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles,
3476 bool willPresent) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003477 // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
3478 if (handles.empty()) {
3479 mReleasePreviousBuffer = false;
3480 return false;
3481 }
3482
Pascal Muetschard81cef292023-02-06 12:18:52 +01003483 std::deque<sp<CallbackHandle>> remainingHandles;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003484 for (const auto& handle : handles) {
3485 // If this transaction set a buffer on this layer, release its previous buffer
3486 handle->releasePreviousBuffer = mReleasePreviousBuffer;
3487
3488 // If this layer will be presented in this frame
3489 if (willPresent) {
3490 // If this transaction set an acquire fence on this layer, set its acquire time
3491 handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
3492 handle->frameNumber = mDrawingState.frameNumber;
Alec Mouri21d94322023-10-17 19:51:39 +00003493 handle->previousFrameNumber = mDrawingState.previousFrameNumber;
Melody Hsu793f8362024-01-08 20:00:35 +00003494 if (FlagManager::getInstance().ce_fence_promise() &&
Alec Mouri9892aac2023-12-11 21:16:59 +00003495 mPreviousReleaseBufferEndpoint == handle->listener) {
Melody Hsue4ef87f2024-03-26 23:54:45 +00003496 // Add fence from previous screenshot now so that it can be dispatched to the
Alec Mouri9892aac2023-12-11 21:16:59 +00003497 // client.
Melody Hsue4ef87f2024-03-26 23:54:45 +00003498 for (auto& [_, future] : mAdditionalPreviousReleaseFences) {
3499 handle->previousReleaseFences.emplace_back(std::move(future));
Alec Mouri9892aac2023-12-11 21:16:59 +00003500 }
3501 mAdditionalPreviousReleaseFences.clear();
Melody Hsu793f8362024-01-08 20:00:35 +00003502 } else if (FlagManager::getInstance().screenshot_fence_preservation() &&
3503 mPreviousReleaseBufferEndpoint == handle->listener) {
3504 // Add fences from previous screenshots now so that they can be dispatched to the
3505 // client.
3506 for (const auto& futureAndContinution : mPreviousReleaseFenceAndContinuations) {
3507 handle->previousSharedReleaseFences.emplace_back(futureAndContinution.chain());
3508 }
3509 mPreviousReleaseFenceAndContinuations.clear();
Alec Mouri9892aac2023-12-11 21:16:59 +00003510 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003511 // Store so latched time and release fence can be set
3512 mDrawingState.callbackHandles.push_back(handle);
3513
3514 } else { // If this layer will NOT need to be relatched and presented this frame
Pascal Muetschard81cef292023-02-06 12:18:52 +01003515 // Queue this handle to be notified below.
3516 remainingHandles.push_back(handle);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003517 }
3518 }
3519
Pascal Muetschard81cef292023-02-06 12:18:52 +01003520 if (!remainingHandles.empty()) {
3521 // Notify the transaction completed threads these handles are done. These are only the
3522 // handles that were not added to the mDrawingState, which will be notified later.
3523 std::vector<JankData> jankData;
3524 transferAvailableJankData(remainingHandles, jankData);
3525 mFlinger->getTransactionCallbackInvoker().addCallbackHandles(remainingHandles, jankData);
3526 }
3527
Patrick Williamsbb25f802022-08-30 23:02:34 +00003528 mReleasePreviousBuffer = false;
3529 mCallbackHandleAcquireTimeOrFence = -1;
3530
3531 return willPresent;
3532}
3533
3534Rect Layer::getBufferSize(const State& /*s*/) const {
3535 // for buffer state layers we use the display frame size as the buffer size.
3536
3537 if (mBufferInfo.mBuffer == nullptr) {
3538 return Rect::INVALID_RECT;
3539 }
3540
3541 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
3542 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
3543
3544 // Undo any transformations on the buffer and return the result.
3545 if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
3546 std::swap(bufWidth, bufHeight);
3547 }
3548
3549 if (getTransformToDisplayInverse()) {
Leon Scroggins III85d4b222023-05-09 13:58:18 -04003550 uint32_t invTransform = SurfaceFlinger::getActiveDisplayRotationFlags();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003551 if (invTransform & ui::Transform::ROT_90) {
3552 std::swap(bufWidth, bufHeight);
3553 }
3554 }
3555
3556 return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
3557}
3558
3559FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
3560 if (mBufferInfo.mBuffer == nullptr) {
3561 return parentBounds;
3562 }
3563
3564 return getBufferSize(getDrawingState()).toFloatRect();
3565}
3566
3567bool Layer::fenceHasSignaled() const {
3568 if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
3569 return true;
3570 }
3571
3572 const bool fenceSignaled =
3573 getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
3574 if (!fenceSignaled) {
3575 mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
3576 TimeStats::LatchSkipReason::LateAcquire);
3577 }
3578
3579 return fenceSignaled;
3580}
3581
Vishnu Nair3af0ec02023-02-10 04:13:48 +00003582void Layer::onPreComposition(nsecs_t refreshStartTime) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003583 for (const auto& handle : mDrawingState.callbackHandles) {
3584 handle->refreshStartTime = refreshStartTime;
3585 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003586}
3587
3588void Layer::setAutoRefresh(bool autoRefresh) {
3589 mDrawingState.autoRefresh = autoRefresh;
3590}
3591
3592bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
3593 // 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 +00003594 auto* snapshot = editLayerSnapshot();
3595 snapshot->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00003596
3597 if (mSidebandStreamChanged.exchange(false)) {
3598 const State& s(getDrawingState());
3599 // mSidebandStreamChanged was true
3600 mSidebandStream = s.sidebandStream;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00003601 snapshot->sidebandStream = mSidebandStream;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003602 if (mSidebandStream != nullptr) {
3603 setTransactionFlags(eTransactionNeeded);
3604 mFlinger->setTransactionFlags(eTraversalNeeded);
3605 }
3606 recomputeVisibleRegions = true;
3607
3608 return true;
3609 }
3610 return false;
3611}
3612
3613bool Layer::hasFrameUpdate() const {
3614 const State& c(getDrawingState());
3615 return (mDrawingStateModified || mDrawingState.modified) &&
3616 (c.buffer != nullptr || c.bgColorLayer != nullptr);
3617}
3618
Vishnu Naird47bcee2023-02-24 18:08:51 +00003619void Layer::updateTexImage(nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003620 const State& s(getDrawingState());
3621
3622 if (!s.buffer) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003623 if (bgColorOnly || mBufferInfo.mBuffer) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003624 for (auto& handle : mDrawingState.callbackHandles) {
3625 handle->latchTime = latchTime;
3626 }
3627 }
3628 return;
3629 }
3630
3631 for (auto& handle : mDrawingState.callbackHandles) {
3632 if (handle->frameNumber == mDrawingState.frameNumber) {
3633 handle->latchTime = latchTime;
3634 }
3635 }
3636
3637 const int32_t layerId = getSequence();
3638 const uint64_t bufferId = mDrawingState.buffer->getId();
3639 const uint64_t frameNumber = mDrawingState.frameNumber;
3640 const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3641 mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
3642 mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
3643
3644 mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
3645 FrameTracer::FrameEvent::ACQUIRE_FENCE);
3646 mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
3647 FrameTracer::FrameEvent::LATCH);
3648
3649 auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
3650 if (bufferSurfaceFrame != nullptr &&
3651 bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
3652 // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
3653 // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
3654 // are processing the next state.
3655 addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
3656 mDrawingState.acquireFenceTime->getSignalTime(),
3657 latchTime);
3658 mDrawingState.bufferSurfaceFrameTX.reset();
3659 }
3660
3661 std::deque<sp<CallbackHandle>> remainingHandles;
3662 mFlinger->getTransactionCallbackInvoker()
3663 .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
3664 mDrawingState.callbackHandles = remainingHandles;
3665
3666 mDrawingStateModified = false;
3667}
3668
3669void Layer::gatherBufferInfo() {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003670 mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
3671 mPreviousReleaseBufferEndpoint = mBufferInfo.mReleaseBufferEndpoint;
3672 if (!mDrawingState.buffer) {
3673 mBufferInfo = {};
3674 return;
3675 }
3676
3677 if ((!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer))) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003678 decrementPendingBufferCount();
3679 }
3680
Patrick Williamsbb25f802022-08-30 23:02:34 +00003681 mBufferInfo.mBuffer = mDrawingState.buffer;
Vishnu Nair7ee4f462023-04-19 09:54:09 -07003682 mBufferInfo.mReleaseBufferEndpoint = mDrawingState.releaseBufferEndpoint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003683 mBufferInfo.mFence = mDrawingState.acquireFence;
3684 mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
3685 mBufferInfo.mPixelFormat =
3686 !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
3687 mBufferInfo.mFrameLatencyNeeded = true;
3688 mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
3689 mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
3690 mBufferInfo.mFence = mDrawingState.acquireFence;
3691 mBufferInfo.mTransform = mDrawingState.bufferTransform;
3692 auto lastDataspace = mBufferInfo.mDataspace;
3693 mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
Alec Mouri74c7ae12023-03-26 02:57:47 +00003694 if (mBufferInfo.mBuffer != nullptr) {
3695 auto& mapper = GraphicBufferMapper::get();
3696 // TODO: We should measure if it's faster to do a blind write if we're on newer api levels
3697 // and don't need to possibly remaps buffers.
3698 ui::Dataspace dataspace = ui::Dataspace::UNKNOWN;
3699 status_t err = OK;
3700 {
3701 ATRACE_NAME("getDataspace");
3702 err = mapper.getDataspace(mBufferInfo.mBuffer->getBuffer()->handle, &dataspace);
3703 }
3704 if (err != OK || dataspace != mBufferInfo.mDataspace) {
3705 {
3706 ATRACE_NAME("setDataspace");
3707 err = mapper.setDataspace(mBufferInfo.mBuffer->getBuffer()->handle,
3708 static_cast<ui::Dataspace>(mBufferInfo.mDataspace));
3709 }
3710
3711 // Some GPU drivers may cache gralloc metadata which means before we composite we need
3712 // to upsert RenderEngine's caches. Put in a special workaround to be backwards
3713 // compatible with old vendors, with a ticking clock.
3714 static const int32_t kVendorVersion =
Alec Mouri8a06fb72023-11-16 22:07:13 +00003715 base::GetIntProperty("ro.board.api_level", __ANDROID_API_FUTURE__);
Alec Mouri74c7ae12023-03-26 02:57:47 +00003716 if (const auto format =
3717 static_cast<aidl::android::hardware::graphics::common::PixelFormat>(
3718 mBufferInfo.mBuffer->getPixelFormat());
3719 err == OK && kVendorVersion < __ANDROID_API_U__ &&
3720 (format ==
3721 aidl::android::hardware::graphics::common::PixelFormat::
3722 IMPLEMENTATION_DEFINED ||
3723 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_420_888 ||
3724 format == aidl::android::hardware::graphics::common::PixelFormat::YV12 ||
3725 format == aidl::android::hardware::graphics::common::PixelFormat::YCBCR_P010)) {
3726 mBufferInfo.mBuffer->remapBuffer();
3727 }
3728 }
3729 }
Patrick Williamsbb25f802022-08-30 23:02:34 +00003730 if (lastDataspace != mBufferInfo.mDataspace) {
John Reck68796592023-01-25 13:47:12 -05003731 mFlinger->mHdrLayerInfoChanged = true;
3732 }
Sally Qi963049b2023-03-23 14:06:21 -07003733 if (mBufferInfo.mDesiredHdrSdrRatio != mDrawingState.desiredHdrSdrRatio) {
3734 mBufferInfo.mDesiredHdrSdrRatio = mDrawingState.desiredHdrSdrRatio;
John Reck68796592023-01-25 13:47:12 -05003735 mFlinger->mHdrLayerInfoChanged = true;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003736 }
3737 mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
3738 mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
3739 mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
3740 mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
3741 mBufferInfo.mApi = mDrawingState.api;
3742 mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
Patrick Williamsbb25f802022-08-30 23:02:34 +00003743}
3744
3745Rect Layer::computeBufferCrop(const State& s) {
3746 if (s.buffer && !s.bufferCrop.isEmpty()) {
3747 Rect bufferCrop;
3748 s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
3749 return bufferCrop;
3750 } else if (s.buffer) {
3751 return s.buffer->getBounds();
3752 } else {
3753 return s.bufferCrop;
3754 }
3755}
3756
Vishnu Nairde177252023-04-21 12:44:10 -07003757sp<Layer> Layer::createClone(uint32_t mirrorRootId) {
Kean Mariotti4ba343c2023-04-19 13:31:02 +00003758 surfaceflinger::LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0,
3759 LayerMetadata());
Patrick Williams83f36b22022-09-14 17:57:35 +00003760 sp<Layer> layer = mFlinger->getFactory().createBufferStateLayer(args);
Vishnu Nairde177252023-04-21 12:44:10 -07003761 layer->setInitialValuesForClone(sp<Layer>::fromExisting(this), mirrorRootId);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003762 return layer;
3763}
3764
Patrick Williamsbb25f802022-08-30 23:02:34 +00003765void Layer::decrementPendingBufferCount() {
3766 int32_t pendingBuffers = --mPendingBufferTransactions;
3767 tracePendingBufferCount(pendingBuffers);
3768}
3769
3770void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
3771 ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
3772}
3773
3774/*
3775 * We don't want to send the layer's transform to input, but rather the
3776 * parent's transform. This is because Layer's transform is
3777 * information about how the buffer is placed on screen. The parent's
3778 * transform makes more sense to send since it's information about how the
3779 * layer is placed on screen. This transform is used by input to determine
3780 * how to go from screen space back to window space.
3781 */
3782ui::Transform Layer::getInputTransform() const {
3783 if (!hasBufferOrSidebandStream()) {
3784 return getTransform();
3785 }
3786 sp<Layer> parent = mDrawingParent.promote();
3787 if (parent == nullptr) {
3788 return ui::Transform();
3789 }
3790
3791 return parent->getTransform();
3792}
3793
3794/**
Vishnu Nairfed7c122023-03-18 01:54:43 +00003795 * Returns the bounds used to fill the input frame and the touchable region.
3796 *
Patrick Williamsbb25f802022-08-30 23:02:34 +00003797 * Similar to getInputTransform, we need to update the bounds to include the transform.
3798 * This is because bounds don't include the buffer transform, where the input assumes
3799 * that's already included.
3800 */
Vishnu Nairfed7c122023-03-18 01:54:43 +00003801std::pair<FloatRect, bool> Layer::getInputBounds(bool fillParentBounds) const {
3802 Rect croppedBufferSize = getCroppedBufferSize(getDrawingState());
3803 FloatRect inputBounds = croppedBufferSize.toFloatRect();
3804 if (hasBufferOrSidebandStream() && croppedBufferSize.isValid() &&
3805 mDrawingState.transform.getType() != ui::Transform::IDENTITY) {
3806 inputBounds = mDrawingState.transform.transform(inputBounds);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003807 }
3808
Vishnu Nairfed7c122023-03-18 01:54:43 +00003809 bool inputBoundsValid = croppedBufferSize.isValid();
3810 if (!inputBoundsValid) {
3811 /**
3812 * Input bounds are based on the layer crop or buffer size. But if we are using
3813 * the layer bounds as the input bounds (replaceTouchableRegionWithCrop flag) then
3814 * we can use the parent bounds as the input bounds if the layer does not have buffer
3815 * or a crop. We want to unify this logic but because of compat reasons we cannot always
3816 * use the parent bounds. A layer without a buffer can get input. So when a window is
3817 * initially added, its touchable region can fill its parent layer bounds and that can
3818 * have negative consequences.
3819 */
3820 inputBounds = fillParentBounds ? mBounds : FloatRect{};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003821 }
Vishnu Nairfed7c122023-03-18 01:54:43 +00003822
3823 // Clamp surface inset to the input bounds.
3824 const float inset = static_cast<float>(mDrawingState.inputInfo.surfaceInset);
3825 const float xSurfaceInset = std::clamp(inset, 0.f, inputBounds.getWidth() / 2.f);
3826 const float ySurfaceInset = std::clamp(inset, 0.f, inputBounds.getHeight() / 2.f);
3827
3828 // Apply the insets to the input bounds.
3829 inputBounds.left += xSurfaceInset;
3830 inputBounds.top += ySurfaceInset;
3831 inputBounds.right -= xSurfaceInset;
3832 inputBounds.bottom -= ySurfaceInset;
3833
3834 return {inputBounds, inputBoundsValid};
Patrick Williamsbb25f802022-08-30 23:02:34 +00003835}
3836
Ady Abraham005398b2023-06-05 13:59:41 -07003837bool Layer::isSimpleBufferUpdate(const layer_state_t& s) const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00003838 const uint64_t requiredFlags = layer_state_t::eBufferChanged;
3839
3840 const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
3841 layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
3842 layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
3843 layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
3844 layer_state_t::eReparent;
3845
Patrick Williamsbb25f802022-08-30 23:02:34 +00003846 if ((s.what & requiredFlags) != requiredFlags) {
Ady Abraham005398b2023-06-05 13:59:41 -07003847 ATRACE_FORMAT_INSTANT("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
3848 (s.what | requiredFlags) & ~s.what);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003849 return false;
3850 }
3851
3852 if (s.what & deniedFlags) {
Ady Abraham005398b2023-06-05 13:59:41 -07003853 ATRACE_FORMAT_INSTANT("%s: false [has denied flags 0x%" PRIx64 "]", __func__,
3854 s.what & deniedFlags);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003855 return false;
3856 }
3857
Patrick Williamsbb25f802022-08-30 23:02:34 +00003858 if (s.what & layer_state_t::ePositionChanged) {
3859 if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
Ady Abraham005398b2023-06-05 13:59:41 -07003860 ATRACE_FORMAT_INSTANT("%s: false [ePositionChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003861 return false;
3862 }
3863 }
3864
3865 if (s.what & layer_state_t::eAlphaChanged) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00003866 if (mDrawingState.color.a != s.color.a) {
Ady Abraham005398b2023-06-05 13:59:41 -07003867 ATRACE_FORMAT_INSTANT("%s: false [eAlphaChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003868 return false;
3869 }
3870 }
3871
3872 if (s.what & layer_state_t::eColorTransformChanged) {
3873 if (mDrawingState.colorTransform != s.colorTransform) {
Ady Abraham005398b2023-06-05 13:59:41 -07003874 ATRACE_FORMAT_INSTANT("%s: false [eColorTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003875 return false;
3876 }
3877 }
3878
3879 if (s.what & layer_state_t::eBackgroundColorChanged) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00003880 if (mDrawingState.bgColorLayer || s.bgColor.a != 0) {
Ady Abraham005398b2023-06-05 13:59:41 -07003881 ATRACE_FORMAT_INSTANT("%s: false [eBackgroundColorChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003882 return false;
3883 }
3884 }
3885
3886 if (s.what & layer_state_t::eMatrixChanged) {
3887 if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
3888 mRequestedTransform.dtdy() != s.matrix.dtdy ||
3889 mRequestedTransform.dtdx() != s.matrix.dtdx ||
3890 mRequestedTransform.dsdy() != s.matrix.dsdy) {
Ady Abraham005398b2023-06-05 13:59:41 -07003891 ATRACE_FORMAT_INSTANT("%s: false [eMatrixChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003892 return false;
3893 }
3894 }
3895
3896 if (s.what & layer_state_t::eCornerRadiusChanged) {
3897 if (mDrawingState.cornerRadius != s.cornerRadius) {
Ady Abraham005398b2023-06-05 13:59:41 -07003898 ATRACE_FORMAT_INSTANT("%s: false [eCornerRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003899 return false;
3900 }
3901 }
3902
3903 if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
3904 if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
Ady Abraham005398b2023-06-05 13:59:41 -07003905 ATRACE_FORMAT_INSTANT("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003906 return false;
3907 }
3908 }
3909
Vishnu Nairbbceb462022-10-10 04:52:13 +00003910 if (s.what & layer_state_t::eBufferTransformChanged) {
3911 if (mDrawingState.bufferTransform != s.bufferTransform) {
Ady Abraham005398b2023-06-05 13:59:41 -07003912 ATRACE_FORMAT_INSTANT("%s: false [eBufferTransformChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003913 return false;
3914 }
3915 }
3916
3917 if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
3918 if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
Ady Abraham005398b2023-06-05 13:59:41 -07003919 ATRACE_FORMAT_INSTANT("%s: false [eTransformToDisplayInverseChanged changed]",
3920 __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003921 return false;
3922 }
3923 }
3924
3925 if (s.what & layer_state_t::eCropChanged) {
3926 if (mDrawingState.crop != s.crop) {
Ady Abraham005398b2023-06-05 13:59:41 -07003927 ATRACE_FORMAT_INSTANT("%s: false [eCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003928 return false;
3929 }
3930 }
3931
3932 if (s.what & layer_state_t::eDataspaceChanged) {
3933 if (mDrawingState.dataspace != s.dataspace) {
Ady Abraham005398b2023-06-05 13:59:41 -07003934 ATRACE_FORMAT_INSTANT("%s: false [eDataspaceChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003935 return false;
3936 }
3937 }
3938
3939 if (s.what & layer_state_t::eHdrMetadataChanged) {
3940 if (mDrawingState.hdrMetadata != s.hdrMetadata) {
Ady Abraham005398b2023-06-05 13:59:41 -07003941 ATRACE_FORMAT_INSTANT("%s: false [eHdrMetadataChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003942 return false;
3943 }
3944 }
3945
3946 if (s.what & layer_state_t::eSidebandStreamChanged) {
3947 if (mDrawingState.sidebandStream != s.sidebandStream) {
Ady Abraham005398b2023-06-05 13:59:41 -07003948 ATRACE_FORMAT_INSTANT("%s: false [eSidebandStreamChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003949 return false;
3950 }
3951 }
3952
3953 if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
3954 if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
Ady Abraham005398b2023-06-05 13:59:41 -07003955 ATRACE_FORMAT_INSTANT("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003956 return false;
3957 }
3958 }
3959
3960 if (s.what & layer_state_t::eShadowRadiusChanged) {
3961 if (mDrawingState.shadowRadius != s.shadowRadius) {
Ady Abraham005398b2023-06-05 13:59:41 -07003962 ATRACE_FORMAT_INSTANT("%s: false [eShadowRadiusChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003963 return false;
3964 }
3965 }
3966
3967 if (s.what & layer_state_t::eFixedTransformHintChanged) {
3968 if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
Ady Abraham005398b2023-06-05 13:59:41 -07003969 ATRACE_FORMAT_INSTANT("%s: false [eFixedTransformHintChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003970 return false;
3971 }
3972 }
3973
3974 if (s.what & layer_state_t::eTrustedOverlayChanged) {
3975 if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
Ady Abraham005398b2023-06-05 13:59:41 -07003976 ATRACE_FORMAT_INSTANT("%s: false [eTrustedOverlayChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003977 return false;
3978 }
3979 }
3980
3981 if (s.what & layer_state_t::eStretchChanged) {
3982 StretchEffect temp = s.stretchEffect;
3983 temp.sanitize();
3984 if (mDrawingState.stretchEffect != temp) {
Ady Abraham005398b2023-06-05 13:59:41 -07003985 ATRACE_FORMAT_INSTANT("%s: false [eStretchChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003986 return false;
3987 }
3988 }
3989
3990 if (s.what & layer_state_t::eBufferCropChanged) {
3991 if (mDrawingState.bufferCrop != s.bufferCrop) {
Ady Abraham005398b2023-06-05 13:59:41 -07003992 ATRACE_FORMAT_INSTANT("%s: false [eBufferCropChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00003993 return false;
3994 }
3995 }
3996
3997 if (s.what & layer_state_t::eDestinationFrameChanged) {
3998 if (mDrawingState.destinationFrame != s.destinationFrame) {
Ady Abraham005398b2023-06-05 13:59:41 -07003999 ATRACE_FORMAT_INSTANT("%s: false [eDestinationFrameChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00004000 return false;
4001 }
4002 }
4003
4004 if (s.what & layer_state_t::eDimmingEnabledChanged) {
4005 if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
Ady Abraham005398b2023-06-05 13:59:41 -07004006 ATRACE_FORMAT_INSTANT("%s: false [eDimmingEnabledChanged changed]", __func__);
Patrick Williamsbb25f802022-08-30 23:02:34 +00004007 return false;
4008 }
4009 }
4010
John Reck68796592023-01-25 13:47:12 -05004011 if (s.what & layer_state_t::eExtendedRangeBrightnessChanged) {
Sally Qi963049b2023-03-23 14:06:21 -07004012 if (mDrawingState.currentHdrSdrRatio != s.currentHdrSdrRatio ||
4013 mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
Ady Abraham005398b2023-06-05 13:59:41 -07004014 ATRACE_FORMAT_INSTANT("%s: false [eExtendedRangeBrightnessChanged changed]", __func__);
John Reck68796592023-01-25 13:47:12 -05004015 return false;
4016 }
4017 }
4018
Alec Mouri1b0d4e12024-02-12 22:27:19 +00004019 if (s.what & layer_state_t::eDesiredHdrHeadroomChanged) {
4020 if (mDrawingState.desiredHdrSdrRatio != s.desiredHdrSdrRatio) {
4021 ATRACE_FORMAT_INSTANT("%s: false [eDesiredHdrHeadroomChanged changed]", __func__);
4022 return false;
4023 }
4024 }
4025
Patrick Williamsbb25f802022-08-30 23:02:34 +00004026 return true;
4027}
4028
Vishnu Naire14c6b32022-08-06 04:20:15 +00004029sp<LayerFE> Layer::getCompositionEngineLayerFE() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004030 // 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 +00004031 return hasSomethingToDraw() ? mLegacyLayerFE : nullptr;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004032}
4033
Vishnu Naire14c6b32022-08-06 04:20:15 +00004034const LayerSnapshot* Layer::getLayerSnapshot() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004035 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00004036}
4037
Vishnu Naire14c6b32022-08-06 04:20:15 +00004038LayerSnapshot* Layer::editLayerSnapshot() {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004039 return mSnapshot.get();
4040}
Vishnu Naire14c6b32022-08-06 04:20:15 +00004041
Vishnu Nair3af0ec02023-02-10 04:13:48 +00004042std::unique_ptr<frontend::LayerSnapshot> Layer::stealLayerSnapshot() {
4043 return std::move(mSnapshot);
4044}
4045
4046void Layer::updateLayerSnapshot(std::unique_ptr<frontend::LayerSnapshot> snapshot) {
4047 mSnapshot = std::move(snapshot);
4048}
4049
Patrick Williamsbb25f802022-08-30 23:02:34 +00004050const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004051 return mSnapshot.get();
Patrick Williamsbb25f802022-08-30 23:02:34 +00004052}
4053
Patrick Williams7584c6a2022-10-29 02:10:58 +00004054sp<LayerFE> Layer::copyCompositionEngineLayerFE() const {
Vishnu Nair3af0ec02023-02-10 04:13:48 +00004055 auto result = mFlinger->getFactory().createLayerFE(mName);
Patrick Williams7584c6a2022-10-29 02:10:58 +00004056 result->mSnapshot = std::make_unique<LayerSnapshot>(*mSnapshot);
4057 return result;
4058}
4059
Vishnu Nair3af0ec02023-02-10 04:13:48 +00004060sp<LayerFE> Layer::getCompositionEngineLayerFE(
4061 const frontend::LayerHierarchy::TraversalPath& path) {
4062 for (auto& [p, layerFE] : mLayerFEs) {
4063 if (p == path) {
4064 return layerFE;
4065 }
4066 }
4067 auto layerFE = mFlinger->getFactory().createLayerFE(mName);
4068 mLayerFEs.emplace_back(path, layerFE);
4069 return layerFE;
4070}
4071
Patrick Williamsbb25f802022-08-30 23:02:34 +00004072void Layer::useSurfaceDamage() {
4073 if (mFlinger->mForceFullDamage) {
4074 surfaceDamageRegion = Region::INVALID_REGION;
4075 } else {
4076 surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
4077 }
4078}
4079
4080void Layer::useEmptyDamage() {
4081 surfaceDamageRegion.clear();
4082}
4083
4084bool Layer::isOpaque(const Layer::State& s) const {
4085 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
4086 // layer's opaque flag.
4087 if (!hasSomethingToDraw()) {
4088 return false;
4089 }
4090
4091 // if the layer has the opaque flag, then we're always opaque
4092 if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
4093 return true;
4094 }
4095
4096 // If the buffer has no alpha channel, then we are opaque
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004097 if (hasBufferOrSidebandStream() && LayerSnapshot::isOpaqueFormat(getPixelFormat())) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004098 return true;
4099 }
4100
4101 // Lastly consider the layer opaque if drawing a color with alpha == 1.0
4102 return fillsColor() && getAlpha() == 1.0_hf;
4103}
4104
4105bool Layer::canReceiveInput() const {
4106 return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
4107}
4108
4109bool Layer::isVisible() const {
4110 if (!hasSomethingToDraw()) {
4111 return false;
4112 }
4113
4114 if (isHiddenByPolicy()) {
4115 return false;
4116 }
4117
4118 return getAlpha() > 0.0f || hasBlur();
4119}
4120
Leon Scroggins III5b581492023-10-31 14:29:41 -04004121void Layer::onCompositionPresented(const DisplayDevice* display,
4122 const std::shared_ptr<FenceTime>& glDoneFence,
4123 const std::shared_ptr<FenceTime>& presentFence,
4124 const CompositorTiming& compositorTiming) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004125 // mFrameLatencyNeeded is true when a new frame was latched for the
4126 // composition.
4127 if (!mBufferInfo.mFrameLatencyNeeded) return;
4128
4129 for (const auto& handle : mDrawingState.callbackHandles) {
4130 handle->gpuCompositionDoneFence = glDoneFence;
4131 handle->compositorTiming = compositorTiming;
4132 }
4133
4134 // Update mFrameTracker.
4135 nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
4136 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
4137
4138 const int32_t layerId = getSequence();
4139 mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
4140
4141 const auto outputLayer = findOutputLayerForDisplay(display);
4142 if (outputLayer && outputLayer->requiresClientComposition()) {
4143 nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
4144 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
4145 clientCompositionTimestamp,
4146 FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
4147 // Update the SurfaceFrames in the drawing state
4148 if (mDrawingState.bufferSurfaceFrameTX) {
4149 mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
4150 }
4151 for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
4152 surfaceFrame->setGpuComposition();
4153 }
4154 }
4155
4156 std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
4157 if (frameReadyFence->isValid()) {
4158 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
4159 } else {
4160 // There was no fence for this frame, so assume that it was ready
4161 // to be presented at the desired present time.
4162 mFrameTracker.setFrameReadyTime(desiredPresentTime);
4163 }
4164
4165 if (display) {
Ady Abrahamace3d052022-11-17 16:25:05 -08004166 const Fps refreshRate = display->refreshRateSelector().getActiveMode().fps;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004167 const std::optional<Fps> renderRate =
4168 mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
4169
Alec Mouri7c1d8b52023-08-29 20:14:46 +00004170 const auto vote = frameRateToSetFrameRateVotePayload(getFrameRateForLayerTree());
Patrick Williamsbb25f802022-08-30 23:02:34 +00004171 const auto gameMode = getGameMode();
4172
4173 if (presentFence->isValid()) {
4174 mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
4175 refreshRate, renderRate, vote, gameMode);
4176 mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
4177 presentFence,
4178 FrameTracer::FrameEvent::PRESENT_FENCE);
4179 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
4180 } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
4181 displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Dominik Laskowskidc2bb802022-09-28 16:02:59 -04004182 // The HWC doesn't support present fences, so use the present timestamp instead.
4183 const nsecs_t presentTimestamp =
4184 mFlinger->getHwComposer().getPresentTimestamp(*displayId);
4185
4186 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
4187 const nsecs_t vsyncPeriod = display->getVsyncPeriodFromHWC();
4188 const nsecs_t actualPresentTime = now - ((now - presentTimestamp) % vsyncPeriod);
4189
Patrick Williamsbb25f802022-08-30 23:02:34 +00004190 mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
4191 refreshRate, renderRate, vote, gameMode);
4192 mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
4193 mCurrentFrameNumber, actualPresentTime,
4194 FrameTracer::FrameEvent::PRESENT_FENCE);
4195 mFrameTracker.setActualPresentTime(actualPresentTime);
4196 }
4197 }
4198
4199 mFrameTracker.advanceFrame();
4200 mBufferInfo.mFrameLatencyNeeded = false;
4201}
4202
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004203bool Layer::willReleaseBufferOnLatch() const {
4204 return !mDrawingState.buffer && mBufferInfo.mBuffer;
4205}
4206
Patrick Williamsbb25f802022-08-30 23:02:34 +00004207bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
Vishnu Naird47bcee2023-02-24 18:08:51 +00004208 const bool bgColorOnly = mDrawingState.bgColorLayer != nullptr;
4209 return latchBufferImpl(recomputeVisibleRegions, latchTime, bgColorOnly);
4210}
4211
4212bool Layer::latchBufferImpl(bool& recomputeVisibleRegions, nsecs_t latchTime, bool bgColorOnly) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004213 ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
4214 getDrawingState().frameNumber);
4215
4216 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
4217
4218 if (refreshRequired) {
4219 return refreshRequired;
4220 }
4221
4222 // If the head buffer's acquire fence hasn't signaled yet, return and
4223 // try again later
4224 if (!fenceHasSignaled()) {
4225 ATRACE_NAME("!fenceHasSignaled()");
4226 mFlinger->onLayerUpdate();
4227 return false;
4228 }
Vishnu Naird47bcee2023-02-24 18:08:51 +00004229 updateTexImage(latchTime, bgColorOnly);
Patrick Williamsbb25f802022-08-30 23:02:34 +00004230
4231 // Capture the old state of the layer for comparisons later
4232 BufferInfo oldBufferInfo = mBufferInfo;
4233 const bool oldOpacity = isOpaque(mDrawingState);
4234 mPreviousFrameNumber = mCurrentFrameNumber;
4235 mCurrentFrameNumber = mDrawingState.frameNumber;
4236 gatherBufferInfo();
4237
Vishnu Nair7ee4f462023-04-19 09:54:09 -07004238 if (mBufferInfo.mBuffer) {
4239 // We latched a buffer that will be presented soon. Clear the previously presented layer
4240 // stack list.
4241 mPreviouslyPresentedLayerStacks.clear();
4242 }
4243
4244 if (mDrawingState.buffer == nullptr) {
4245 const bool bufferReleased = oldBufferInfo.mBuffer != nullptr;
4246 recomputeVisibleRegions = bufferReleased;
4247 return bufferReleased;
4248 }
4249
Patrick Williamsbb25f802022-08-30 23:02:34 +00004250 if (oldBufferInfo.mBuffer == nullptr) {
4251 // the first time we receive a buffer, we need to trigger a
4252 // geometry invalidation.
4253 recomputeVisibleRegions = true;
4254 }
4255
4256 if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
4257 (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
4258 (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
4259 (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
4260 recomputeVisibleRegions = true;
4261 }
4262
4263 if (oldBufferInfo.mBuffer != nullptr) {
4264 uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
4265 uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
4266 if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
4267 bufHeight != oldBufferInfo.mBuffer->getHeight()) {
4268 recomputeVisibleRegions = true;
4269 }
4270 }
4271
4272 if (oldOpacity != isOpaque(mDrawingState)) {
4273 recomputeVisibleRegions = true;
4274 }
4275
4276 return true;
4277}
4278
4279bool Layer::hasReadyFrame() const {
4280 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
4281}
4282
4283bool Layer::isProtected() const {
4284 return (mBufferInfo.mBuffer != nullptr) &&
4285 (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
4286}
4287
Patrick Williamsbb25f802022-08-30 23:02:34 +00004288void Layer::latchAndReleaseBuffer() {
4289 if (hasReadyFrame()) {
4290 bool ignored = false;
4291 latchBuffer(ignored, systemTime());
4292 }
4293 releasePendingBuffer(systemTime());
4294}
4295
4296PixelFormat Layer::getPixelFormat() const {
4297 return mBufferInfo.mPixelFormat;
4298}
4299
4300bool Layer::getTransformToDisplayInverse() const {
4301 return mBufferInfo.mTransformToDisplayInverse;
4302}
4303
4304Rect Layer::getBufferCrop() const {
4305 // this is the crop rectangle that applies to the buffer
4306 // itself (as opposed to the window)
4307 if (!mBufferInfo.mCrop.isEmpty()) {
4308 // if the buffer crop is defined, we use that
4309 return mBufferInfo.mCrop;
4310 } else if (mBufferInfo.mBuffer != nullptr) {
4311 // otherwise we use the whole buffer
4312 return mBufferInfo.mBuffer->getBounds();
4313 } else {
4314 // if we don't have a buffer yet, we use an empty/invalid crop
4315 return Rect();
4316 }
4317}
4318
4319uint32_t Layer::getBufferTransform() const {
4320 return mBufferInfo.mTransform;
4321}
4322
4323ui::Dataspace Layer::getDataSpace() const {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004324 return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
4325}
4326
Alec Mouri89f5d4e2023-10-20 17:12:49 +00004327bool Layer::isFrontBuffered() const {
4328 if (mBufferInfo.mBuffer == nullptr) {
4329 return false;
4330 }
4331
4332 return mBufferInfo.mBuffer->getUsage() & AHARDWAREBUFFER_USAGE_FRONT_BUFFER;
4333}
4334
Patrick Williamsbb25f802022-08-30 23:02:34 +00004335ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
4336 ui::Dataspace updatedDataspace = dataspace;
4337 // translate legacy dataspaces to modern dataspaces
4338 switch (dataspace) {
Alec Mouri74c7ae12023-03-26 02:57:47 +00004339 // Treat unknown dataspaces as V0_sRGB
4340 case ui::Dataspace::UNKNOWN:
Patrick Williamsbb25f802022-08-30 23:02:34 +00004341 case ui::Dataspace::SRGB:
4342 updatedDataspace = ui::Dataspace::V0_SRGB;
4343 break;
4344 case ui::Dataspace::SRGB_LINEAR:
4345 updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
4346 break;
4347 case ui::Dataspace::JFIF:
4348 updatedDataspace = ui::Dataspace::V0_JFIF;
4349 break;
4350 case ui::Dataspace::BT601_625:
4351 updatedDataspace = ui::Dataspace::V0_BT601_625;
4352 break;
4353 case ui::Dataspace::BT601_525:
4354 updatedDataspace = ui::Dataspace::V0_BT601_525;
4355 break;
4356 case ui::Dataspace::BT709:
4357 updatedDataspace = ui::Dataspace::V0_BT709;
4358 break;
4359 default:
4360 break;
4361 }
4362
4363 return updatedDataspace;
4364}
4365
4366sp<GraphicBuffer> Layer::getBuffer() const {
4367 return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
4368}
4369
Vishnu Nairb76d99a2023-03-19 18:22:31 -07004370void Layer::setTransformHintLegacy(ui::Transform::RotationFlags displayTransformHint) {
4371 mTransformHintLegacy = getFixedTransformHint();
4372 if (mTransformHintLegacy == ui::Transform::ROT_INVALID) {
4373 mTransformHintLegacy = displayTransformHint;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004374 }
Vishnu Nair71fcf912022-10-18 09:14:20 -07004375 mSkipReportingTransformHint = false;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004376}
4377
4378const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
4379 return mBufferInfo.mBuffer;
4380}
4381
4382bool Layer::setColor(const half3& color) {
Vishnu Nairbbceb462022-10-10 04:52:13 +00004383 if (mDrawingState.color.rgb == color) {
Patrick Williamsbb25f802022-08-30 23:02:34 +00004384 return false;
4385 }
4386
4387 mDrawingState.sequence++;
Vishnu Nairbbceb462022-10-10 04:52:13 +00004388 mDrawingState.color.rgb = color;
Patrick Williamsbb25f802022-08-30 23:02:34 +00004389 mDrawingState.modified = true;
4390 setTransactionFlags(eTransactionNeeded);
4391 return true;
4392}
4393
4394bool Layer::fillsColor() const {
4395 return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
4396 mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
4397}
4398
4399bool Layer::hasBlur() const {
4400 return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
4401}
4402
Vishnu Nairba354102022-08-01 00:14:18 +00004403void Layer::updateSnapshot(bool updateGeometry) {
4404 if (!getCompositionEngineLayerFE()) {
4405 return;
4406 }
4407
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004408 auto* snapshot = editLayerSnapshot();
Vishnu Nairba354102022-08-01 00:14:18 +00004409 if (updateGeometry) {
4410 prepareBasicGeometryCompositionState();
4411 prepareGeometryCompositionState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004412 snapshot->roundedCorner = getRoundedCornerState();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004413 snapshot->transformedBounds = mScreenBounds;
4414 if (mEffectiveShadowRadius > 0.f) {
4415 snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
4416
4417 // Note: this preserves existing behavior of shadowing the entire layer and not cropping
4418 // it if transparent regions are present. This may not be necessary since shadows are
4419 // typically cast by layers without transparent regions.
4420 snapshot->shadowSettings.boundaries = mBounds;
4421
4422 const float casterAlpha = snapshot->alpha;
4423 const bool casterIsOpaque =
4424 ((mBufferInfo.mBuffer != nullptr) && isOpaque(mDrawingState));
4425
4426 // If the casting layer is translucent, we need to fill in the shadow underneath the
4427 // layer. Otherwise the generated shadow will only be shown around the casting layer.
4428 snapshot->shadowSettings.casterIsTranslucent = !casterIsOpaque || (casterAlpha < 1.0f);
4429 snapshot->shadowSettings.ambientColor *= casterAlpha;
4430 snapshot->shadowSettings.spotColor *= casterAlpha;
4431 }
4432 snapshot->shadowSettings.length = mEffectiveShadowRadius;
Vishnu Nairba354102022-08-01 00:14:18 +00004433 }
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004434 snapshot->contentOpaque = isOpaque(mDrawingState);
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004435 snapshot->layerOpaqueFlagSet =
4436 (mDrawingState.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque;
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004437 sp<Layer> p = mDrawingParent.promote();
4438 if (p != nullptr) {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004439 snapshot->parentTransform = p->getTransform();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004440 } else {
Vishnu Nair8fc721b2022-12-22 20:06:32 +00004441 snapshot->parentTransform.reset();
Vishnu Nairbedb44b2022-08-02 21:47:40 +00004442 }
4443 snapshot->bufferSize = getBufferSize(mDrawingState);
4444 snapshot->externalTexture = mBufferInfo.mBuffer;
Vishnu Naire14c6b32022-08-06 04:20:15 +00004445 snapshot->hasReadyFrame = hasReadyFrame();
Vishnu Nairba354102022-08-01 00:14:18 +00004446 preparePerFrameCompositionState();
4447}
4448
Vishnu Naire14c6b32022-08-06 04:20:15 +00004449void Layer::updateChildrenSnapshots(bool updateGeometry) {
4450 for (const sp<Layer>& child : mDrawingChildren) {
4451 child->updateSnapshot(updateGeometry);
4452 child->updateChildrenSnapshots(updateGeometry);
4453 }
4454}
4455
Vishnu Nair0a4fb002022-08-08 02:40:42 +00004456void Layer::updateMetadataSnapshot(const LayerMetadata& parentMetadata) {
4457 mSnapshot->layerMetadata = parentMetadata;
4458 mSnapshot->layerMetadata.merge(mDrawingState.metadata);
4459 for (const sp<Layer>& child : mDrawingChildren) {
4460 child->updateMetadataSnapshot(mSnapshot->layerMetadata);
4461 }
4462}
4463
4464void Layer::updateRelativeMetadataSnapshot(const LayerMetadata& relativeLayerMetadata,
4465 std::unordered_set<Layer*>& visited) {
4466 if (visited.find(this) != visited.end()) {
4467 ALOGW("Cycle containing layer %s detected in z-order relatives", getDebugName());
4468 return;
4469 }
4470 visited.insert(this);
4471
4472 mSnapshot->relativeLayerMetadata = relativeLayerMetadata;
4473
4474 if (mDrawingState.zOrderRelatives.empty()) {
4475 return;
4476 }
4477 LayerMetadata childRelativeLayerMetadata = mSnapshot->relativeLayerMetadata;
4478 childRelativeLayerMetadata.merge(mSnapshot->layerMetadata);
4479 for (wp<Layer> weakRelative : mDrawingState.zOrderRelatives) {
4480 sp<Layer> relative = weakRelative.promote();
4481 if (!relative) {
4482 continue;
4483 }
4484 relative->updateRelativeMetadataSnapshot(childRelativeLayerMetadata, visited);
4485 }
4486}
4487
Chavi Weingarten328a8312023-01-26 21:17:52 +00004488bool Layer::setTrustedPresentationInfo(TrustedPresentationThresholds const& thresholds,
Chavi Weingarten076acac2023-01-19 17:20:43 +00004489 TrustedPresentationListener const& listener) {
4490 bool hadTrustedPresentationListener = hasTrustedPresentationListener();
4491 mTrustedPresentationListener = listener;
4492 mTrustedPresentationThresholds = thresholds;
4493 bool haveTrustedPresentationListener = hasTrustedPresentationListener();
4494 if (!hadTrustedPresentationListener && haveTrustedPresentationListener) {
4495 mFlinger->mNumTrustedPresentationListeners++;
4496 } else if (hadTrustedPresentationListener && !haveTrustedPresentationListener) {
4497 mFlinger->mNumTrustedPresentationListeners--;
4498 }
Chavi Weingarten328a8312023-01-26 21:17:52 +00004499
4500 // Reset trusted presentation states to ensure we start the time again.
4501 mEnteredTrustedPresentationStateTime = -1;
4502 mLastReportedTrustedPresentationState = false;
4503 mLastComputedTrustedPresentationState = false;
4504
4505 // If there's a new trusted presentation listener, the code needs to go through the composite
4506 // path to ensure it recomutes the current state and invokes the TrustedPresentationListener if
4507 // we're already in the requested state.
4508 return haveTrustedPresentationListener;
Chavi Weingarten076acac2023-01-19 17:20:43 +00004509}
4510
Vishnu Naira156f482023-02-22 00:23:38 +00004511void Layer::updateLastLatchTime(nsecs_t latchTime) {
4512 mLastLatchTime = latchTime;
4513}
4514
Arthur Hung69f95222023-10-04 07:39:02 +00004515void Layer::setIsSmallDirty(const Region& damageRegion,
4516 const ui::Transform& layerToDisplayTransform) {
4517 mSmallDirty = false;
Jerry Chang36678002023-11-29 16:56:17 +00004518 if (!mFlinger->mScheduler->supportSmallDirtyDetection(mOwnerAppId)) {
Arthur Hungc70bee22023-06-02 01:35:52 +00004519 return;
4520 }
4521
4522 if (mWindowType != WindowInfo::Type::APPLICATION &&
4523 mWindowType != WindowInfo::Type::BASE_APPLICATION) {
4524 return;
4525 }
Arthur Hung69f95222023-10-04 07:39:02 +00004526
4527 Rect bounds = damageRegion.getBounds();
Arthur Hungc70bee22023-06-02 01:35:52 +00004528 if (!bounds.isValid()) {
4529 return;
4530 }
4531
Arthur Hung69f95222023-10-04 07:39:02 +00004532 // Transform to screen space.
4533 bounds = layerToDisplayTransform.transform(bounds);
4534
Arthur Hungc70bee22023-06-02 01:35:52 +00004535 // If the damage region is a small dirty, this could give the hint for the layer history that
4536 // it could suppress the heuristic rate when calculating.
Tony Huangf3621102023-09-04 17:14:22 +08004537 mSmallDirty = mFlinger->mScheduler->isSmallDirtyArea(mOwnerAppId,
Tony Huang9ac5e6e2023-08-24 09:01:44 +00004538 bounds.getWidth() * bounds.getHeight());
Arthur Hungc70bee22023-06-02 01:35:52 +00004539}
4540
Arthur Hung69f95222023-10-04 07:39:02 +00004541void Layer::setIsSmallDirty(frontend::LayerSnapshot* snapshot) {
4542 setIsSmallDirty(snapshot->surfaceDamage, snapshot->localTransform);
4543 snapshot->isSmallDirty = mSmallDirty;
4544}
4545
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -07004546} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004547
4548#if defined(__gl_h_)
4549#error "don't include gl/gl.h in this file"
4550#endif
4551
4552#if defined(__gl2_h_)
4553#error "don't include gl2/gl2.h in this file"
4554#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08004555
4556// TODO(b/129481165): remove the #pragma below and fix conversion issues
4557#pragma clang diagnostic pop // ignored "-Wconversion"